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);
}
}
You can use this method to fill your
Listbox
: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 totrue
is encountered, the otherelse if
clauses are skipped.Suppose that
a
andb
are bothtrue
. When you writeyou do not execute both
Foo1
andFoo2
. Sincea
istrue
,Foo1
executes andb
is not even evaluated.Now consider your problem. Consider the number 15. All three candidate divisors, 3, 5 and 15, divide into that number.
Since the multiples of
15
are also multiples of3
(and5
), you will never even reach themyval % 15 == 0
test for multiples of15
.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:
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 afor
loop for that:I always solved this a slightly different way: by constructing the string to add.