Go Back

For loop, While loop, Do while loop in c language

11/15/2023
All Articles

#For loop, While loop, Do while loop in c language

For loop, While loop, Do while loop in c language

For loop, While loop, Do while loop in c language

Looping is the process of repeatedly carrying out the same action until a predetermined condition is met. It also goes by the name "iteration." In C, there are three different kinds of loops that are utilised. We will cover every facet of C loops in this section of the course.you can use the following loop constructs: for loop, while loop, and do-while loop.

1. For Loop:
The for loop is typically used when the number of iterations is known beforehand.

#include <stdio.h>

int main() {
    // Syntax: for (initialization; condition; update)
    for (int i = 1; i <= 5; i++) {
        printf("Iteration %d\n", i);
    }

    return 0;
}


2. While Loop:
The while loop is used when the number of iterations is not known beforehand, and the loop continues as long as the condition is true.

#include <stdio.h>

int main() {
    // Syntax: while (condition)
    int i = 1;
    while (i <= 5) {
        printf("Iteration %d\n", i);
        i++;
    }

    return 0;
}


3. Do-While Loop:
The do-while loop is similar to the while loop, but it guarantees that the loop body is executed at least once because the condition is checked after the loop body.

#include <stdio.h>

int main() {
    // Syntax: do { /* code */ } while (condition);
    int i = 1;
    do {
        printf("Iteration %d\n", i);
        i++;
    } while (i <= 5);

    return 0;
}


In all three examples, the loop body contains a simple printf statement for illustration. You can replace it with any code you want to execute repeatedly.
Also, ensure that the loop control variables (like i in these examples) are properly initialized, updated, and have a condition that eventually becomes false to avoid an infinite loop.

 

Article