Hi everyone. I don’t understand why the code below doesn’t work.
I am expecting:
Checking i = 1
Checking i = 2
Checking i = 4
Checking i = 5
Checking i = 7
Checking i = 8
Checking i = 10
The answer is 10.
But I get only:
while the program runs no-stop.
My code is:
[code]#include <stdio.h>
int main(int argc, const char * argv[]) {
printf(“DO-WHILE Loop\n”);
int x = 0;
do
{
if (x % 3 == 0)
{
continue;
}
printf(“Checking i = %d\n”, x);
if (x + 90 == x * x)
{
break;
}
x++;
} while (x < 12);
printf(“The answer is %d.\n”, x);
return 0;
}[/code]
The problem is at the top - you set x = 0 initially.
Then, inside the loop, you continue if x % 3 == 0. the continue keyword causes the code to jump back to the top of the loop immediately.
The result is that the line that increments x (at the bottom of the loop) is never reached, so x never increments, so the loop never stops running, and x stays zero forever.
One potential way to fix the problem would be to keep 0 as the initial value of x, but to move the x++; to the top of the loop, to guarantee that x always increments regardless of what else happens in the loop.
Or, if you want 0 to be checked by the conditionals in the loop, -1 could be the initial value.
Alright. I get your point.
I will put the value of x as -1.
Thanks!