0
0
C++programming~5 mins

Why loops are needed in C++

Choose your learning style9 modes available
Introduction

Loops help us repeat tasks easily without writing the same code many times. They save time and make programs shorter and clearer.

When you want to print numbers from 1 to 10.
When you need to add up all items in a list.
When you want to keep asking a user for input until they give a valid answer.
When you want to repeat a game action multiple times.
When you want to process each item in a collection one by one.
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 a 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 "Hello" three times using a while loop.
C++
int count = 1;
while (count <= 3) {
    std::cout << "Hello\n";
    count++;
}
This prints numbers 0 and 1 using a do-while loop, which runs the code at least once.
C++
int n = 0;
do {
    std::cout << "Number: " << n << "\n";
    n++;
} while (n < 2);
Sample Program

This program shows two loops: a for loop counting numbers and a while loop printing a message multiple times.

C++
#include <iostream>

int main() {
    std::cout << "Counting from 1 to 5:\n";
    for (int i = 1; i <= 5; i++) {
        std::cout << i << " ";
    }
    std::cout << "\n";

    std::cout << "\nRepeating message 3 times:\n";
    int count = 1;
    while (count <= 3) {
        std::cout << "Hello!\n";
        count++;
    }

    return 0;
}
OutputSuccess
Important Notes

Loops help avoid repeating the same code many times.

Be careful to make sure loops eventually stop, or the program will run forever.

Summary

Loops repeat actions to save time and code.

Use loops when you want to do something many times.

There are different loops for different situations: for, while, and do-while.