Studying for a computer science final......
I really cannot figure this example out.....
I understand that leaving the first argument blank makes it act like TRUE....
but I don't understand what leaving a variable in the second argument accomplishes....
What I don't understand the most is how a printf statement "updates" the variable condition...
#include<stdio.h>
int main()
{
int x=1, y=1;
for(; y; printf("%d %d\n", x, y))
{
y = x++ <= 5;
}
printf("\n");
return 0;
}
The output is:
2 1
3 1
4 1
5 1
6 1
7 0
edit:
I understand now the for-loop structure part.....
Thanks for the answers - very insightful thanks!
A for
loop can be thought of as for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
The first part of the loop is for initialisation. Leaving this empty is fine, it just indicates that you have already initialised any variables required by the loop.
The y
in the second expression (or condition) of the for
loop is equivalent to y!=0
. It keeps the for
loop running until y==0
.
The printf
in the afterthought is run at the end of each iteration but doesn't change the value of y
. The loop's body does change y
however.
Most textbooks will describe this. Or see Wikipedia or cplusplus.
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