C++ Loop
In C++, loops are used to repeatedly execute a block of code as long as a specified condition is true or for a specific number of iterations. C++ provides several types of loops to cater to different looping requirements. The commonly used loops in C++ are:
1. while Loop
The while loop executes a block of code as long as a specified condition is true.
while (condition) {
// Code to be executed
}
int count = 0;
while (count < 5) {
cout << "Count: " << count << endl;
count++;
}
2. do-while Loop
The do-while loop is similar to the while loop, but it executes the block of code at least once before checking the condition.
do {
// Code to be executed
} while (condition);
int i = 0;
do {
cout << "i: " << i << endl;
i++;
} while (i < 5);
3. for Loop
The for loop is used when you know the number of iterations in advance. It consists of an initialization, condition, and increment/decrement statement.
for (initialization; condition; increment/decrement) {
// Code to be executed
}
for (int i = 0; i < 5; i++) {
cout << "i: " << i << endl;
}
4. foreach Loop (C++11 and later)
The foreach loop, also known as the range-based for loop, simplifies iteration over elements of a container, such as an array or vector.
for (element : container) {
// Code to be executed
}
int arr[] = {1, 2, 3, 4, 5};
for (int element : arr) {
cout << "Element: " << element << endl;
}
Loops provide a powerful mechanism for iterating over collections, processing data, and performing repetitive tasks. Choosing the appropriate loop depends on the specific requirements of your program. It's important to ensure that the loop's condition is properly defined to prevent infinite loops. Additionally, loop control statements can be used to modify the loop's behavior and flow when necessary.