C++ Loops (for, while) Tutorial
Loops in C++ allow you to execute a block of code multiple times. Common loop types are for, while, and do-while.
1. for Loop
The for loop is ideal for running a block of code a specific number of times:
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
cout << "Iteration " << i + 1 << endl;
}
return 0;
}
In this example, the loop runs 5 times, incrementing i with each iteration.
2. while Loop
The while loop continues as long as its condition is true:
#include <iostream>
using namespace std;
int main() {
int count = 0;
while (count < 5) {
cout << "Count is " << count << endl;
count++;
}
return 0;
}
This loop increments count until it reaches 5.
3. do-while Loop
The do-while loop guarantees at least one execution of the code block:
#include <iostream>
using namespace std;
int main() {
int num = 10;
do {
cout << "Number is " << num << endl;
num--;
} while (num > 0);
return 0;
}
In this example, the loop prints and decrements num until it becomes zero.
4. Nested Loops
Loops can be nested to handle multi-dimensional data or repeated patterns:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << "(" << i << ", " << j << ") ";
}
cout << endl;
}
return 0;
}
This example demonstrates nested loops to print a 3x3 grid.
5. Infinite Loops
An infinite loop runs indefinitely and should be avoided unless intentionally used:
while (true) {
cout << "This will run forever unless interrupted!" << endl;
}
Use break or conditions to exit loops safely.
6. Best Practices
- Prefer
forloops for known iteration counts. - Use
whileordo-whileloops for uncertain iterations. - Always ensure a loop has an exit condition to avoid infinite loops.