×

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

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++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

C++ Multimap

Definition: In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and...

4 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 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.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 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.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.