Loops in C++

In this section of the C++ tutorial, let’s discuss the concept of loops in C++. Loops in C++ programming are used when a sequence of statements is to be executed repeatedly.

Loops in C++

There are times when you want the same thing to happen numerous times. For example, if you want to print a table of 2, how would you do that?

2*1=2

2*2=4

2*3=6

2*4=8

2*5=10

2*6=12

2*7=14

2*8=16

2*9=18

2*10=20

Would you print each step one by one?

It won’t be a smart way. Right?

That’s where you will need the concept known as loops in the programming language.

C++ Program to Print Table of Any Number

#include<iostream>
using namespace std;
int main()
{
int i,n=2;
for(i=1;i<=10;++i)
cout<<"\n"<<n<<" * "<<i<<" = "<<n*i;
return 0;
}

Output:

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Types of Loops in C++

Type of Loops Description
while loop It is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
for loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Do while loop A do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block.
Nested loops A nested loop is a loop within a loop, an inner loop within the body of an outer one.

Infinite loop

An infinite loop (sometimes referred to as an endless loop) is a coding piece that lacks a functional exit to repeat indefinitely. When a condition always evaluates to true, an infinite loop occurs.

Example of Infinite loop

#include <iostream> 
using namespace std; 
int main () 
{ 
int i;
for ( ; ; ) 
{ 
cout << "This is an example of infinite loop using for loop.\n"; 
}

while (i != 0) 
{ 
i-- ; 
cout << "This is an example of infinite loop using while loop.\n"; 
} 
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart