loops are used to execute a block of code repeatedly as long as a specified condition is met. There are several types of loops in C++: for
, while
, do-while
, and the range-based for
loop. Here’s a detailed explanation of each:
for
LoopThe for
loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and update. The syntax is:
for (initialization; condition; update) {
// code to be executed
}
Example:
for (int i = 0; i < 10; i++) {
std::cout << "i: " << i << std::endl;
}
while
LoopThe while
loop is used when the number of iterations is not known and depends on a condition. The syntax is:
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i < 10) {
std::cout << "i: " << i << std::endl;
i++;
}
do-while
LoopThe do-while
loop is similar to the while
loop, but it guarantees that the loop body is executed at least once. The syntax is:
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
std::cout << "i: " << i << std::endl;
i++;
} while (i < 10);
for
Loop (C++11 and later)The range-based for
loop is used to iterate over elements in a container (like arrays, vectors, etc.). It simplifies the syntax and enhances readability. The syntax is:
for (type variable : container) {
// code to be executed
}
Example:
int arr[] = {1, 2, 3, 4, 5};
for (int num : arr) {
std::cout << "num: " << num << std::endl;
}
Loops can be nested inside other loops. Each loop will run its full course for every iteration of the outer loop.
Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
std::cout << "i: " << i << ", j: " << j << std::endl;
}
}
break
: Terminates the loop and transfers control to the statement immediately following the loop.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
std::cout << "i: " << i << std::endl;
}
continue
: Skips the current iteration of the loop and proceeds with the next iteration.
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << "i: " << i << std::endl;
}