For loop in C

By | February 20, 2023

Prerequisite – Control Statements in C
In C, a “for” loop is a control structure used for iterating over a range of values. It is often used to perform a set of statements a fixed number of times, or to iterate over the elements of an array.

Syntax:
The syntax of a “for” loop in C is as follows:

for (initialization; condition; update) {
    // code to be executed
}
  1. The initialization statement is executed once at the beginning of the loop and is used to initialize the loop variable.
  2. The condition is checked at the beginning of each iteration of the loop. If the condition is true, the loop continues to execute. If the condition is false, the loop terminates.
  3. The update statement is executed at the end of each iteration of the loop and is used to update the loop variable.

Examples:
Here are some examples of using the “for” loop in C:

Example-1: Print the 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

Example-2: Calculate the sum of the first 10 natural numbers

#include <stdio.h>

int main() {
    int i, sum = 0;

    for (i = 1; i <= 10; i++) {
        sum += i;
    }

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

    return 0;
}

Output:

Sum = 55

Example-3: Find the maximum element in an array

#include <stdio.h>

int main() {
    int arr[5] = {3, 8, 1, 5, 2};
    int i, max = arr[0];

    for (i = 1; i < 5; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    printf("Maximum element = %d", max);

    return 0;
}

Output:

Maximum element = 8

Example-4: Print a multiplication table

#include <stdio.h>

int main() {
    int i, j;

    for (i = 1; i <= 10; i++) {
        for (j = 1; j <= 10; j++) {
            printf("%d x %d = %d\n", i, j, i*j);
        }
    }

    return 0;
}

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
...
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.