C for Loop (original) (raw)

Last Updated : 20 May, 2025

In C programming, the 'for' loop is a control flow statement that is used to repeatedly execute a block of code as many times as instructed. It uses a variable (loop variable) whose value is used to decide the number of repetitions. It is commonly used to iterate over a sequence such as an array or list.

**Example:

C `

#include <stdio.h>

int main() {

// for loop to print "Hi" 5 times
for (int i = 5; i < 10; i++) {
    printf("Hi\n");
}

return 0;

}

`

Explanation: In this example, the loop prints the text "Hi" 5 times. The loop variable i is initialized to 1. The conditioni <= 5** is checked before each iteration. After each iteration, i is incremented by **1. So this loop was executed 5 times.

**C for Loop Syntax

C `

for (initialization; condition; updation) { // Body of the loop }

`

where,

**Note: As we can see, unlike the while loop and do…while loop, the for loop contains the initialization, condition, and updating statements for loop as part of its syntax.

**Working of For Loop

The working of for loop is mentioned below:

**Flowchart of for Loop

The following flow chart defines the logic behind the working of for loop.

c for loop flowchart

C for Loop Flow Diagram

C For Loop Examples

The below examples demonstrate the use of for loop in different cases:

First N Natural Numbers Using For Loop

C `

#include <stdio.h>

int main() { int n = 5;

// Initialization of loop variable
int i;
for (i = 1; i <= n; i++)
       printf("%d ", i);

return 0;

}

`

We have not used braces {} in the body of the loop in this program. Actually, the braces {} can be skipped if there are only one statement in the loop.

C `

#include <stdio.h>

int main() {

// Outer for loop to print a multiplication
  // table for all numbers upto 5
for (int i = 1; i <= 5; i++) {
  
      // Inner loop to print each value in table
    for (int j = 1; j <= 5; j++) {
        printf("%d ", i * j);  
    }
    printf("\n");
}
return 0;

}

`

Output

1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25

**Explanation: This code uses nested for loops to generate a multiplication table up to 5. The outer loop iterates through the rows (from 1 to 5), and the inner loop (controlled by j) iterates through the columns (also from 1 to 5). For each combination of i and j, the product i * j is printed, creating the table entries.

Infinite For Loop

This is a kind of _for loop where the input parameters are not available or the condition that's always true due to which, the loop iterates/runs endlessly.

C `

#include <stdio.h>

int main() {

// for loop with no initalization, condition
  // and updation
for (;;)  {
    printf("GfG\n");
}

return 0;

}

`

**Output

GfG
GfG
.
.
.
_infinity