Lesson 6 of 20Core Programming20 min

Loops in C++

Loops repeat a block of code. Choose the loop that best matches the task: a for loop for counted repetition, a while loop for condition-controlled repetition, or a do-while loop when the code must run at least once.

for Loop

Count from 1 to 5
for (int i = 1; i <= 5; i++)
{
    cout << i << endl;
}

while Loop

Repeat while a condition is true
int number = 1;

while (number <= 5)
{
    cout << number << endl;
    number++;
}

do-while Loop

Menu that appears at least once
int choice;

do
{
    cout << "1. Continue
0. Exit
";
    cin >> choice;
} while (choice != 0);

break and continue

break exits the loop immediately. continue skips the rest of the current repetition and moves to the next one.

Practice task

Ask the user for five marks, calculate their total, and display the average.

Lesson Summary

Repeat tasks using for, while, and do-while loops.