Yu-Hung Chiu
Yu-Hung Chiu

Reputation: 1

beginner on c# on The while Loop

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?

Upvotes: 1

Views: 92

Answers (2)

Safirah
Safirah

Reputation: 375

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

Upvotes: 2

mimre
mimre

Reputation: 92

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.

Upvotes: 0

Related Questions