Loops in C

Loops in C

Loops in C are control structures used to repeat a set of instructions multiple times. They help reduce code duplication and improve program readability. By using loops in C, tasks like printing numbers, processing arrays, and performing repetitive calculations become simple and organized.

Types of Loops in C

There are three main types of loops in C:

1. while Loop in C

The while loop checks the condition before executing the loop body. This type of loops in C is useful when the number of iterations is not fixed.

Example: Print numbers from 1 to 5

#include <stdio.h>
int main() {
    int i = 1;
    while(i <= 5) {
        printf("%d\n", i);
        i++;
    }
    return 0;
}

OUTPUT:

1
2
3
4
5

2. do-while Loop in C

The do-while loop executes the loop body at least once, even if the condition is false. This makes it a special type of loops in C.

Example: Print a number once

#include <stdio.h>
int main() {
    int i = 1;
    do {
        printf("%d\n", i);
        i++;
    } while(i <= 5);
    return 0;
}

OUTPUT:

1
2
3
4
5

3. for Loop in C

The for loop is used when the number of iterations is known in advance. It is one of the most commonly used loops in C.

Example: Print numbers from 1 to 5

#include <stdio.h>
int main() {
    int i;
    for(i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}

OUTPUT:

1
2
3
4
5

Leave a Comment

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