Loops in C++ (for, while, do-while)
Loops in C++ Tutorial (for, while, do-while)
Loops are used in C++ to execute a block of code repeatedly as long as a specified condition is true. They help reduce code duplication and improve efficiency.
C++ provides three main types of loops:
for loop
while loop
do-while loop
The for loop is used when you know in advance how many times you want to execute a block of code.
Syntax:
for (initialization; condition; update) {
// Code block to be executed
}
Example:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "Iteration " << i << endl;
}
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
The while loop is used when the number of iterations is not known in advance. It checks the condition before executing the block.
Syntax:
while (condition) {
// Code block to be executed
}
Example:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << "Iteration " << i << endl;
i++;
}
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
The do-while loop is similar to the while loop but it executes the block of code at least once, even if the condition is false.
Syntax:
do {
// Code block to be executed
} while (condition);
Example:
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << "Iteration " << i << endl;
i++;
} while (i <= 5);
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Use for when iteration count is known.
Use while for condition-based loops.
Use do-while if the loop must run at least once.
Always update loop variables to avoid infinite loops.