+ 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!

3rd Dec 2016, 2:47 PM
alex
alex - avatar
4 Respostas
+ 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) "
3rd Dec 2016, 2:58 PM
Wen Qin
Wen Qin - avatar
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++);
3rd Dec 2016, 3:25 PM
DFX
DFX - avatar
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
3rd Dec 2016, 3:32 PM
Ash Ketchum
Ash Ketchum - avatar
0
a fix for the bottom one is to start with int num = -1
22nd Dec 2016, 9:45 PM
Tanel Helmik
Tanel Helmik - avatar