Loops are used to continuously run a statement or block of statements until the condition is true. These statements are sometimes known as repetitive or iterative statements.
How Do Loops in C++ Work?
Until a specific condition is met, a sequence of statements is executed.
The curly braces that surround the loop body contain the number of statements that will be executed.
Every time the loop body is executed, the condition is evaluated to see if it is true, and if it is true, the loop body is repeated.
The loop body won’t be performed if the condition check appears to be false.
Different Types of Loops in C++
There are mainly three types of loops in C++, they are:
- for loop
- while loop
- do-while loop
1. for loop
For loop is the most used type of loop in C++. When we know the exact number of repetitions in advance, the for loop is an excellent option in this case.
The general syntax of for loop is:
for (initialization; condition; increment/decrement)
statement;
The above for loop syntax is for a single statement for
loop, and if you have multiple statements in a loop, then the syntax will be:
for (initialization; condition; increment/decrement)
{
Statement1;
Statement2;
.
.
.
StatementN;
}
For one statement, there is no need for braces {}
while in the second form, multiple statements are used, so they are enclosed in the pair of braces {}
.
The primary purpose of a for loop is to repeatedly execute a statement or set of statements as long as the condition is true.
How Does The ‘for loop’ Work?
Below is the process a for loop in C++ work;
- Initialization: Typically, it involves establishing a counter variable’s initial value. This is only executed once.
- Condition: The loop continues if it is true; the loop is terminated, and the statement is skipped (not executed).
- Increment/Decrement: The loop counter is incremented/decremented, and control goes back to the second step, which is the condition.
- Loop Body: It can either be a single statement or a block of statements enclosed in curly braces { }.
Consider the following example, which will clarify the concept of using for loop in C++.
Let’s say we want to display numbers from 1 to 5.
First of all, let’s do it without using a loop.
#include <iostream> using namespace std; int main() { // Print numbers from 1 to 5 cout << "1" << endl; cout << "2" << endl; cout << "3" << endl; cout << "4" << endl; cout << "5" << endl; return 0; }
OUTPUT:
1
2
3
4
5
Now, let’s achieve the same thing using a LOOP.
#include <iostream> using namespace std; int main() { // Loop to print numbers from 1 to 5 for (int i = 1; i < 6; i++) { cout << i << endl; } return 0; }
OUTPUT:
1
2
3
4
5
See how a loop can make your program easier and shorter.
Here is another example of for loop in C++.
#include <iostream> using namespace std; int main() { int i; // Prompt the user to enter a number cout << "Enter a Number: "; cin >> i; // Countdown using a for loop for (i; i > 0; i--) { cout << i << endl; } return 0; }
OUTPUT:
Enter a Number= 10
10
9
8
7
6
5
4
3
2
1
Using the initialization and increment/decrement fields is not always necessary. Although they can be left empty, there must always be written semicolon signs between them.
For instance, if we wanted to declare no initialization and no increment, we might write: for ( ; i < 5 ; )
.
int i= 0; for ( ; i < 5; ) { cout << “ i << “, “; i++; }
OUTPUT:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
For example, if we want to include an increment/decrement expression but no initialization, we can use the for loop like for (; i < 5; i++)
.
2. while loop
Another programming structure used in C++ programs is the while loop, which repeats a statement or set of statements until a condition is satisfied.
The general syntax of the while loop is:
while (condition)
{
Statement1;
Statement2;
Statement3;
.
.
.
StatementN;
}
How Does The ‘while loop’ Work?
The while loop has three parts, similar to the for loop: initialization, condition, and increment/decrement.
The initialization is done here before the while
clause, and the incrementing/decrementing is done inside the while loop’s body.
Consider the following example, which will clarify the concept of using a while loop in C++.
#include <iostream> using namespace std; int main() { int num = 1; // Loop to print numbers from 1 to 30 while (num <= 30) { // Print the current number followed by a space cout << num << " "; // Check if ten numbers have been printed, then move to the next line if (num % 10 == 0) cout << endl; // Increment the number num++; } return 0; }
OUTPUT:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
The key difference between a while loop and a for loop is that a while loop does not need knowing the exact number of iterations in advance, but a for loop must.
3. do-while loop
A programmer might sometimes want to run the loop at least once to resolve a problem. The do-while loop in C++ makes this possible.
The general syntax of the do-while loop is:
do
{
Statement1;
Statement2;
.
.
.
StatementN;
}
while (condition);
How Does The ‘do-while’ Loop Work?
The only difference between the do-while loop and the while loop is that the do-while loop checks the condition after the body of the loop has been executed.
Even if the condition is false
, the do-while loop’s execution ensures that the statements in its body are executed at least once.
Consider the following example, which will clarify the concept of using a do-while
loop in C++.
#include <iostream> using namespace std; int main() { int num; // Repeat until user enters 0 do { // Prompt the user to enter a number cout << "Enter any number (Enter 0 to stop): "; cin >> num; // Display the entered number cout << "You entered: " << num << "\n"; } while (num != 0); // Continue looping until user enters 0 return 0; }
OUTPUT:
Enter Any Number (Enter 0 to Stop): 14
You Entered: 14
Enter Any Number (Enter 0 to Stop): 17
You Entered: 17
Enter Any Number (Enter 0 to Stop): 21
You Entered: 21
Enter Any Number (Enter 0 to Stop): 0
You Entered: 0
Nested Loops
The use of one loop inside the body of another loop is called a nested loop. The enclosed loop is known as the inner loop, while the enclosing loop is known as the outer loop.
The general syntax of the Nested loop:
for (initialization; condition; increment/decrement)
{
for (initialization; condition; increment/decrement)
{
Statement1;
Statement2;
Statement3;
.
.
.
StatementN;
}
}
Example of Nested Loop:
Consider the following example, which will clear the concept of using nested loops in C++.
#include <iostream> using namespace std; int main() { // Outer loop iterates from 1 to 10 int j = 1; while (j <= 10) { int i = 1; // Inner loop iterates from 1 to the current value of outer loop variable j while (i <= j) { // Print the current value of inner loop variable i cout << i; i++; } // Print a new line at the end of each row cout << endl; j++; } return 0; }
OUTPUT:
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910