For Loop - C Statement

C examples for Statement:for

Introduction

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.

Demo Code

#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 */
    }
}

Result

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.

Demo Code

#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*/
}

Result

We can split the first and third parameters into several statements by using the comma operator.

Demo Code

#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) */
    }
}

Result

If all parameters are left out, it becomes a never-ending loop, unless there is another exit condition defined.

for (;;) {
  /* infinite loop */
}

Related Tutorials