C++ Loops
Loops repeat a block of code, so you do not have to write the same lines many times.
The while Loop
Example
cpp
#include <iostream>
using namespace std;
int main() {
int savings = 0;
int month = 0;
while (savings < 10000) {
savings += 3000;
month++;
}
cout << "Goal reached in " << month << " months\n";
return 0;
}Output
Goal reached in 4 months
The do...while Loop
The body runs first, and the condition is checked after. So it always runs at least once:
Example
cpp
int n = 100;
do {
cout << n << "\n";
n++;
} while (n < 3);Output
100
The for Loop
Example
text
for (start; condition; step) {
// repeated code
}Example
cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 10; i >= 0; i -= 2) {
cout << i << " ";
}
cout << "\n";
return 0;
}Output
10 8 6 4 2 0
Range-based for Loop
Since C++11 you can loop over every item in an array, vector or string without using an index:
Example
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string cities[] = {"Karachi", "Lahore", "Quetta"};
for (string city : cities) {
cout << city << "\n";
}
return 0;
}Output
Karachi Lahore Quetta
break and continue
| Statement | Effect |
|---|---|
break | Leaves the loop at once |
continue | Skips the rest of the current round |
Example
cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 20; i++) {
if (i % 3 != 0) {
continue; // only multiples of 3
}
if (i > 12) {
break;
}
cout << i << " ";
}
cout << "\n";
return 0;
}Output
3 6 9 12
An infinite loop such as while (true) is fine if you have a break inside that will be reached. Menus in console programs often work like this.
Nested Loops
Example
cpp
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= 3; c++) {
cout << r * c << "\t";
}
cout << "\n";
}Output
1 2 3 2 4 6 3 6 9
Exercise
Exercise
Which loop is the best choice to visit every item of a vector without an index?
