Loops are a fundamental concept in programming, allowing developers to automate repetitive tasks efficiently. In C++, loops enable the execution of a block of code multiple times based on specific conditions, making them indispensable for tasks like iterating over data structures, implementing algorithms, or performing repetitive computations.
C++ provides various types of loops, each suited for different scenarios:
Syntax:
for (initialization; condition; increment/decrement) {
// code block
}
Example:
#include <iostream>
int main() {
for (int p = 0; p<5 ; p++) {
cout<< i;
}
return 0;
}
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
Explanation:
The while loop is used when the number of iterations is not known, and the loop continues as long as a specified condition is true.
Syntax:
while (condition) {
// code block
}
Example:
#include <iostream>
int main() {
int i = 0;
while (i < 5) {
cout<< i;
i++;
}
return 0;
}
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
Explanation:
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.
Syntax:
do {
// code block
} while (condition);
Example:
#include <iostream>
int main() {
int i = 0;
do {
cout<< i;
i++;
} while (i < 5);
return 0;
}
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
Explanation:
In C, you can use loops inside other loops. These are called nested loops.
Example:
#include <iostream>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout <<i<< j;
}
}
return 0;
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
Explanation:
You can use the break statement to exit a loop prematurely, regardless of whether the loop’s condition is true.
Example:
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
Cout<< i;
}
return 0;
}
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
Explanation:
You can use the continue statement to skip the current iteration of the loop and proceed with the next iteration.
Example:
#include <iostream>
int main() {
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // Skips the rest of the loop when i equals 3
}
Cout<< i;
}
return 0;
}
Output:
i = 0
i = 1
i = 2
i = 4
Indian Institute of Embedded Systems – IIES