+ 2
Why num++ postfix is used in while loop
in this code after console writeline num++ postfix is used without it compiler gives unlimited 1s and with prefix ++num same 1 to 5 can any describe this why it is used int num= 1; while(num < 6) { Console.WriteLine(num); num++; } /* Outputs 1 2 3 4 5 */
4 Respuestas
+ 7
Hi Shahzaib Jahangir
++ is an increment of one
This is a shortcut of writing:
VariableName = VaraiableName + 1
This means that it adds 1 to a number.
Your example:
In the example num starts at 1
It is less that 6 so the first output is 1
Then num++ same as ‘num + 1’
The value of num is now 2
This is then repeated until the
value of num is not less than 6
+ 2
num++ is used to increase value of num. With increasing, num gets to 6, so condition becomes false and while loop stops.
If num++ was not defined:
1) num would always be 1,
2) num < 6 would be true, so while loop would become infinite.
0
when the only command in the line is an increment, it is irrelevant whether you use prefix or postfix. the difference is visible in other scenarios however
0
("num") string