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.
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-2is the controlling expression that is evaluated before each execution of the loop body. The expressionexpression-3is 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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With