C for loop

A for loop in C is a control flow statement used to repeatedly execute a block of code a specified number of times. It is commonly used when you know in advance how many times the loop should run.

Syntax:


for (initialization; condition; update) {
    // Code to execute repeatedly
}

Explanation:

1. Initialization: Defines and initializes the loop control variable (this is executed only once at the beginning).

2. Condition: The loop keeps running as long as this condition is true.

3. Update: Updates the loop control variable after each iteration (e.g., increments or decrements it).

Example:


#include <stdio.h>

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

    return 0;
}

Output:

0
1
2
3
4

Example: Print the table of 2 through for loop


#include <stdio.h>

int main() {
        for (int i = 2; i <=20; i=i+2) 
        {
            printf("%d\n", i); // Prints the current value of i
        }

    return 0;
}

Output:

2
4
6
8
10
12
14
16
18
20