×

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex execution routes.
The following is the general form of a loop statement:

Flowchart:

LOOPS IN C++

Loop control statements

Control statements in loops change the execution sequence. When execution quits a scope, all automated objects generated in that scope are discarded.

C++ supports the four loop control statements:

1. for loop

2. while loop

3. do-while loop

4. nested loops

For Loop:

A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times.

The syntax of for loop:

In C++, a for loop is written as

for (initialize; condition; increment) 
 {
 statement(x);
}

The control flow in a for loop is shown below:

1. The initial step is run first for only one time. Any loop variables can be declared and initialised at this phase. You don't have to use a statement here as long as you use a semicolon.

2. Then the condition is evaluated, if it is true, the loop's body is executed. If false, the loop’s body is skipped, and the control is handed to the statement after the For loop.

3. Once the for loop body is completed, the control flow returns to the increment statement. This sentence can be left blank if a semicolon follows the condition.

4. The condition is currently being re-evaluated. If the condition is true, the loop will be run, and the process will be repeated. When the condition is no longer true, the for loop comes to an end.

Program as an Example of For loop:

#include<iostream>
using namespace std;
 int main ()
 {
// for loop execution
 for(int n=1; n<=10;  n++ )
{
 cout <<  " the value of n: " << n << endl;
}
 return 0;
}

OUTPUT:

When the program is executed, the following result –
the value of n=1
the value of n=2
the value of n=3
the value of n=4
the value of n=5
the value of n=6
the value of n=7
the value of n=8
the value of n=9
the value of n=10

Advantages of For loop

* It enables code reuse.

*When we utilise loops, we don't have to write the same code over and over again.

*We can traverse the elements of data structures using loops (array or linked lists).

While Loop

A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when the condition no longer met.

The syntax for the while loop:

while(condition)
{
statement(x);
 }

The control flow in a While loop is shown below:

A while loop will check if its provided condition is met before running the code. The specified condition is also known as a Boolean condition, which is an expression that only returns true or false answer. The loop will run again and again through itself if the condition's result is true. The while loop, however, will terminate if the condition's conclusion is false.

Meanwhile, the while statement is contained within a while loop within the body. The while expression will run the code if the condition is satisfied.

Example of While Loop

The Following C++ program displays the odd numbers less than 50 using the while loop:

#include <iostream> 
using namespace std;
int main()
{
int x,max; 
cout<<"First 50 odd numbers\n";
x=1; 
 max =50;
 while (x<=max) 
   {
 cout << "x="<<x<<endl;
 x = x + 2; 
    }
return 0;
}

Output:

1 3 5 7 9 11 13 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49

Advantages of using while loop:

1.Like all other loops, this loop also repeat the execution of code blocks.

2. A while loop can go (repeating) as many times as necessary to achieve its goal.

3. Loops that never end (infinite loop)

4. generic syntax= while (condition is true)

Do-While Loop

Another repeated loop found in C++ programming is the do-while loop. The do-while loop can be used whenever a test condition is certain, as it enters the loop at a minimum once and then checks if the given condition is true or false.

The loop actions or statements will be repeated indefinitely as long as the test requirements are met. Three expressions are utilised to build this loop, just as they are in a while loop. Expression 1 is used to initialise the index value that appears after the loop is exited; expression 2 is used to alter the index value, and expression 3 is used to determine whether the loop should be repeated.

Syntax of Do While Loop

               Do
                  { 
                 statement(s);
                 } 
               while(expression);

in other words, do-while is equivalent to:

expression_1
do{
      statement 1
      statement 2
      _________
     _________
      Expression 2
}While (expression 3)

The control flow in a While loop is shown below:

In this loop the conditional expression appears after the loop. So, The loop's statement(s) run once before the condition is tested. If the condition expression is true, the flow of control runs the loop's statement(s) again. This procedure is repeated until the specified condition is no longer true.

Examples of Do-While Loop

Program 1:

#include<iostream>
using namespace std;
 int main ()
 { 
// Local variable declaration:
 int n= 10;   //expression1
 // do loop execution 
do
   { 
cout << " the value of n: " << n << endl;
 n= n + 1;     //expression2


 } 
while(n <= 20 );   //expression3
return 0;
 }

When the program is executed, the following result –


The value of n: 10
 The value of n: 11
The value of n: 12
the value of n: 13
 the value of n: 14
 the value of n: 15 

Program 2: Program to print the sum of even numbers using a do-while loop:

#include<iostream>
using namespace std;
int main()
{
	int n, max, sum = 0;
	cout << "\n Enter the Maximum Limit for Even Numbers = ";
           cin >> max;	
          cout <<"\n Even Numbers between 0 and "<<max<<" = ";
	for(n= 1;n<= max;n++)
	{
                          if (n%2==0 ) 
		{
                                            cout<<n<< " ";
			sum=sum+n;
		}
           }
           cout<<"\n The Sum of All Even Numbers up to "<<max<<" = "<<sum;
          return 0;
        }

When the program is executed, the output is –

Enter a number 10
2+4+6+8+10=30

Advantages of the do-while loop:

  1. At least once, a do-while loop is run.
  2. This loop makes the code readable. However, it's admittedly less commonly used than for and while loops, but when we used this loop with the while loop it makes the code less readable.

Nested Loop:

It's possible to nest one loop inside another. C++ allows for a minimum of 256 levels of nesting.

Syntax:

The syntax for a nested for loop statement in C++ is as follows –

for (initialization; cond; increment ) 
{ 
    for ( initial; cond; increment )
       {
     Loop body;
       }
   Loop body       // you can put more statements. 
 }

The syntax for a nested while loop statement in C++ is as follows –

initialization;
while(condition)
              {
                 inti
                while(cond)
                     {  
                     Loop body; 
                     incrementation
                     }  
              Loop body;    // you can put more statements. 
             Increment
                }

The syntax for a nested do...while loop statement in C++ is as follows –

inti;   
    do 
          {   
          Loop body; // you can put more statements.
          inti              
              do
               { 
                  Loop body; 
                  increment;
                  }While (cond);
           Increment;
               }While (cond);

Example of Nested Loop

Program: Program to Print prime numbers between 1 and 100 using nested for loops

#include<iostream>
 using namespace std;
 int main ()
 {
 int i, j; 
       for (i=2;i<=100;i++)
          {
              for(j=2;j<=(i/j);j++)
             {
                   if(!(i%j)) break;   // if factor found, not prime 
             }          
          if(j > (i/j)) cout << i <<\t; 
          } 
       return 0; 
    }

When the program is executed, the output is –

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

ADVANTAGES OF NESTED LOOPS:

1. A nested loop is a loop structure in which one loop is contained within another.

2. It comes in handy when dealing with many iterations.

3. The amount of Memory space used will be lowered.


Related Topics

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

C++ Memory Management

Memory management is a method of controlling computer memory and allocating memory space to applications to increase overall system performance. What is the purpose of memory management? Because the array contains homogeneous...

4 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.