for loop

Home / C Programming / for loop

for loop


C programming, the `for` loop is a powerful loop structure that allows you to repeatedly execute a block of code for a specific number of iterations. It provides a compact way to initialize, test, and update loop control variables in a single line.

The basic syntax of the `for` loop in C is as follows:

for (initialization; condition; update) {

    // code to execute

}

The `initialization` is used to initialize loop control variables, typically setting an initial value. The `condition` is a test expression that is evaluated before each iteration. If the condition is true, the code block within the `for` loop is executed. The `update` is used to update the loop control variables after each iteration.

Here's an example to illustrate the usage of `for` loop:

#include <stdio.h>

int main() {

    for (int i = 1; i <= 5; i++) {

        printf("Count: %d\n", i);

    }

    printf("Loop complete.\n");

    return 0;

}

In this example, the `for` loop initializes the loop control variable `i` to 1, checks if `i` is less than or equal to 5, and executes the code block. After each iteration, the loop updates `i` by incrementing it with `i++`. The loop continues to execute as long as the condition `i <= 5` is true. The output will be the numbers 1 to 5 printed on separate lines.

You can also use multiple loop control variables and perform more complex operations within the initialization, condition, and update sections. For example:

#include <stdio.h>

int main() {

    int num = 0;

    int sum = 0;

    for (int i = 1; i <= 5; i++) {

        printf("Enter number %d: ", i);

        scanf("%d", &num);

        sum += num;

    }

    printf("Sum: %d\n", sum);

    return 0;

}

In this example, the `for` loop prompts the user to enter five numbers. It uses the loop control variable `i` to keep track of the iteration number. Within each iteration, it reads a number from the user using `scanf()` and adds it to the `sum` variable. After the loop completes, it prints the sum of the entered numbers.