C For Loop

In C programming language, the for loop is a control flow statement that allows you to execute a block of code repeatedly for a fixed number of times or until a condition is met. The for loop has the following syntax:

for (initialization; condition; update) {
    // code to be executed repeatedly
}

The initialization is typically used to set a loop control variable to an initial value, and the condition is a boolean expression that determines whether the loop should continue. The update statement is executed at the end of each iteration and is typically used to modify the loop control variable.

Here is an example of a for loop that prints the numbers from 1 to 5:

#include <stdio.h>

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

In this example, the loop control variable i is initialized to 1, and the condition i <= 5 determines whether the loop should continue. The update statement i++ increments i at the end of each iteration. The loop continues as long as i is less than or equal to 5. Inside the loop, the value of i is printed using the printf() function. Finally, the program exits with a return value of 0.

The for loop can also be used to iterate over elements of an array or a collection. Here is an example of a for loop that calculates the sum of an array of integers:

 
#include <stdio.h>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int sum = 0;
    int i;
    for (i = 0; i < 5; i++) {
        sum += numbers[i];
    }
    printf("Sum = %d\n", sum);
    return 0;
}

In this example, the loop iterates over the elements of the numbers array and calculates their sum. The loop control variable i is used as an index into the array, and the loop continues as long as i is less than the length of the array (which is 5 in this case). The sum variable is initialized to 0 before the loop and is incremented by the value of each element in the array. Finally, the sum is printed using the printf() function.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

91599