Loop in C++
Video Tutorial
Overview
Loops are used in computer programming to execute a group of instructions or a block of code multiple times without writing the same block of code repeatedly. There are mainly two types of loops: entry controlled loop and exit controlled loop. for loop and while loop is considered as entry controlled loop and do-while loop is considered as exit controlled loop.
Scope
- This article will explain the parts of the loop and types of loops.
- We will learn about basic syntax along with an example of for loop, while loop, do-while loop.
- We will also learn about Range-based for loop and infinite loop.
Introduction
Suppose you need to print the statement hello 50 times. Primitively we can do this by writing the line of code std::cout << "Hello"; 50 times. We are writing the same line of code again and again 50 times, which is time-consuming and space-consuming. An efficient code takes less time and space to execute. Using the above approach is not a good option because it consumes a lot of space and time. In such conditions, Loops or iteration statements are used. Using loop or iteration statements, we can do this by writing just a few lines of code.
How to Use Loops in C++?
Before jumping into how to use a loop in c++, Let's see how a loop works?
Loops repeat a block of code until the given condition in loop is not false. But how will the program know that the condition true or false?
We will take a variable known as an iterative or counter variable. We find i being used widely as the iterative variable. After the block of code is executed once, we will update the value of the iterative variable. We will repeat this process until the value of the iterative variable is True for the given condition.
Types of Loops
Based on when the condition is checked in the loop, We have two types of loops.
- Entry Controlled loops
- Exit Controlled Loops
Entry Controlled Loops
If the condition is checked before entering the body of the loop, then it is known as Entry controlled loop. The block of code present in the body of the loop is executed only if the condition is true.
Example: For loop and While loop.
Exit Controlled Loops
If the condition is checked after executing the block of code in the body of the loop, then it is known as Exit controlled loop. In the Exit controlled loop, The block of code in the body of the loop is executed at least once.
Example: do-while loop.
Parts of a Loop
Loops are also known as iteration statements. A loop contains mainly four parts.
- Initialization expression.
- Test expression.
- Update expression.
- The body of the loop.
Let us try to understand loops in a Reverse engineering manner. First, let us look at an example. Then understand the concept using the example.
Output:
Now we shall breakdown what happened between line number 6 and line number 9.
Initialization Expression
Before we enter into the loop, its control variables must be initialized. In initialization expression(s), we initialize the control variables. The initialization expression is executed only once and it gives the loop variable its first value.
In the example, we have considered. The Initialization Expression is i = 1 in line number 6. Here we have initialized the value of the loop variable i.e i with the value of 1.
Test Expression
We don't want to run the loop forever, the loop has to stop at a certain point where the condition is met. But how will the loop come to know that it has to stop executing the loop body? Test expression decides whether the loop-body will be executed or not. If the test expression evaluates to true i.e., 1. Then the loop-body is executed else the loop gets terminated.
In the example, we have considered. The test Expression is i <= 3 in line number 6. The loop checks this condition before executing the loop body. If the value of the test condition is False, Then the loop-body doesn't get executed.
Update Expression
The update expression changes the value of the loop variable after every execution of the loop body.
In the example, we considered, In line number 6 i++ is the update expression
The Body of the Loop
The statements which need to be repeated again and again are present in the loop-body.
In the example we considered, we wanted to print I love Scaler! 3 times. To do this, we need to execute the line cout << "I love Scaler!\n"; 3 times. Therefore we put the line of code in the body of the loop.
In a nutshell, the example we considered is the for loop. We initialized the value of i=1,test expression as i<=3 and update expression i++. We will understand for loop in a better way later in this article, along with other loops
Iteration Statements in C++
There are mainly 3 types of loops or iteration statements in C++ namely :
- for loop.
- while loop.
- do-while loop.
We will see how can we print the line Hello Scaler 5 times using different loops.
Let us look at each of the statements one by one.
-
For Loop
Syntax
Example
Output:
Explanation:
- In the loop, first, the test expression is checked. In the first iteration the value of i is 1 and the condition i<=5 is True as 1 is less than 5. Therefore the body of the loop is executed.
- Once the loop is executed, the expression is updated, i.e., i++. Now the value of i is 2, again the test expression is checked and the loop body is executed.
- After 5 iterations, the value of i becomes 6. The condition i<=5 becomes false. Therefore the loop terminates.
Flow Diagram of for Loop
-
while statement
Both for loop and while loop are entry-controlled loops. The for loop is used when the number of iterations is known in advance. We use the while loop when the number of iterations is not known in advance. Iterations are based on some Boolean conditions.
Syntax
Example
Output:
Explanation:
- In the program, first, we need to initialize the iterating variable. In the above example, we have considered i as the iterative variable and set its value to 1.
- In the while loop, first, the expression is checked. If the expression evaluates to true, then the body of the loop gets executed.
- We will increment the value of the iterating variable in the loop as per requirement.
- After execution of the body of the loop, Again the test condition is checked. If the condition expression evaluates to false, Then the control breaks out of the loop.
Flow Diagram of while loop
-
do-while Loop
We use Do-While Loop when we want to run a loop at least one time. The loop body is executed once and later the condition is checked. Syntax
Example
Output
Explanation
- In the above code, we first executed the body of the loop even before checking the condition.
- In the body of the loop, We will update the value of the iterating variable as per requirement.
- Once the body of the loop is executed, We will check the condition.
- If the condition checked is true, we will run through the loop again.
Flow Diagram of do-while Loop
Range-based for Loop
In C++ 11 standard, a special for loop is added, which is known as range-based for loop. In a range-based for loop, we can iterate through all the elements in an array, containers, or range.
Note: An array is a collection of similar data elements stored at contiguous memory locations.
A container is a holder object that stores a collection of other objects (its elements).
Syntax
Example
Here, we created an array marks[] and the contents of the array were initialized. Later in for loop inside the parenthesis, we first declared a variable (The data type of the variable should be the same as that of the collection which needs to be iterated ) followed by a : followed by a colon, the name of the collection is to be iterated.
In the body of the loop, we will print the value of the iterative variable which in turn contains the value of the collection.
Output
As we can see, through each iteration the iterating variable takes the value of the elements in the array one by one.
What is an Infinite Loop?
We know that the loop will stop executing the code in the loop-body when the condition is met or if it becomes false. What if the condition is never met or the condition is always True? Such cases are known as infinite loops.
Let us look at an infinite loops
Output
We get the line Infinite loop getting printed continuously infinite times in the console.
Important Points
- When the number of iterations is known beforehand, Use the for loop.
- When the exact number of iterations is not known but the loop termination condition is known, Use the while loop.
- When the code needs to be executed at least once, Such as menu-driven programs, use the do-while loop.
Conclusion
- There are mainly two types of loops or iteration statements, viz. Entry controlled loops and Exit controlled loop.
- A loop has four parts . Initialization expression, Test expression, Update expression, The body of the loop.
- for loop and while loop is known as Entry controlled loop and do-while loop is known as Exit controlled loop.
- The range-based loop is used to iterate through a collection.
- Loops with a condition evaluate to true always lead to an infinite loop.