C Loops (for, while) Tutorial

Loops in C programming allow you to execute a block of code multiple times efficiently. This tutorial covers for, while, and do-while loops.

1. The for Loop

The for loop is used when the number of iterations is known:

#include <stdio.h>

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

    return 0;
}

This loop runs 5 times, printing the current iteration.

2. The while Loop

The while loop executes as long as its condition is true:

#include <stdio.h>

int main() {
    int i = 0;

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

    return 0;
}

The while loop checks the condition before each iteration.

3. The do-while Loop

The do-while loop guarantees at least one execution of the loop body:

#include <stdio.h>

int main() {
    int i = 0;

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

    return 0;
}

The do-while loop evaluates the condition after each execution.

4. Nested Loops

Loops can be nested to perform more complex tasks:

#include <stdio.h>

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

    return 0;
}

Nested loops execute one loop inside another.

5. Conclusion

Loops are fundamental for repetitive tasks in C. Practice using for, while, and do-while to master their usage.

0 Interaction
1.9K Views
Views
36 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home