Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

C++ Loops — for, while, do-while, range-based | Tutorials Logic

Types of Loops

Loops allow you to execute a block of code repeatedly. C++ provides four looping constructs:

LoopUse whenChecks condition
forNumber of iterations is knownBefore each iteration
whileNumber of iterations is unknownBefore each iteration
do-whileMust execute at least onceAfter each iteration
range-based forIterating over a collectionAutomatic

1. for Loop

The for loop is ideal when you know exactly how many times to iterate. It combines initialization, condition check, and update in a single line.

Syntax: for (initialization; condition; update) { body }

for Loop Examples
#include <iostream>
using namespace std;

int main() {
    // Basic for loop - count 1 to 5
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    cout << endl;  // 1 2 3 4 5

    // Count down
    for (int i = 5; i >= 1; i--) {
        cout << i << " ";
    }
    cout << endl;  // 5 4 3 2 1

    // Step by 2
    for (int i = 0; i <= 10; i += 2) {
        cout << i << " ";
    }
    cout << endl;  // 0 2 4 6 8 10

    // Nested for - multiplication table
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            cout << i * j << "\t";
        }
        cout << endl;
    }
    // 1  2  3
    // 2  4  6
    // 3  6  9

    // Sum 1 to 100
    int sum = 0;
    for (int i = 1; i <= 100; i++) sum += i;
    cout << "Sum 1..100 = " << sum << endl;  // 5050

    return 0;
}

2. while Loop

The while loop checks the condition before each iteration. If the condition is false from the start, the body never executes. Use it when the number of iterations depends on a runtime condition.

Syntax: while (condition) { body }

while Loop Examples
#include <iostream>
using namespace std;

int main() {
    // Basic while loop
    int i = 1;
    while (i <= 5) {
        cout << i << " ";
        i++;
    }
    cout << endl;  // 1 2 3 4 5

    // Reverse digits of a number
    int num = 12345, reversed = 0;
    while (num > 0) {
        reversed = reversed * 10 + num % 10;
        num /= 10;
    }
    cout << "Reversed: " << reversed << endl;  // 54321

    // Read until user enters 0
    int n, total = 0;
    cout << "Enter numbers (0 to stop):" << endl;
    while (cin >> n && n != 0) {
        total += n;
    }
    cout << "Total: " << total << endl;

    // Condition false from start - body never runs
    int x = 10;
    while (x < 5) {
        cout << "This never prints" << endl;
        x++;
    }
    cout << "Loop skipped entirely" << endl;

    return 0;
}

3. do-while Loop

The do-while loop executes the body first, then checks the condition. This guarantees the body runs at least once - even if the condition is false from the start. It's perfect for menus and input validation.

Syntax: do { body } while (condition);

do-while Loop Examples
#include <iostream>
using namespace std;

int main() {
    // Basic do-while
    int i = 1;
    do {
        cout << i << " ";
        i++;
    } while (i <= 5);
    cout << endl;  // 1 2 3 4 5

    // Runs at least once even when condition is false
    int x = 10;
    do {
        cout << "Runs once: x = " << x << endl;
        x++;
    } while (x < 5);  // false immediately, but body already ran

    // Menu - always show at least once
    int choice;
    do {
        cout << "\n--- Menu ---" << endl;
        cout << "1. Start" << endl;
        cout << "2. Settings" << endl;
        cout << "3. Exit" << endl;
        cout << "Enter choice (1-3): ";
        cin >> choice;
    } while (choice < 1 || choice > 3);  // repeat until valid input

    cout << "You chose: " << choice << endl;

    // Input validation - keep asking until positive number
    int num;
    do {
        cout << "Enter a positive number: ";
        cin >> num;
    } while (num <= 0);
    cout << "You entered: " << num << endl;

    return 0;
}

4. Range-based for Loop (C++11)

The range-based for loop iterates over every element in a collection - arrays, vectors, strings, maps, and any container with begin()/end(). It's cleaner and less error-prone than index-based loops.

Syntax: for (type element : collection) { body }

  • Use auto to let the compiler deduce the element type.
  • Use const auto& to avoid copying (read-only access).
  • Use auto& to modify elements in place.
Range-based for Loop Examples
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;

int main() {
    // Over a C-style array
    int nums[] = {10, 20, 30, 40, 50};
    for (int n : nums) {
        cout << n << " ";
    }
    cout << endl;  // 10 20 30 40 50

    // Over a vector with auto
    vector<string> fruits = {"Apple", "Banana", "Cherry"};
    for (const auto& fruit : fruits) {
        cout << fruit << endl;
    }

    // Modify elements with auto&
    vector<int> scores = {85, 92, 78};
    for (auto& s : scores) s += 5;  // add 5 to each score
    for (auto s : scores) cout << s << " ";  // 90 97 83
    cout << endl;

    // Over a string - character by character
    string word = "Hello";
    for (char c : word) {
        cout << c << "-";
    }
    cout << endl;  // H-e-l-l-o-

    // Over a map - structured binding (C++17)
    map<string, int> ages = {{"Alice", 25}, {"Bob", 30}, {"Carol", 28}};
    for (const auto& [name, age] : ages) {
        cout << name << " is " << age << " years old" << endl;
    }

    return 0;
}

for vs while vs do-while - Quick Comparison

Featureforwhiledo-while
Condition checkBefore iterationBefore iterationAfter iteration
Minimum executions001
Best forKnown countUnknown countMust run once
Init + updateIn loop headerManualManual
Typical useArrays, countingFile reading, eventsMenus, validation

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.