Need help understanding how my for loop works
#include<stdio.h>
int main(){
int i;
clrscr();
for(i=0,i++,i<=5;i++,i<=2;i=0,i<=5,i+=3){
printf("%d ",i);
}
return 0;
}
The output of this program is开发者_如何学编程 2. Please elaborate the logic
This loop is equivalent to:
i = 0;
i++;
i <= 5;
i++;
while (i <= 2)
{
printf("%d ", i);
i = 0;
i <= 5;
i += 3;
i++;
}
I'm guessing the part you may not have encountered before is the comma operator. A sequence of expressions separated by commas are each evaluated in turn, and the "return" value is the value of the final expression. e.g.:
x = (y + 3, ++y, y + 5);
is roughly equivalent to:
y + 3;
++y;
x = y + 5;
i=0,i++,i<=5;
corresponds to initialisation.here i becomes 1
i++,i<=2;
corresponds to test condition.here i becomes 2 and its value gets printed.
i=0,i<=5,i+=3;
corresponds to increment condition in which value of i becomes 5 which fails test condition so loop ends here.
well it might be confusing to the starter but let me explain it to u more cleaner way, then just the snippet
Let me divide my solution into 3 parts as 1)initialization 2) condition 3)increment as 3 parts of for loop
1st part
i=0,i++,i<=5
i is assigned 0
i++ increments to 1
i<=5 \\ this code has no effect as it is used in assinging part of for loop
it should be used only in condtions. so value of i is 1
i<=5 \\ doesnt make any sense it keeps i value as it is
2nd part
i++,i<=2
i++ \\ i value is 2
i<=2 \\ these code has effect as it is in conditional part of for loop
so now it checks the condition i<=2 and i value is 2 So condition becomes true
and enters into loop and prints the i value as 2
3rd part
i=0,i<=5;i+=3
i=0 assigns i = 0
i<=5 \\ as i told you, code has no effect so i still holding zero value in it
i+=3 implies i=i+3 (right hand operators)
as i value is zero it becomes i = 0+3 now i value is 3
goes to the condition part again
i++ \\ now i has four in it
i<=2 \\ fails as i value is 4 so loop exits
Remember and read more about comma operator and right hand operators.
x=4
x=(x+2,++x,x-4,++x,x+5)
x value is 11 now guess it why?
first performs x+2 gets 6 but ignores cuz you did not mention variable to store the value,++x makes it 5 as it is incrementor you dont need any assigning even the x-4 value is ignored and ++x makes x as 6 and x+5 gives 11 as it came to end that value is stored in x
I think I made it clear and cleaner for you Thanks anymore doubts feel free to ask me!
Initialization: i++ //so i=1
condition: i++ //so i=2 and i<=2 is true
print 2
Increment i+=3 //so i=5 condition false. come out of loop
Adding to @Oli Charlesworth's answer:
- You increment
i
twice before entering the loop. - Once the loop is entered, you print the number 2.
- The other conditions you have are never evaluated.
- Finally, you increment
i
, which makes it 3 and the loop stops on the next iteration (which hasi
set to 3 and thusi
is now greater than 2), program exits.
精彩评论