Cyberithub

Tutorial: Loops in C++(v17) with best examples

Advertisements

In this tutorial, I am going to take you through the concepts of Loops in C++. It is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". In the Programming World, loops are frequently used to run a block of code multiple times to perform an Operation or Task. Hence it is very important to understand the functionality of Loops in C++.

 

Tutorial: Loops in C++(v17) with best examples 1

Loops in C++

There comes a need to execute some portion of the program either a specified number of times or until a particular condition is satisfies.
This repetitive task can be done by using various loops control instruction.

There are basically 3 ways by using which we can repeat a part of a program.

Using a "for" statement

for is the most popular looping instruction. It allow us to specify three things about a loop in a single line.
a)setting a loop counter to an initial value.
b)Testing the loop counter to determine whether its value has reached the number of rpetitions desired.
c)Increasing the value of loop counter each time the program segment within the loop has been executed.

Syntax

for(intialise counter ; test counter ; increment counter)
{
execute statement 1;
execute statement 2;
execute statement 3;
............
}

Example

#include <iostream>
using namespace std;
int main () {
int i, n;
cout<<"Enter the end value"<<"\n";
cin>>n;
for(i=0; i<=n; i++)
{
cout<<i<<"\t";
}

return 0;
}

Using a "while" statement

When we use while loop, condition is evaluated first and if it returns true then the block of code inside while loop execute,
Once the condition returns false, control comes out from the loop.

Syntax

initialise counter;
while(condition)
{
execute statement 1;
execute statement 2;
........
counter++;
}

Example

#include <iostream>
using namespace std;
int main () {
int i=1, n;
cout<<"Enter the end value"<<"\n";
cin>>n;
while(i<=n)
{
cout<<i<<"\t";
i++;
}

return 0;
}

Using a "do-while" statement

In do-while loop, loop condition is checked at the bottom of the loop.Hence statements in the loop is executed once before the condition is tested.

Syntax

do {
execute statement 1;
execute statement 2;
........
} while( condition );

Example

#include <iostream>
using namespace std;
int main () {

int n, i=1;
cout<<"Enter the end value"<<"\n";
cin>>n;
cout<<"Number series till end value"<<"\n";

do {
cout<<i<<"\t";
i++;
}while( i <= n );

return 0;
}

Also Read: Constructor in C++

Reference: C++ Tutorials

Leave a Comment