Loops in C++ - for, while, and do-while


Loops are used in C++ to execute a block of code repeatedly as long as a certain condition is met. They are essential for tasks that involve repetition, such as iterating over arrays, processing data, and more. In this guide, we'll explore for loops, while loops, and do-while loops in C++.


The for Loop

The for loop is used when you know in advance how many times you want to execute a block of code. It consists of three parts: initialization, condition, and increment (or decrement).


for (initialization; condition; increment) {
// Code to repeat while the condition is true
}

Example:


#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "Iteration " << i << endl;
}
return 0;
}

This code will print "Iteration 1" through "Iteration 5" because the loop runs while the condition i <= 5 is true.


The while Loop

The while loop is used when you want to execute a block of code as long as a specific condition is true. The condition is evaluated before each iteration.


while (condition) {
// Code to repeat while the condition is true
}

Example:


#include <iostream>
using namespace std;
int main() {
int count = 1;
while (count <= 5) {
cout << "Iteration " << count << endl;
count++;
}
return 0;
}

This code achieves the same result as the previous example but uses a while loop instead.


The do-while Loop

The do-while loop is similar to the while loop but with a key difference: the condition is evaluated after the code block is executed. This guarantees that the code block is executed at least once.


do {
// Code to execute at least once
} while (condition);

Example:


#include <iostream>
using namespace std;
int main() {
int count = 1;
do {
cout << "Iteration " << count << endl;
count++;
} while (count <= 5);
return 0;
}

This code is similar to the previous examples but uses a do-while loop. The message "Iteration 1" is guaranteed to be printed at least once.


Conclusion

Loops are a fundamental concept in C++ that allow you to automate repetitive tasks. They help simplify your code and make it more efficient. As you continue your C++ journey, you'll discover more advanced uses and applications of loops.