0
0
C++programming~5 mins

Loop execution flow in C++

Choose your learning style9 modes available
Introduction

Loops help repeat actions many times without writing the same code again and again.

When you want to print numbers from 1 to 10.
When you need to check each item in a list one by one.
When you want to keep asking a user for input until they give a correct answer.
When you want to repeat a task until a certain condition is met.
Syntax
C++
for (initialization; condition; update) {
    // code to repeat
}

while (condition) {
    // code to repeat
}

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

The for loop is good when you know how many times to repeat.

The while loop repeats as long as the condition is true.

Examples
This prints numbers 1 to 5 using a for loop.
C++
for (int i = 1; i <= 5; i++) {
    std::cout << i << " ";
}
This prints numbers 1 to 5 using a while loop.
C++
int i = 1;
while (i <= 5) {
    std::cout << i << " ";
    i++;
}
This prints numbers 1 to 5 using a do-while loop, which runs the code at least once.
C++
int i = 1;
do {
    std::cout << i << " ";
    i++;
} while (i <= 5);
Sample Program

This program shows how each loop type repeats code to print numbers 1 to 3.

C++
#include <iostream>

int main() {
    std::cout << "For loop output: ";
    for (int i = 1; i <= 3; i++) {
        std::cout << i << " ";
    }
    std::cout << "\n";

    std::cout << "While loop output: ";
    int j = 1;
    while (j <= 3) {
        std::cout << j << " ";
        j++;
    }
    std::cout << "\n";

    std::cout << "Do-while loop output: ";
    int k = 1;
    do {
        std::cout << k << " ";
        k++;
    } while (k <= 3);
    std::cout << "\n";

    return 0;
}
OutputSuccess
Important Notes

Loops run the code inside their block repeatedly until the condition is false.

Be careful to update variables inside loops to avoid infinite loops.

Summary

Loops help repeat tasks easily and clearly.

Use for when you know how many times to repeat.

Use while or do-while when repeating depends on a condition.