×

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

Design Patterns in C++

A design pattern offers an all-encompassing, repeatable answer to the typical issues that arise in software design. Usually, the pattern demonstrates the connections and interactions between several classes or objects....

10 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.