Reputation: 97
Why the loop is running from 2 to 7?
int i;
for(i=1;i<=6;printf("\n%d\n",i))
i++;
The output of this is
2 3 4 5 6 7
but limit of i
is 6.
Upvotes: 2
Views: 163
Reputation: 134386
The Syntax of a for
loop is
for (
clause-1;
expression-2;
expression-3)
statement
The execution is as below, quoting from C11
, chapter §6.8.5.3, (emphasis mine)
The expression
expression-2
is the controlling expression that is evaluated before each execution of the loop body. The expressionexpression-3
is evaluated as a void expression after each execution of the loop body. [....]
Here, i++
is the body and printf("\n%d\n",i)
is the expression-3.
So, the order of execution would be something like
i = 1;
start loop
i < = 6 //==> TRUE
i++; //i == 2
printf // Will print 2 ///iteration 1 done
i < = 6 //==> TRUE
i++; //i == 3
printf // Will print 3 ///iteration 2 done
.
.
.
i < = 6 //==> TRUE
i++; //i == 6
printf // Will print 6 ///iteration 5 done
i < = 6 //==> TRUE
i++; //i == 7
printf // Will print 7 ///iteration 6 done
i < = 6 ==> FALSE
end loop.
Upvotes: 8
Reputation: 8614
You have written the for loop in an unusual manner.
The operation of a for loop is given below.
The initialization is done first. i=1
Then the expression is checked i<=6
Then the body is carried out i++
Then the increment is carried out. In your case this is printf("\n%d\n",i)
Repeat Step 2 to 4, until step 2 is FALSE.
In your case, you can see that the printf
will be done for i==7
first, and then the expression will be checked for i==7
. After that the for loop will exit. Similarly the first print will be done only after one increment on i
So, first print will be for 2
and last will be for 7
Upvotes: 1
Reputation: 234865
The workings of the loop are equivalent to the now-obvious
int i;
for (i = 1; i <= 6; /*intentionally blank*/){
i++;
printf("\n%d\n", i);
}
as, conceptually, the 3rd expression in the for
loop is ran just before the closing brace of the loop body.
Upvotes: 2
Reputation: 409442
A for
loop like
for(i=1;i<=6;printf("\n%d\n",i))
i++;
is equivalent to
{
i = 1; // Initialization clause from for loop
while (i <= 6) // Condition clause from for loop
{
i++; // Body of for loop
printf("\n%d\n", i); // "Increment" clause from for loop
}
}
As you can see, the printf
is done after the variable i
is incremented, which of course means it will print the incremented value (2
to 7
).
Upvotes: 3
Reputation: 8142
You've written the loop incorrectly - you've swapped the body of the loop with the incrementation code. So after having done i++
which is in the body of the loop, it does the printf
as the incrementation when that should be the other way around.
Write the for
loop correctly as follows.
int i;
for(i=1;i<=6;i++)
printf("\n%d\n",i)
Upvotes: -5