Loops allow you to execute a block of code repeatedly based on a condition. They help avoid code duplication and make your programs efficient and easier to maintain. C++ provides several types of loops for different scenarios.
The for loop is used when you know beforehand how many times you want to repeat a block of code.
for (initialization; condition; update) {
// statements to repeat
}
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "Iteration: " << i << endl;
}
return 0;
}
- i = 1 initializes the loop counter.
- i <= 5 is the loop continuation condition.
- i++ increments the counter after each iteration.
The while loop repeats a block of code as long as a specified condition is true. It is useful when the number of iterations is not known in advance.
while (condition) {
// statements to repeat
}
#include <iostream>
using namespace std;
int main() {
int count = 1;
while (count <= 5) {
cout << "Count: " << count << endl;
count++;
}
return 0;
}
- The loop runs while count is less than or equal to 5.
- Increment count inside the loop to avoid infinite loops.
The do-while loop is similar to the while loop, but it guarantees that the loop body executes at least once before the condition is checked.
do {
// statements to repeat
} while (condition);
#include <iostream>
using namespace std;
int main() {
int number = 1;
do {
cout << "Number: " << number << endl;
number++;
} while (number <= 5);
return 0;
}
- The code inside do runs once before the condition is checked.
- The loop continues as long as the condition is true.
break; inside loops to exit the loop immediately.continue; skips the current iteration and jumps to the next iteration.| Loop Type | Use When | Runs At Least Once? |
|---|---|---|
| for | Known number of iterations | No |
| while | Unknown iterations, condition-checked before | No |
| do-while | Unknown iterations, condition-checked after | Yes |
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!