for(x=0; x<100; x );
printf(“%d”,x);
why it gives 100
(i) Identify bug/bugs in this program segment (ii) Write a correct version of this program segment
I tried
for(x=0; x<100; x ){
printf(“%d”,x);}
ı can see all numbers 0 to 100 but
for(x=0; x<100; x );
printf(“%d”,x);
ı can see only 100 why ? ı dont know the reason
CodePudding user response:
I can see only 100 why? I dont know the reason
Because a semi-colon terminates a statement.
To better understand what's happening, format your code properly. (Better yet, use an IDE which formats the code for you. And do not use a word processor as an IDE. Those fancy quotes in your code are syntax errors.) The original code is this:
for(x=0; x<100; x );
printf("%d",x);
Two statements, unrelated to one another. The first one is a loop, by itself, with no loop body. It repeats, successfully doing nothing 100 times. The second statement outputs a value. Compare that to your corrected code:
for(x=0; x<100; x ) {
printf("%d",x);
}
Now what you have is a loop, the body of which contains one statement. That statement is executed 100 times, each time outputting a value.
Consistently and meaningfully formatting your code for readability is not there to help the compiler. It's there to help you. Keep your code human-readable and you, as a human, will be better able to read and understand it.
CodePudding user response:
for(x=0; x<100; x ); printf(“%d”,x);
There is a semicolon between the for loop and the print. So the print is not in the loop.
x
will be counted from 0 to 100. After the empty loop completes, it will print the last value (100).