The while loop repeats a block as long as the condition is true. The condition is checked before each iteration.
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << "i = " << i << endl;
i++;
}
return 0;
}
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
do-while Loop
The do-while loop always runs the block at least once, then checks the condition.
int n;
do {
cout << "Enter a positive number: ";
cin >> n;
} while (n <= 0);
cout << "You entered: " << n << endl;
for Loop
The for loop is perfect when you know how many times to iterate. It bundles init, condition, and update in one line.
for (int i = 0; i < 5; i++) {
cout << "Iteration " << i << endl;
}
// Print multiplication table of 7
for (int i = 1; i <= 10; i++) {
cout << "7 x " << i << " = " << 7 * i << endl;
}
Range-Based for Loop (C++11)
The cleanest way to iterate over a collection:
int numbers[] = {10, 20, 30, 40, 50};
for (int n : numbers) {
cout << n << " ";
}
// Output: 10 20 30 40 50
Tip: Use for when the number of iterations is known. Use while when it depends on a condition. Use do-while when you need at least one run.
Exercise
Use a for loop to print the sum of all numbers from 1 to 100.
Show Solution
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
cout << "Sum 1-100 = " << sum << endl; // 5050
return 0;
}
Quiz
Which loop always executes its body at least once?
A) for
B) while
C) do-while
D) range-based for
Answer
C) do-while — it checks the condition after the body runs.
What are the three parts of a for loop header?
A) condition, body, update
B) init, condition, update
C) start, end, step
D) declare, loop, exit
Answer
B) init, condition, update — e.g., for (int i=0; i<5; i++).
Summary
while — checks condition first, runs 0 or more times.
do-while — runs at least once, checks condition after.
for — compact loop for a known number of iterations.
Range-based for — cleanly iterates over arrays and collections.