C++ Loops
Loops in C++:
1. for Loop:
The for loop is commonly used when you know the number of iterations in advance. It consists of an initialization statement, a condition, and an iteration statement.
#include <iostream>
int main() {
// Syntax: for (initialization; condition; iteration)
for (int i = 0; i < 5; ++i) {
std::cout << "Iteration " << i + 1 << std::endl;
}
return 0;
}
2. while Loop:
The while loop is used when you want to repeatedly execute a block of code as long as a condition is true. The condition is checked before the loop body is executed.
#include <iostream>
int main() {
// Syntax: while (condition)
int count = 0;
while (count < 5) {
std::cout << "Count: " << count << std::endl;
++count;
}
return 0;
}
3. do-while Loop:
The do-while loop is similar to the while loop, but it guarantees that the loop body is executed at least once, even if the condition is false initially.
#include <iostream>
int main() {
// Syntax: do { /* code */ } while (condition);
int count = 0;
do {
std::cout << "Count: " << count << std::endl;
++count;
} while (count < 5);
return 0;
}
Loop Control Statements:
a. break Statement:
The break statement is used to exit the loop prematurely.
#include <iostream>
int main() {
for (int i = 0; i < 10; ++i) {
std::cout << i << " ";
if (i == 5) {
break; // Exit the loop when i equals 5
}
}
return 0;
}
b. continue Statement:
The continue statement is used to skip the rest of the loop body and move to the next iteration.
#include <iostream>
int main() {
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
std::cout << i << " ";
}
return 0;
}
Loops are fundamental for creating efficient and flexible programs. Depending on the situation, you may choose the loop type that best fits your requirements. Understanding loop control statements (break and continue) is also important for managing the flow of your loops.