Note: This is my first time using "Stack Overflow" and I am relatively new to C#
(please excuse my poor programming skills at the moment)
My Code:
static void Main(string[] args)
{
Challenge(5, 12);
}
static void Challenge(int num1, int num2)
{
//finds the sum of the two variables
int sum = num1 + num2;
Console.WriteLine("The sum of {0} and {1} is...\n{2}", num1, num2, sum);
bool isDivisible = true;
//checks if divisible by 5 and sets a value for 'isDivisible'
if ((sum % 10 == 5) || (sum % 10 == 0))
{
Console.WriteLine("\nThe sum is divisible by 5!");
isDivisible = true;
}
else if ((sum % 10 != 5) || (sum % 10 != 0))
{
Console.WriteLine("\nThe sum is not divisible by 5!");
isDivisible = false;
}
//depending on value of 'isDivisible', returns certain functions
if (isDivisible == true)
{
Console.WriteLine("This value is usable.");
Console.WriteLine("\n\nThe remaining usable values are: ");
for (int newVal = sum + 1; newVal <= 55; newVal++) // '+ 1' added to make sure 'sum' is not printed again
{
if ((newVal % 10 == 5) || (newVal % 10 == 0))
{
Console.WriteLine(newVal);
}
}
}
else if (isDivisible == false)
{
Console.WriteLine("This value is not usable.");
Console.WriteLine("\n\nThese values are considered usable: ");
for (int newVal = 0; newVal <= 55; newVal++)
{
if ((newVal % 10 == 5) || (newVal % 10 == 0))
{
Console.WriteLine(newVal);
}
}
}
Console.ReadLine();
}
I viewed some articles online, as well as the "Stack Overflow" post: Why compile error "Use of unassigned local variable"? . After learning that local variables are not initialized (and must be given a value), I set my bool value for "isDivisible" equal to true by default.
Question:
Is there a better way to define a local variable that is of Boolean value (at least in the case of the program I am trying to run here)?
Thanks!
Your condition in the else if is wrong, it's not the complement of the first condition, so it doesn't make sense. The correct complement would be:
else if ((sum % 10 != 5) && (sum % 10 != 0))
However, you don't need to use an else if at all, you can just use an else as you want to catch every case that is not caught by the first condition. That also means that you don't have to initialise the boolean variable, as the compiler can see that it always will be set by one of the code blocks:
bool isDivisible;
//checks if divisible by 5 and sets a value for 'isDivisible'
if ((sum % 10 == 5) || (sum % 10 == 0))
{
Console.WriteLine("\nThe sum is divisible by 5!");
isDivisible = true;
}
else
{
Console.WriteLine("\nThe sum is not divisible by 5!");
isDivisible = false;
}
Side note: Instead of (sum % 10 == 5) || (sum % 10 == 0) you could just use sum % 5 == 0.
Side note 2: You don't need to compare a boolean variable to true, you can just use it as a condition. Also, you don't need the else if there either. Instead of this:
if (isDivisible == true)
{
...
}
else if (isDivisible == false)
{
...
}
you can use:
if (isDivisible)
{
...
}
else
{
...
}
Comparison expressions in C# will return a boolean value indicating whether or not they are true. So you could simplify your initial assignment to:
bool isDivisible = ((sum % 10 == 5) || (sum % 10 == 0));
Instead of explicitly setting it to true or false. Then your variable would always be set.
This doesn't work for all cases. Sometimes, it is difficult to reduce the comparison operation to a simple expression. But, it is often a handy way to initialize bools.
Related
Im doing a C# program that is suppose to take an amount from 0-99 (amount of change given back) and from that the program should put the change in the correct positions. A example is if I enter:
Amount of change given back: 68
it should read as:
Quarters 2
Dimes 1
Nickles 1
Pennies 3
I am using a Windows form application in visual studios 2015.
Whenever i enter the amount of 1, it should be 1 penny but it gives it 2, same for dimes nickles and quarters. anything else it works just fine.
This is what my code looks like:
private void calcButton_Click(object sender, EventArgs e){
//declare variables
const int QUARTERS = 25;
const int DIMES = 10;
const int NICKELS = 5;
const int PENNIES = 1;
int changeVal = 0;
//validations
if (int.TryParse(changeTextBox.Text, out changeVal)){
if (changeVal > 0 && changeVal < 100){
//calcs each value with the remainder operator divided by each change amount
int quarterVal = changeVal / QUARTERS;
int dimeVal = ((changeVal % QUARTERS) / DIMES);
int nickelVal = (((changeVal % QUARTERS) % DIMES) / NICKELS);
int pennyVal = ((((changeVal % QUARTERS) % DIMES) % NICKELS) / PENNIES);
//if statements to put each coin in each specific value variable
if (changeVal == QUARTERS){
quarterVal++;
changeVal = changeVal - QUARTERS;
}
else if (changeVal == DIMES){
dimeVal++;
changeVal = changeVal - DIMES;
}
else if (changeVal == NICKELS){
nickelVal++;
changeVal = changeVal - NICKELS;
}
else if (changeVal == PENNIES){
pennyVal++;
changeVal -= changeVal - PENNIES;
}
//display
quartersLabel.Text = quarterVal.ToString();
dimesLabel.Text = dimeVal.ToString();
nickelsLabel.Text = nickelVal.ToString();
penniesLabel.Text = pennyVal.ToString();
}
//error message
else{
MessageBox.Show("You have to enter a numeric value greater than 0 and less than 100");
}
}
//error message
else{
MessageBox.Show("Please enter a numeric value");
}
}
If you can tell me what I'm doing wrong that would be very helpful!
You are comparing your ChangeVal to the face value of the coins. and then Incrementing it when they are equal,
This Section only runs when your changeVal is equal to the facevalue of the coin
hence 1, 5, 10, 25 all produce a double count. Just remove the section below.
if (changeVal == QUARTERS)
{
quarterVal++;
changeVal = changeVal - QUARTERS;
}
else if (changeVal == DIMES)
{
dimeVal++;
changeVal = changeVal - DIMES;
}
else if (changeVal == NICKELS)
{
nickelVal++;
changeVal = changeVal - NICKELS;
}
else if (changeVal == PENNIES)
{
pennyVal++;
changeVal -= changeVal - PENNIES;
}
You are already calculating the number of coins required with the code below:
int quarterVal = changeVal / QUARTERS;
etc....
But you are then incrementing this by 1 if the changeVal is equal to one of your predefined constants.
Basically, you don't need the 4 if statements that increment the counts when the value entered is an exact match for one of your defined constants.
I'm building a method to calculate shipping cost. I've already validated the data type to an integer. As long as the integer entered is greater than 0, the logic works correctly. When the number entered is less than one, an error message is generated and repeats the request for a larger whole integer. Okay so far.
However, after the error message asks for a valid integer, the data entered is ignored and the calculation is incorrect. How can I repeat the request until the user enters a number greater than 0 and then perform the desired calculation with it? Thanks!
static double CalculateShipping(int items, double shippingCharge)
{
if (items == 1)
shippingCharge = 2.99;
else if (items > 1 && items < 6)
shippingCharge = 2.99 + 1.99 * (items - 1);
else if (items > 5 && items < 15)
shippingCharge = 10.95 + 1.49 * (items - 5);
else if (items > 14)
shippingCharge = 24.36 + 0.99 * (items - 14);
else
{
Console.WriteLine("You must order at least 1 item.");
Console.WriteLine();
Console.Write("Please enter a whole number greater than zero: ");
items = Console.Read();
}
return shippingCharge;
}
static int ReadItemsCountFromInput()
{
while(true)
{
Console.WriteLine("enter items count: ");
string s = Console.ReadLine();
int r;
if(int.TryParse(s, out r) && r > 0)
{
return r;
}
else
{
Console.WriteLine("you should enter number greater than zero");
}
}
}
static double CalculateShipping(int items, double shippingCharge)
{
if (items == 1)
shippingCharge = 2.99;
else if (items > 1 && items < 6)
shippingCharge = 2.99 + 1.99 * (items - 1);
else if (items > 5 && items < 15)
shippingCharge = 10.95 + 1.49 * (items - 5);
else if (items > 14)
shippingCharge = 24.36 + 0.99 * (items - 14);
return shippingCharge;
}
static void Main()
{
int items = ReadItemsCountFromInput();
double result = CalculateShipping(items, 0);
Console.WriteLine("Shipping: {0}", result);
}
Wrap your Console statements in a While loop. Something like...
bool MyValidationFlag = false;
While MyValidationFlag == False
{
// Prompt User
If (UserInput is an integer > 1)
MyValidationFlag = True
else
MyValidationFlag = False
}
(You might also want to throw in some kind of check for an "escape" value in case the user wants to quit.)
I want to find whether a number is prime or not by limiting the number of iterations as much as possible.The following program was suggested in a blog.I can understand these parts of the code..
public static bool Isprime(long i)
{
if (i == 1)
{
return false;
}
else if (i < 4)
{
return true;
}
else if (i % 2 == 0)
{
return false;
}
else if (i < 9)
{
return true;
}
else if (i % 3 == 0)
{
return false;
}
But I don't understand why f is incremented by 6.
else
{
double r = Math.Floor(Math.Sqrt(i));
int f = 5;
while (f <= r)
{
if (i % f == 0) { return false; }
if (i % (f + 2) == 0) { return false; }
f = f + 6;
}
return true;
}
}
Because every prime number (except 2 and 3) is of the form 6k +/- 1
Every other number cannot be prime, because they are divisible by 2 or 3
Also, a few modifications to your method:
public static bool Isprime(long i)
{
if (i < 2)
{
return false;
}
else if (i < 4)
{
return true;
}
else if ((i & 1) == 0)
{
return false;
}
else if (i < 9)
{
return true;
}
else if (i % 3 == 0)
{
return false;
}
else
{
double r = Math.Floor(Math.Sqrt(i));
int f = 5;
while (f <= r)
{
if (i % f == 0) { return false; }
if (i % (f + 2) == 0) { return false; }
f = f + 6;
}
return true;
}
}
You didn't check for negative numbers
To check if a number is even, (i & 1) == 0 is more efficient. Unfortunately, there is no such trick for i % 3
Though a good answer has been accepted, and I've offered another answer previously, I offer a new method for ulong that does things slightly different that may help explain why the 6 is important. This uses a for loop rather than a while.
UPDATE: I have expanded upon this answer with a version that runs in parallel threads. See this CodeReview Link for the parallel version.
Edit: added quick elimination of many composites
public static bool IsPrime6(ulong number)
{
// Get the quick checks out of the way.
if (number < 2) { return false; }
// Dispense with multiples of 2 and 3.
if (number % 2 == 0) { return (number == 2); }
if (number % 3 == 0) { return (number == 3); }
// Another quick check to eliminate known composites.
// http://programmers.stackexchange.com/questions/120934/best-and-most-used-algorithm-for-finding-the-primality-of-given-positive-number/120963#120963
if (!( ((number - 1) % 6 == 0) || ((number + 1) % 6 == 0)) )
{
return false;
}
// Quick checks are over. Number is at least POSSIBLY prime.
// Must iterate to determine the absolute answer.
// We loop over 1/6 of the required possible factors to check,
// but since we check twice in each iteration, we are actually
// checking 1/3 of the possible divisors. This is an improvement
// over the typical naive test of odds only which tests 1/2
// of the factors.
// Though the whole number portion of the square root of ulong.MaxValue
// would fit in a uint, there is better performance inside the loop
// if we don't need to implicitly cast over and over a few million times.
ulong root = (ulong)(uint)Math.Sqrt(number);
// Corner Case: Math.Sqrt error for really HUGE ulong.
if (root == 0) root = (ulong)uint.MaxValue;
// Start at 5, which is (6k-1) where k=1.
// Increment the loop by 6, which is same as incrementing k by 1.
for (ulong factor = 5; factor <= root; factor += 6)
{
// Check (6k-1)
if (number % factor == 0) { return false; }
// Check (6k+1)
if (number % (factor + 2UL) == 0) { return false; }
}
return true;
}
This is based on math theorem that states every prime number > 3 can be represented as (6k+/-1). But that doesn't mean every number of the form (6k+/1) is a prime.
The correct converse would be that if you have a number that is not represented as (6k+/-1) then that number cannot be prime.
For later use with modulo operator, (6k-1) is equivalent to (6(k+1)+5).
Thus our intent is to start the loop at 5, i.e. the first occurrence of (6k-1) for k=1, do checks inside the loop for (6k-1) and (6k+1), and then increment by 6 for another iteration through the loop.
In short, iterating by adding 6 to the previous factor is the same as adding 1 to k.
Explanation of Ugly Explicit Casts
I took out the UL designators after further tests showed that for this algorithm they made little difference.
Tests
To run some tests, you could try:
const long Largest63bitPrime = 9223372036854775783L;
const ulong Largest64bitPrime = 18446744073709551557UL;
On my laptop, it take 13 seconds for the largest 63-bit prime, and 18 seconds for the largest 64-bit prime. Surprisingly, the version above is 1.5 seconds faster against (ulong)Largest63bitPrime than using my other answer's long specific version that employs a while.
Quick Elimination of Many Composites
Based on comments to the OP itself, I added a new check. It’s kind of difficult to find the worst case scenario, or best time-savings case here. I tested it against Largest64bitPrime + 6. Without the check, it was 14.2 microseconds compared to 1.1 microseconds with it. But's in now included so that the algorithm is considered complete.
See #Dennis_E's answer and explanation, which I gave +1. I offer 2 variations on his. There could be 100's of millions of implicit casts being done by these statements:
double r = Math.Floor(Math.Sqrt(i));
int f = 5;
while (f <= r)
The loop conditional implicitly cast f to a double repeatedly. That obscures where some performance can be degraded. While the whole number portion of the square root of long.MaxValue could fit in a uint, to boost performance you are better off keeping every as long. Now performance inside the loop will suffer from any implicit casts.
public static bool Isprime1(long number)
{
// Get the quick checks out of the way.
if (number < 2) { return false; }
// 2 and 3 are prime.
if (number < 4) { return true; }
// besides 2, any other even number, i.e. any other multiple of 2, is not prime.
if ((number % 2) == 0) { return false; }
// 5 and 7 are also prime.
if (number < 9) { return true; }
// multiples of 3 are not prime.
if (number % 3 == 0) { return false; }
// Quick checks are over. Must iterate to find the answer.
// Though the whole number portion of the square root of long.MaxValue
// would fit in a uint, there is better performance inside the loop
// if we don't need to implicitly cast over and over a few million times.
long root = (long)Math.Sqrt(number);
long factor = 5;
while (factor <= root)
{
if (number % factor == 0L) { return false; }
if (number % (factor + 2L) == 0L) { return false; }
factor = factor + 6L;
}
return true;
}
All the above extends the answer by #Dennis_E. Another variation would be:
public static bool Isprime2(long number)
{
// Get the quick checks out of the way.
if (number < 2) { return false; }
// 2, 3, 5, & 7 are prime.
if ((new long[] { 2L, 3L, 5L, 7L }).Contains(number)) { return true; }
// any other multiples of 2 are not prime.
if ((number % 2) == 0) { return false; }
// any other multiples of 3 are not prime.
if (number % 3 == 0) { return false; }
// Quick checks are over. Must iterate to find the answer.
// Though the whole number portion of the square root of long.MaxValue
// would fit in a uint, there is better performance inside the loop
// if we don't need to implicitly cast over and over a few million times.
long root = (long)Math.Sqrt(number);
long factor = 5;
while (factor <= root)
{
if (number % factor == 0L) { return false; }
if (number % (factor + 2L) == 0L) { return false; }
factor = factor + 6L;
}
return true;
}
public class Prime {
public static void main(String[] args) {
Scanner get=new Scanner(System.in);
int n;
System.out.println("Enter a number to find its primality");
n=get.nextInt();
System.out.println(n+" isPRime? "+isPrime(Math.ceil(Math.sqrt(n)),n));
}
private static boolean isPrime(double n,int k){
boolean isPrim=true;
int p=(int)n;
for(int i=2;i<=p;i++){
boolean iprime=false;
for(int j=2;j<i/2;j++){
if(i%j==0){
iprime=true;
break;
}
}
if(!iprime && k>i){
if(k%i==0){
isPrim=false;
return isPrim;
}
}
}
return isPrim;
}
}
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
When solving "fizz-buzz" in C# using a "while" loop, I found out that first I should find the multiples of both 3 and 5 (multiples of 15) and then go to the multiples of 3 and 5 like below.
int myval = 0;
while (myval < 100)
{
myval = myval + 1;
if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz");
}
else if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else
{
listBox1.Items.Add(myval);
}
}
But if I write the code to filter multiples of 3 and 5 first and then go to the multiples of both 3 and 5 (multiples of 15) like below the end result only shows the fizz (multiples of 3) and buzz (multiples of 5) without fizz-buzz (multiples of both 3 and 5). Does anyone know what's the reason for this even IDE doesn't show me any errors.
myval = 0;
while (myval < 100)
{
myval = myval + 1;
if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz"); // for multiples of both 3 and 5
}
else
{
listBox1.Items.Add(myval);
}
}
Because it satisfies the first two conditions. So it will never hit your third else statement.
This boils down to the fact that if-else statements are processed sequentially. As soon as a condition that evaluates to true is encountered, the other else if clauses are skipped.
Suppose that a and b are both true. When you write
if (a) {
Foo1();
}
else if (b) {
Foo2();
}
you do not execute both Foo1 and Foo2. Since a is true, Foo1 executes and b is not even evaluated.
Now consider your problem. Consider the number 15. All three candidate divisors, 3, 5 and 15, divide into that number.
if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz"); // for multiples of both 3 and 5
}
else
{
listBox1.Items.Add(myval);
}
Since the multiples of 15 are also multiples of 3 (and 5), you will never even reach the myval % 15 == 0 test for multiples of 15.
It's because something divisible by 3 and 5 is also divisible by 3 and by 5. If you catch either of those conditions first, the later condition is never checked.
You could also write it like so:
var resultString = "";
if(myval % 3 == 0) resultString += "fizz";
if(myval % 5 == 0) resultString += "buzz";
if(myval % 5 != 0 && myval % 3 != 0) resultString += myval;
listBox1.Items.Add(resultString);
This will print all conditions without needing a separate check for % 15.
Also, I know this wasn't the original question, but typically someone wouldn't use a while loop to cycle through a range of numbers. Use a for loop for that:
for( int myval = 0; myval <= 100; myval++)
{
// code goes here
}
I always solved this a slightly different way: by constructing the string to add.
for (int myVal = 0; myVal < 100; myVal++)
{
string fb = "";
if ((myVal % 3) == 0) { fb = "fizz"; }
if ((myVal % 5) == 0) { fb += "buzz"; }
// Handle the case where it isn't divisible by 3 or 5:
if (fb == "") { fb = myVal.ToString(); }
// "output" the string.
listBox1.Items.Add(fb);
}
You can use this method to fill your Listbox:
foreach (int i in Enumerable.Range(1,100)){
string str = null;
listBox1.Items.Add((str = (i % 3 == 0 ? "fizz" : "")
+ (i % 5 == 0 ? "buzz" : "")) == ""
? i.ToString() : str );
}
In my program, I think my count variable is not holding the value. What do I do so that it can hold? here`s my code.
static void Main(string[] args)
{
double a;
double count = 0;
Console.WriteLine("Enter the Numbers : ");
for (double i = 1; i <= 10; i++)
{
a = Convert.ToDouble(Console.ReadLine());
if (a % 2 != 0 || a % 3 != 0 || a % 5 != 0)
{
count = count++;
}
//else
//{
// }
Console.ReadLine();
}
Console.WriteLine("The Numbers That Are divisible by 2,3,5 are : " + count);
Console.ReadLine();
}
Your mistake is the line count = count++;. This does not increase count by one. You need to use just count++;.
The expression count++ will increment the value of count by one and then return as the expression's value the original value of count. In this case the increment of count++ happens before the assignment, so count is first incremented by one, but then you assign the value of count++, that is, the original value, to count again, so it does not increase at all.
Your program lists numbers that are not divisible by any of those numbers. If you want to count numbers which aren't divisible by all of them then you need to use if (a % 2 != 0 && a % 3 != 0 && a % 5 != 0) instead. I would also suggest using integers instead of doubles if possible.
Finally, your print statement says numbers that are divisible by 2,3,5, but count is the number of numbers which are not divisible by those numbers.
Edit: Are you entering 10 numbers each time you test? I'm not sure what kind of result you will get if you give a blank input.
Not to add to what jk and David Kanarek said in their answers or what the others the comments on those answers, As pointed out by jk use count+1 instead of count ++ , also a few notes:
1) Your using console.Readline() twice in the loop, so the user will enter 20 inputs but only 10 will be read..
2) Just alittle extra thought on Anton's comment, in your if clause , if you use || your trying to catch any of the conditions being true, in other words:
// a=2
if (a % 2 != 0 || a % 3 != 0 || a % 5 != 0) // False || True || True = True
{
count = count + 1 ;// count will increase
}
on the other hand, using && :
// a=2
if (a % 2 != 0 && a % 3 != 0 && a % 5 != 0) // False && True && True = false
{
count = count + 1 ; //count will not increase
}
A useful Link explaining operators