1
int num = 0;
while(num < 6) 
{
Console.WriteLine(num);
num++; 
}


int num = 0
while(num++ < 6) 
Console.WriteLine(num);

I stuck on this , can't tell the difference, can anyone step by step, plz?

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118

2 Answers2

2

On the first one you're condition is If num is less than 6 keep going on, and then on the loop you add one to num. So the output will be: 0 1 2 3 4 5

On the second case you're condition is the same, because it's only going to increment num after that statment. So the output will be: 1 2 3 4 5 6

If you want it the condition to be If num + 1 is less than 6 keep going on, do while(++num < 6)

More information here

Community
  • 1
  • 1
Safirah
  • 365
  • 6
  • 17
  • 1
    For #2, I would note that since there is only one line of code to execute after the true/false check for the while loop, adding the executed statement the line below the while is the same as using brackets, but can only be applied to the immediately following line. It's hard to explain in words, haha – Mark C. Dec 03 '16 at 14:50
  • @MarkC. I had to double read what you said, but you're right ^^. while(num++ < 6) in this case is the same as while(num < 6){num++; (...) – Safirah Dec 03 '16 at 14:53
0

There is only a difference in printing, as pointed out in the comments. In the first case num is first printed then increased, in the second case it is the other way round.

The first block of code just has a clearer style.

In both cases num starts out as 0. The while loop runs until num < 6. The statement Console.WriteLine(num); prints the current value of num.

The tricky, maybe confusing, part is the num++ statement. It first generates a copy of num, then increases num and returns the copy. If it is used standalone in a line, it simply increases the variable.

In the case of num++ < 6, First a copy of num' of num is created, then num is increased, and the statement num++ < 6 is evaluated with the copy (num' < 6).

The second loop omit the braces { } thus only encompasses the next statement.

mimre
  • 92
  • 1
  • 9