C examples for Statement:for
The for loop runs through a code block for a specific number of times.
It uses three parameters.
The first one initializes a counter and is executed once before the loop.
The second parameter is checked before each iteration.
The third parameter is executed at the end of each iteration.
#include <stdio.h> int main(void) { int k;//from w w w . j a va 2s . c o m for (k = 0; k < 10; k++) { printf("%d", k); /* 0-9 */ } }
Since the C99 standard the first parameter may contain a declaration, typically a counter variable.
The scope of this variable is limited to the for loop.
#include <stdio.h> int main(void) { for (int k = 0; k < 10; k++) { printf("%d", k); /* 0-9 */ }/*from w w w.j a v a 2s .c o m*/ }
We can split the first and third parameters into several statements by using the comma operator.
#include <stdio.h> int main(void) { int k, m;/*from w ww . ja va2 s . co m*/ for (k = 0, m = 0; k < 10; k++, m--) { printf("%d", k+m); /* 000... (10x) */ } }
If all parameters are left out, it becomes a never-ending loop, unless there is another exit condition defined.
for (;;) { /* infinite loop */ }