Loop or iteration or repetition is a programming construct that allows a set of instructions to be executed multiple times until a specific condition is met.
Loops are used to perform repetitive tasks without having to write the same code multiple times. They are fundamental in programming and are used in various applications, such as processing data, automating tasks, and creating interactive programs.
Except processes (web servers) that runs without stopping which are placed in an infinite loop, it is important to always ensure that loops have a proper termination condition.
Apart from servers, many computing processes such as embedded systems and microcontrollers, Graphical User Interfaces (GUIs), operating system tasks, device drivers and monitoring tools, event-driven applications,etc. are intentionally designed to run in an infinite loop—often called an event loop or main loop — to ensure they continuously monitor, respond, or function until the system is turned off or terminated.
Infinite loops can cause a program to hang or consume excessive system resources.
There are three main types of loops in C++ and other programming languages:
A for loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The syntax of a for loop in C++ is as follows:
for (initialization; condition; update) {
// code to be executed
}
In a for loop, the initialization step is executed only once at the beginning of the loop. The condition is evaluated before each iteration, and if it evaluates to true, the code block inside the loop is executed. After each iteration, the update step is executed, which typically modifies the control variable.
The update is done either by increasing (++) or decreasing (--) the control variable.
For instance if the control variable is i, the increment will be i++ and the decrement will be i--.
In most programming languages like C+++, you must declare and initialize the control variable before the loop.
For instance if we want to start the loop from 1 to 10, we can initialize the control variable as int i = 1;.
When ascending (from least to highest), the control variable is increased.
When descending (from highest to least), the control variable is decreased.
You have to use appropriate comparator operators (e.g., <, >, <=, >=) in the condition to make the condition true from start and end at a point.
For instance, if we want the loop to iterate from 1 to 10, we can use any of the following conditions if we have initialized a control variable i to 1:
i < 11i <= 10The first condition reads as i is less than 11. The loop will continue as long as i is less than 11.
i increases after each iteration.
Note: most programmers use i as the control variable because of the word iteration but you can use any variable name of your choice.
| Iteration Number | Calculation | Value of i | Loop Status |
| 1 | i = 1 | 1 | True, loop continues (since 1 < 11) |
| 2 | i = 1 + 1 | 2 | True, loop continues (since 2 < 11) |
| 3 | i = 2 + 1 | 3 | True, loop continues (since 3 < 11) |
| 4 | i = 3 + 1 | 4 | True, loop continues (since 4 < 11) |
| 5 | i = 4 + 1 | 5 | True, loop continues (since 5 < 11) |
| 6 | i = 5 + 1 | 6 | True, loop continues (since 6 < 11) |
| 7 | i = 6 + 1 | 7 | True, loop continues (since 7 < 11) |
| 8 | i = 7 + 1 | 8 | True, loop continues (since 8 < 11) |
| 9 | i = 8 + 1 | 9 | True, loop continues (since 9 < 11) |
| 10 | i = 9 + 1 | 10 | True, loop continues (since 10 < 11) |
| 11 | i = 10 + 1 | 11 | False, loop terminates (since 11 is not less than 11) |
The second condition reads as i is less than or equal to 10. The loop will continue as long as i is less than or equal to 10.
i increases after each iteration.
| Iteration Number | Calculation | Value of i | Loop Status |
| 1 | i = 1 | 1 | True, loop continues (since 1 < 10) |
| 2 | i = 1 + 1 | 2 | True, loop continues (since 2 < 10) |
| 3 | i = 2 + 1 | 3 | True, loop continues (since 3 < 10) |
| 4 | i = 3 + 1 | 4 | True, loop continues (since 4 < 10) |
| 5 | i = 4 + 1 | 5 | True, loop continues (since 5 < 10) |
| 6 | i = 5 + 1 | 6 | True, loop continues (since 6 < 10) |
| 7 | i = 6 + 1 | 7 | True, loop continues (since 7 < 10) |
| 8 | i = 7 + 1 | 8 | True, loop continues (since 8 < 10) |
| 9 | i = 8 + 1 | 9 | True, loop continues (since 9 < 10) |
| 10 | i = 9 + 1 | 10 | True, loop continues (since 10 <= 10) |
| 11 | i = 10 + 1 | 11 | False, loop terminates (since 11 is not less than or equal to 10) |
For example, the following for loop prints the numbers from 1 to 10 as explained:
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
Since there is no newline character in the cout statement, all the numbers will be printed on the same line.
If we wish each number to be printed on a new line, we can add a newline character (\n) to the cout statement:
for (int i = 1; i <= 10; i++) {
cout << i << endl;
}
To loop in a descending order, we can display the numbers from 10 to 1:
If we initialize our control variable i to 10 and the loop is supposed to continue while i is greater than 0, our condition will be i > 0:
i = 10
| Iteration Number | Calculation | Value of i | Loop Status |
| 1 | i = 10 | 10 | True, loop continues (since 10 > 0) |
| 2 | i = 10 - 1 | 9 | True, loop continues (since 9 > 0) |
| 3 | i = 9 - 1 | 8 | True, loop continues (since 8 > 0) |
| 4 | i = 8 - 1 | 7 | True, loop continues (since 7 > 0) |
| 5 | i = 7 - 1 | 6 | True, loop continues (since 6 > 0) |
| 6 | i = 6 - 1 | 5 | True, loop continues (since 5 > 0) |
| 7 | i = 5 - 1 | 4 | True, loop continues (since 4 > 0) |
| 8 | i = 4 - 1 | 3 | True, loop continues (since 3 > 0) |
| 9 | i = 3 - 1 | 2 | True, loop continues (since 2 > 0) |
| 10 | i = 2 - 1 | 1 | True, loop continues (since 1 > 0) |
| 11 | i = 1 - 1 | 0 | False, loop terminates (since 0 is not greater than 0) |
For example, the following for loop prints the numbers from 10 to 1 as explained:
for (int i = 10; i > 0; i--) {
cout << i << " ";
}
For fun sake, let's print "*" characters 5 times:
Since our task is to display 5 starts (*), we can intialize our control variable to 1 and the loop is supposed to start at 5, hence our condition will either be i <= 5 or i < 6.
Since our task is to display horizontally, we won't use the newline character:
for (int i = 1; i <= 5; i++) {
cout << "*";
}
Aternatively,
for (int i = 1; i < 6; i++) {
cout << "*";
}
Alternatively,
for (int i = 0; i < 5; i++) {
cout << "*";
}
Since our task is to display vertically, we will use the newline character:
for (int i = 1; i <= 5; i++) {
cout << "*" << endl;
}
Aternatively,
for (int i = 1; i < 6; i++) {
cout << "*" << endl;
}
Alternatively,
for (int i = 0; i < 5; i++) {
cout << "*" << endl;
}
A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The syntax of a while loop in C is as follows:
while (condition) {
// code to be executed
// update control variable
}
In a while loop, the condition is evaluated before each iteration. If the condition evaluates to true, the code block inside the loop is executed. The loop continues until the condition becomes false.
For example, the following while loop prints the numbers from 1 to 5:
int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}
The control variable is i and its value is updated within the loop to ensure the loop terminates when the condition becomes false.
Note: if there is no update to the control variable within the loop, it may result in an infinite loop and the program may hang, freeze or crash.
To intentionally create an infinite loop, you can use a condition that always evaluates to true, such as while (1).
For example, the following while loop creates an infinite loop:
while (1) {
// code to be executed
}
The code below runs an infinite loop:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while(1){
cout << i << endl;
i++;
}
return 0;
}
You can also use while(true)
The code will look like this:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while(true){
cout << i << endl;
i++;
}
return 0;
}
You should only use an infinite loop when it is intentional and you have specific need for it.
In this example, the while loop will continue to execute indefinitely, printing the value of i and incrementing it by 1 on each iteration. The loop will only stop if the program is manually terminated.
A do-while loop is a control flow statement that allows code to be executed at least once and then repeatedly based on a given boolean condition. The syntax of a do-while loop in C is as follows:
do {
// code to be executed
// update control variable
} while (condition);
In a do-while loop, the code block inside the loop is executed first, and then the condition is evaluated. If the condition evaluates to true, the loop continues; otherwise, it terminates.
Since the condition is checked after the first iteration, the code block is guaranteed to execute at least once.
For example, the following do-while loop prints the numbers from 1 to 5:
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
It is mostly used to repeatedly ask a user for input until a valid response is received.
Let's modify our previous grading system that we built earlier to use a do-while loop to repeated ask the user to enter a score until a user enters a score between 0 to 100.
Our previous code was:
#include <iostream>
using namespace std;
int main() {
int score;
cout << "Enter your score: ";
cin >> score;
if (score >= 75) {
cout << "Your grade is 1." << endl;
} else if (score >= 70) {
cout << "Your grade is 2." << endl;
} else if (score >= 65) {
cout << "Your grade is 3." << endl;
} else if (score >= 60) {
cout << "Your grade is 4." << endl;
} else if (score >= 55) {
cout << "Your grade is 5." << endl;
} else if (score >= 50) {
cout << "Your grade is 6." << endl;
} else if (score >= 45) {
cout << "Your grade is 7." << endl;
} else if (score >= 40) {
cout << "Your grade is 8." << endl;
} else {
cout << "Your grade is 9." << endl;
}
return 0;
}
We will put the taking of the value from the user in a loop to continually ask the user to enter until a valid response is given.
Caption of the part to modify is below:
do{
cout << "Enter your score (0 - 100): ";
cin >> score;
}while((score < 0)||(score > 100));
The do-while loop first asks the user to enter the score. If a user enters the correct range of score, the condition in the do-while loop will be false and the loop ends but if not, the loop will be repeated until user enters the correct input.
Our updated code will be:
#include <iostream>
using namespace std;
int main() {
int score;
do{
cout << "Enter your score (0 - 100): ";
cin >> score;
}while((score < 0)||(score > 100));
if (score >= 75) {
cout << "Your grade is 1." << endl;
} else if (score >= 70) {
cout << "Your grade is 2." << endl;
} else if (score >= 65) {
cout << "Your grade is 3." << endl;
} else if (score >= 60) {
cout << "Your grade is 4." << endl;
} else if (score >= 55) {
cout << "Your grade is 5." << endl;
} else if (score >= 50) {
cout << "Your grade is 6." << endl;
} else if (score >= 45) {
cout << "Your grade is 7." << endl;
} else if (score >= 40) {
cout << "Your grade is 8." << endl;
} else {
cout << "Your grade is 9." << endl;
}
return 0;
}
We can also use a loop to make our program run multiple times until a user enters a particular number or character to exit the program.
We will modify the grading program above and place it in a while loop. We will ask a user to enter 0 to exit the program and any other number to continue.
We first have to initialize our control variable to a number which is not 0.
#include <iostream>
using namespace std;
int main() {
int score;
int exit = 1;
while(exit !=0){
do{
cout << "Enter your score (0 - 100): ";
cin >> score;
}while((score < 0)||(score > 100));
if (score >= 75) {
cout << "Your grade is 1." << endl;
} else if (score >= 70) {
cout << "Your grade is 2." << endl;
} else if (score >= 65) {
cout << "Your grade is 3." << endl;
} else if (score >= 60) {
cout << "Your grade is 4." << endl;
} else if (score >= 55) {
cout << "Your grade is 5." << endl;
} else if (score >= 50) {
cout << "Your grade is 6." << endl;
} else if (score >= 45) {
cout << "Your grade is 7." << endl;
} else if (score >= 40) {
cout << "Your grade is 8." << endl;
} else {
cout << "Your grade is 9." << endl;
}
/* Alert user to enter 0 to exit or other number to continue and get the value from the user */
cout << "Enter 0 to exit or any other number to continue: ";
cin >> exit;
}
return 0;
}