Reputation: 71
I have a confusion in basic concept for C language for loop increment. This is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int j=0;int a;
for(j;j<=3;++j)
{
printf("hello\n");
a=j;
}
printf("%d,%d\n",j,a);
}
My question is: Why is the output of a not equal to output of j? I was thinking that if j
is getting increased for every iteration and the value of j
is being stored in a
, then why is a not the same?
Upvotes: 0
Views: 371
Reputation: 16
We should be bit carefull,when we are using prefix incrementation in a looping concept.
For j=0 a=0
# 1st iteration
For j=1 a=1
#2nd iteration
For j=2 a=2
# 3rd iteration
For j=3 a=3
#4th iteration
For j=4
as the condition is not satisfied, control comes out of the for loop. But the j
value is incremented earlier so it outputs "4"
.
Upvotes: 0
Reputation: 44274
It's due to the way the 3 expressions in the for-loop are executed.
Consider
for( exp1; exp2; exp3)
{
body;
}
this will be executed like:
exp1;
if (exp2 == false) goto end_of_loop;
body;
exp3;
if (exp2 == false) goto end_of_loop;
body;
exp3;
if (exp2 == false) goto end_of_loop;
body;
exp3;
if (exp2 == false) goto end_of_loop;
. . .
. . .
end_of_loop:
As you can see exp3
is always executed one time after body
.
So in your case j
will be incremented one time after it was assigned to a
.
Like:
a=j; // part of body
++j; // exp3
j<=3 (exp2) becomes false and the loop ends
Upvotes: 0
Reputation: 755
1st:
j = 0
j <= 3 => print hello and a = 0, ++j
2nd:
j = 1
j <= 3 => print hello and a = 1, ++j
3rd:
j = 2
j <= 3 => print hello and a = 2, ++j
4th:
j = 3
j <= 3 => print hello and a = 3, ++j
5th:
j = 4 not satisfy j <= 3
So j = 4 and a =3
Upvotes: 0
Reputation: 626
The for
loop checks the condition at every iteration. So when you initialized j=0
, gave the condition that the following code be looped till j<=3
while incrementing the value of j
after every iteration, the loop does the same.
So for the first iteration, j is 0 and hence the condition is satisfied and a
is assigned the value of j
. Now the value of j
is incremented by 1. It goes on till j=3.
When j=3, a is also equal to 3. Now, the value of j is incremented by 1 and it equals 4. Now the condition is checked. Since j!=3
, the loop breaks and you move out of the loop. Hence, although j=4, a is still 3.
Hope it helps.
Upvotes: 0
Reputation: 1728
Till j<=3
condition the value of j
is assigned to a
but after that when j
is incremented by 1 (j==4), it breaks out from the loop as the value of j
is now 4
and it didn't assign the value of j
to a
. So finally we get a=4
and j=3
.
Upvotes: 1
Reputation: 109
For j=0
a=0
For j=1
a=1
For j=2
a=2
For j=3
a=3
For j=4
loop get terminated as j<=3
become false, so j value is 4 and a value is 3.
Upvotes: 1