Loops (for, while, do-while) in C++
Loops allow a set of instructions to be executed repeatedly until a specific condition is met. In C++, there are three main types of loops: for
, while
, and do-while
. Each loop has its own use case depending on the situation. This article explains each loop with examples.
1. The for Loop
The for
loop is typically used when the number of iterations is known beforehand. It has three parts: initialization, condition, and increment/decrement, which are all defined in the loop header.
Syntax of for Loop
for (initialization; condition; increment/decrement) { // Code to be executed }
Example of for Loop
#include <iostream> int main() { for (int i = 1; i <= 5; i++) { std::cout << "Iteration: " << i << std::endl; } return 0; }
In this example, the for
loop initializes i
to 1, checks if i <= 5
, and increments i
after each iteration. The loop executes five times, printing the value of i
each time.
2. The while Loop
The while
loop is used when the number of iterations is not known beforehand, and you want the loop to continue as long as a specific condition is true. The condition is checked at the start of each iteration.
Syntax of while Loop
while (condition) { // Code to be executed }
Example of while Loop
#include <iostream> int main() { int i = 1; while (i <= 5) { std::cout << "Iteration: " << i << std::endl; i++; } return 0; }
In this example, i
is initialized to 1. The while
loop checks if i <= 5
before each iteration. If true, the loop executes, prints i
, and increments i
. The loop stops when i
becomes 6.
3. The do-while Loop
The do-while
loop is similar to the while
loop, but the condition is checked at the end of each iteration. This ensures that the loop executes at least once, even if the condition is false at the start.
Syntax of do-while Loop
do { // Code to be executed } while (condition);
Example of do-while Loop
#include <iostream> int main() { int i = 1; do { std::cout << "Iteration: " << i << std::endl; i++; } while (i <= 5); return 0; }
In this example, i
is initialized to 1. The do-while
loop executes, prints i
, and increments i
. After each iteration, the condition i <= 5
is checked. The loop stops when i
becomes 6. Unlike the while
loop, the do-while
loop will run at least once even if the initial condition is false.
4. Comparing the Loops
- for Loop: Ideal for situations where the number of iterations is known in advance.
- while Loop: Best suited for situations where the number of iterations is unknown and depends on a condition.
- do-while Loop: Useful when you want the loop to execute at least once, regardless of the condition.
5. Conclusion
Loops are essential in C++ for repeating tasks based on conditions. The for
loop is used when the iteration count is known, while
for unknown iteration counts based on a condition, and do-while
ensures at least one execution. Choosing the right loop type makes code more efficient and easier to understand.