For Loop in C Language

In C, for loop is used to iterate over statements or parts of programmes several times. It is commonly used to traverse data structures such as arrays and linked lists. In this tutorial, we will learn about for loop with the help of examples.


A loop is used in programming to repeat a block of code until the specified condition is met.


The syntax of the for loop is:

C
for (initializationStatement ; testExpression; updateStatement) {
  // statements inside the body of loop
}


How for loop works?

  • The initialization statement is used only once.
  • Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is terminated.
  • If the test expression is true, the statements inside the for loop's body are executed, and the update statement is updated.
  • Again the test expression is checked.

This process is repeated until the test expression is false. The loop is terminated when the test expression is false.

For Loop In C



Example 1: For Loop

C
// Printing numbers from 1 to 10
#include <stdio.h>

int main() {
  int i;

  for (i = 1; i <= 10; i++)
  {
    printf("%d ", i);
  }
  return 0;
}

Output :

1 2 3 4 5 6 7 8 9 10


The value of i is set to 1.


  • The test expression i <= 10 is checked. Because 1 less than 10 is true, the for loop's body gets executed. This will display 1 (value of i) on the screen.

  • The i update statement is executed. The value of i will now be 2. The test expression is evaluated to true once more, and the body of the for loop is run. This will display 2 (value of i)on the screen.

  • The update statement i++ is executed once more, and the test expression i <=10 is evaluated. This process will continue until i becomes 11.

  • When i reaches 11, i<= 10 is false, and the for loop ends.

Example 2: For Loop

C
// Program to calculate the sum of first n natural numbers
// 1+2+3.....n
#include <stdio.h>
int main()
{
    int n, sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    // for loop terminates when num is less than i
    for(int i = 1; i <= n; i++)
    {
        sum = sum + i;
    }

    printf("Sum = %d", sum);

    return 0;
}

Output :

Enter a positive integer: 5 Sum = 15


The user's input is saved in the variable n. Assume the user typed 5.


  • The i is set to 1, and the test expression is run. Because the test expression i <=n (1 less than or equal to 5) is true, the for loop's body is run, and the sum value is 1.

  • The update statement i++ is  run, and i equals 2. The test expression is checked again. Because 2 is less than 5, the test expression is true, and the for loop body is run. The sum will now be 3.

  • This process goes on and the sum is calculated until the i reaches 6.

  • When the i is 6, the test expression is evaluated to 0 (false), and the loop terminates.

  • Then, the value of sum is printed on the screen.