login

C For Loop Statement

Summary: In this tutorial, you will learn about C for loop statement to execute a block of code repeatedly with various options.

Let's start with the C for loop statement syntax as follows:

 

 

for (initialization_expression;loop_condition;increment_expression){
  // statements
}

There are three parts that are separated by semi-colons in control block of the C for loop.

  • initialization_expression is executed before execution of the loop starts. The initialization_expression is typically used to initialize a counter for the number of loop iterations. You can initialize a counter for the loop in this part.
  • The execution of the loop continues until the loop_condition is false. This expression is checked at the beginning of each loop iteration.
  • The increment_expression, is usually used to increase (or decrease) the loop counter. This part is executed at the end of each loop iteration.

The flow chart of the C for loop is as belows:

Here is an example of using C for loop statement to print number from 0 to 4 on screen:

#include <stdio.h>
 
void main(){
    // using for loop statement
    int max = 5;
    int i;
    for(i = 0; i < max;i++){
 
        printf("%d\n",i);
 
    }
}

And the output is

0
1
2
3
4

Dive into C For Loop

C for loop is very flexible based on the combination of the three expression is used. The counter can be not only counted up but also counted down.  You can count by twos, threes and so on. You can count by not only number but also character. Let's take a look at the example program below:

/* 
 * File:    main.c
 * Author:  http://cprogramminglanguage.net
 * Purpose: Demonstrates C for loop : counter
 */
#include <stdio.h>

void main() {
    
    /* count down from 10*/
    int waits = 10;
    int s;
    for(s = waits; s > 0;s--)
        printf("%d\n",s);
    printf("Happy New Year!\n");
    
    /* count by 3*/
    for(s = 0; s < 10; s+=3)
        printf("%d\n",s);
    
    
    /*count by character */
    char c;
    for(c = 'a'; c <= 'z'; c++)
        printf("ASCII(%c) = %d\n",c,c);
    
    return 0;
}

With C for loop, you can omit any expression or all of them. The following program demonstrates the flexibility of C for loop:

/* 
 * File:    main.c
 * Author:  http://cprogramminglanguage.net
 * Purpose: Demonstrates C for loop : omit expressions
 */
#include <stdio.h>

void main() {
    
    int max = 5;
    /* omit the first and the last expressions*/
    int c = 0;
    for(;c < max;){
       c++;
       printf("c = %d\n",c);
    }
    
    /* omit all expressions*/
    int i = 0;
    for(;;){
        i++;
        /* use break to escape the loop*/
        if(i > max)
            break;
        printf("i = %d\n",i);
    }
    
    return 0;
}