In C++ programming language, the repetitive operation is done through loop control instruction. There are three methods by which we can repeat a part of a program.
The for loop lets us specify three aspects of a loop in a single line:
Syntax:
for(initialization ; condition ; updation) { //statement1 //statement2 }
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
cout << 5*i<<"\n";
}
return 0;
}
5
10
15
20
25
30
35
40
45
50
Just like nested if-else, we can make use of nested for loop as per our requirement.
Syntax:
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement;
}
}
In C++, the while loop is an entry-controlled loop (Entry Controlled Loops are used when checking a test condition is mandatory before executing the loop body). It is typically used when the number of iterations is unknown.
Syntax:
initialization;
while(condition)
{
//code to be executed
updation;
}
#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{
cout <<i <<"\n";
// update expression
i++;
}
return 0;
}
1
2
3
4
5
The do-while loop in C++ is an exit-controlled loop; unlike the for and while loops, the condition is checked at the end of the loop (i.e., after all the statements inside the do-while block have been executed), so the do-while loop runs at least once in the program even if the condition fails.
syntax:
do
{
//statements to be executed
}while(condition);
#include <iostream>
using namespace std;
int main()
{
int i = 2; // Initialization expression
do
{
// loop body
cout << i<<"\n";
// update expression
i=i+2;
} while (i < 11); // test expression
return 0;
}
2
4
6
8
10
Note: also read about the Decision-Making in C++
If you like my post, please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…