Loops in C plus plus or C++ loops are used to execute a block of code multiple times until a certain condition is met. They are essential in scenarios where repetitive tasks need to be automated efficiently in the program.
Loops help reduce repetition and redundancy in a code. They make an easy, simple implementation of a block of code more than once. In this article, we will understand the need to implement C++ loops and learn how to implement the C++ loops in our program.
Types of Loops in C++
C plus plus provides three major types of loops, including the:
- For Loop
- While Loop
- Do-While Loop
Also, a Range-Based For Loop (introduced in C++11) is used for iterating over arrays or collections.
For Loop
The for loop is used when we know how many times we need to run a block of code. It is used when the number of iterations is known in advance. It consists of three parts, including:
- Initialization: Executed once at the beginning
- Condition: Checked before each iteration. If this condition is true, then only the loop continues
- Update: Executes after each iteration
Syntax |
---|
for (initialization; condition; update ) { // Code to Execute
} |
Properties of For Loop
- The For Loop is an entry-controlled loop where the condition is checked before execution
- For loop in C++ is used when the number of iterations is known already or beforehand.
- The for loop in C plus plus is easy to read and compact in its form.
- For loop can include multiple initialization and update expressions
Examples of C++ For Loop |
---|
#include <iostream>
using namespace std; int main() { for (int i = 1; i <=5; i++) { cout << “Iteration” << i << endl; } return 0; } |
Output:
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 |
While Loop
The while loop is used when we do not have an idea of how many times we need to run a block of code. It is used when the number of iterations is unknown and depends on a condition that is evaluated before each iteration.
While loop only consists of the condition that is used to check whether the following condition satisfies to enter the loop or not. If the condition is true, then only the loop continues; otherwise, it breaks out of the loop.
Syntax |
---|
while (condition) {
// Code to Execute } |
Properties of While Loop
- The while loop in C plus plus is an entry-controlled loop that checks the condition before executing the body of the loop
- The while loop is used when the number of iterations is unknown or how many times the block of code needs to run is not known in advance
- The while loop can result in an infinite loop if the condition is never false
Example of C++ While Loop |
---|
#include <iostream>
using namespace std; int main() { int i = 1; while ( i <= 5) { cout << “Iteration” << i << endl; i++; } return 0; } |
Output:
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 |
Example of C++ While Infinite Loop
We can run the While loop for an infinite number of times when the condition always evaluates to true especially when there is no stopping condition in the while loop.
Example of an Infinite Loop |
---|
int i = 1;
while ( i > 0 ) { cout << i << “ “ ; i++; } |
This loop will keep running indefinitely unless we stop it manually |
Do-While Loop
The do-while loop in C++ is similar to the while loop, but it executes at least once, even if the condition is false. It contains a do block that consists of the code to execute and after a while condition that verifies the condition whether it is fit to enter the loop body or do body or not.
C++ Do-While Loop Syntax |
---|
do {
// Code to Execute } while (condition); |
<d
Properties of Do-While Loop
- A do-while loop is an exit-controlled loop as the loop body executes first, and then the condition is checked
- The do-while loop ensures at least one iteration occurs, even if the condition is false initially
- The do-while loop is useful when you need to execute a task first and check conditions later.
Also, Check C++ conditionals: If, Else, and Nested Conditional Statements
Example of Do-While loop |
---|
#include <iostream>
using namespace std; int main() { int i = 1; do { cout << “Iteration” << i << endl; i++; } while ( i <= 5 ); return 0; } |
Output:
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 |
One Time Running Do While Loop
This loop will execute at least once in the program, whether or not the conditionis satisfied or not in the program.
Example of Do-While loop That Runs Once |
---|
int num = 10;
do { cout << “This will print at least once!” << endl; } while ( num < 5 ); |
Even though “num < 5” is false, the message still prints once! |
Range-Based For Loop (C++11)
The range-based for loop is introduced in C++11. The range-based for loop simplifies iteration over arrays and containers. The for loop here only contains an element type variable and a collection from which this variable is being picked.
Syntax |
---|
for (element_type variable: collection) {
//Code to Execute } |
Properties of Range-Bound For Loop
- The range-bound for loop simplifies the iteration over the collection of elements, such as arrays or containers.
- The range-bound for loop automatically handles the size of the collection
- The range-bound for loop does not require explicit indexing
Example of Range-Bound For Loop |
---|
#include <iostream>
using namespace std; int main() { int arr[ ] = {1, 2, 3, 4, 5}; for (int num : arr) { cout << num << “ “; } return 0; } |
Output:
1 2 3 4 5 |
Example of C++ Loops with Vectors
Let us check a simple example of C plus plus loops with the data structure Vectors and see the output of the result.
Example with Vectors |
---|
#include <iostream>
#include <vector> using namespace std; int main() { vector<int> numbers = {10, 20, 30, 40}; for (int num : numbers) { cout << num << “ “; } return 0; } |
Output:
10 20 30 40 |
Entry Controlled Loop vs Exit Controlled Loops
Let us know some common differences between the entry controlled loops and exit controlled loops with their effects in detail.
Entry-Controlled vs Exit-controlled Loops |
|
---|---|
Entry-Controlled Loops | Exit Controlled Loops |
The loop condition is checked before executing the loop body. | The loop body is executed first, and then the condition is checked. |
for loop, while loop | do-while loop |
May not execute if the condition is false initially. | Executes at least once, even if the condition is false. |
When the number of iterations is determined beforehand or needs to be checked before execution. | When the loop must execute at least once before checking the condition. |
for(int i = 0; i < 5; i++) | do { … } while(condition); |
Iterating over known ranges, loops that require a pre-check. | Menu-driven programs, input validation, and retry mechanisms. |
Benefits of Using C++ Loops In Program
Some of the major benefits of using C++ loops in programs, especially for beginners, are mentioned below.
- The biggest advantages of C++ loops are that they reduce writing repetitive code in a program, which means executing the same block multiple times and hence saving a lot of time and effort that used to go to waste.
- It is ideal for automating repetitive tasks while iterating over arrays, data processing, game loops, and more. It helps in handling large datasets easily online.
- It also enhances the code readability and maintainability, which also makes the code debugging easier.
- It supports user input dynamically and is great for cases when you have to take multiple inputs from users until a condition is met.
- It is essential for sorting, searching, and traversing big data structures and is used in linked lists, trees, graphs, and recursion operations.
- It optimizes execution time and hence reduces the chances of error as the logic is applied consistently over the program.
Learn C++ Loops With PW Skills Course
Get enrolled in the PW Skills Decode DSA With C++ Course to get familiar with the programming fundamentals of C++ programming language and get in-depth learning from dedicated mentors and interactive classes throughout the course duration. Get industry led live sessions, recorded versions, and more with the C Plus Plus DSA Course on PW Skills.
Solve practice questions and capstone projects throughout the program and build your knowledge in C++ loops, syntax, data structures, and plenty more topics to gain complete proficiency in this programming language only at pwskills.com
C++ Loops FAQs
Q1. When should I use a for loop instead of a while loop?
Ans. A for loop is used when we know how many times the iteration has to take place, unlike loops. So wherever we know about the number of iterations in advance, we use a for loop instead of a while loop.
Q2. How do you use a for loop in a C++ program?
Ans. The for loop is used when we know how many times we need to run a block of code. It is used when the number of iterations is known in advance. The syntax of the for loop is mentioned above in the article.
Q3. Which is the most used loop statement in C++?
Ans. The while loop is one of the most commonly used loop statements in C++.
Q4. When will the for loop run for infinite time in a C++ program?
Ans: A for loop will run for an infinite time when the condition always evaluates to true. Suppose in For loop we are not providing any condition to stop the loop from running;A then it will run for an infinite time duration until interpreted by any external conditions.