Reputation: 119
I'm trying out a for loop. I added an if statement to stop the loop once it reaches 30.
I have seen that i <= 10
will run 11 times, since the loop will still run when it reaches 10.
Why does the code below run 11 times (first print line) if there is an if statement that sets i
back to 0 when it reaches 10? Shouldn't it only print 10 asterisks instead of 11 - since it never reaches the 11th loop? Also, the second if
sets i
back to 10, which should let the loop run one more time, through the first if
, which would and then set the i
back to 0?
int j = 0;
for (int i = 0; i <= 10; i++)
{
Console.Write("*");
if (i == 10)
{
j++;
Console.WriteLine("");
i = 0;
}
if (j == 30)
{
i = 10;
}
}
Upvotes: 2
Views: 748
Reputation: 70392
On the first loop, the line has 11 stars, because i
iterates from 0 through 10, which is a total of 11 iterations.
Whenever i
becomes the value 10, j
is incremented, a newline is printed, and i
becomes 0
.
However, when i
is set to 0
within the loop, the loop makes i
iterate from 1 to 10, for a total of 10 iterations.
This is because i
is incremented just before the next iteration starts.
A for
loop with this structure:
for (INIT; CONDITION; INCREMENT) {
BODY
}
is more or less equivalent to this while
loop:
INIT
while (CONDITION) {
BODY
INCREMENT
}
The caveat is when BODY has a continue
statement, it actually jumps down to the INCREMENT
part.
Upvotes: 3