Loops (for, while, do-while) in C

In C programming language, loops are used to repeat a block of code multiple times based on a condition. There are three types of loops in C: for loop, while loop, and do-while loop.

1. for Loop: The for loop is used to execute a block of code a fixed number of times. The syntax of the for loop is as follows:

for (initialization; condition; increment/decrement) {
    // code to execute
}

Here’s an example of how to use the for loop in C:

#include 

int main() {
    int i;

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

    return 0;
}

In this example, we use the for loop to print the numbers from 1 to 5. The variable i is initialized to 1, and the loop continues as long as i is less than or equal to 5. After each iteration, i is incremented by 1.

2. while Loop: The while loop is used to execute a block of code as long as a condition is true. The syntax of the while loop is as follows:

while (condition) {
    // code to execute
}

Here's an example of how to use the while loop in C:

#include 

int main() {
    int i = 1;

    while (i <= 5) {
        printf("%d\n", i);
        i++;
    }

    return 0;
}

In this example, we use the while loop to print the numbers from 1 to 5. The variable i is initialized to 1, and the loop continues as long as i is less than or equal to 5. After each iteration, i is incremented by 1.

3. do-while Loop: The do-while loop is used to execute a block of code at least once, and then repeat the block as long as a condition is true. The syntax of the do-while loop is as follows:

do {
    // code to execute
} while (condition);

Here's an example of how to use the do-while loop in C:

#include 

int main() {
    int i = 1;

    do {
        printf("%d\n", i);
        i++;
    } while (i <= 5);

    return 0;
}

In this example, we use the do-while loop to print the numbers from 1 to 5. The variable i is initialized to 1, and the block of code is executed at least once. After each iteration, i is incremented by 1, and the loop continues as long as i is less than or equal to 5.