+ 2
question about while loop (2 example comparison)
int num = 0; while(num < 6) { Console.WriteLine(num); num++; } int num = 0; while(num++ < 6) Console.WriteLine(num); why the below answer is not 012345? thank you!
4 Antworten
+ 4
Because it is in postfix form, the problem itself is not the loop. It will output 123456 but not 12345 as the num used in the condition is postfix.
If you remember, postfix means to process the line of code first before value is being added. So when 'num' was at '5', the while loop granted access and did (num + 1) before processing it's body as the ++ form used in the condition was a postfix form.
The correct way would be " while(++num < 6) "
0
you increment the variable num in the condition of the while loop, before printing it out. you can use this instead:
int num =0;
while(num<6) Console.WriteLine(num++);
0
You incremented the variable num to 1 in the while loop, and then posted it, causing it to jump right to 1 and go 1,2,3,4,5,6
0
a fix for the bottom one is to start with int num = -1