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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…