C++ Tutorial Index

C++ Tutorial C++ History C++ Installation C++ First Program C++ cin and cout C++ Data type C++ Variable C++ operator C++ Keywords

C++ Control Statements

C++ If C++ Nested if C++ If-else C++ If-else-if C++ Switch C++ Break C++ Continue C++ Goto C++ For loop C++ While loop C++ Do while loop

C++ Functions

C++ Call by Value C++ Call by Reference C++ Recursion Function C++ Inline function C++ Friend function

C++ Arrays

Single dimension array Two dimension array

C++ Strings

C++ Strings

C++ Inheritance

C++ Inheritance Single level Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance

C++ Polymorphism

C++ Polymorphism C++ Overloading C++ Overriding C++ Virtual Function

C++ Pointers

C++ Pointers C++ this pointer

C++ Exception Handling

C++ Exception Handling

C++ Constructors

C++ Constructors Default Constructor Parameterize Constructor Copy constructor Constructor Overloading Destructor

C++ File Handling

C++ File Handling C++ Writing to file C++ Reading file C++ Close file

Miscellaneous

C Vs C++ C++ Comments C++ Data Abstraction C++ Identifier C++ Memory Management C++ Storage Classes C++ Void Pointer C++ Array To Function C++ Expressions C++ Features C++ Interfaces C++ Encapsulation std::min in C++ External merge sort in C++ Remove duplicates from sorted array in C++ Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ C++ References C++ Friend Functions C++ Mutable keyword Unary Operators in C++ Initialize Array of objects with parameterized constructors in C++ Differences between #define & const in C/C++ C++ Program to Implement Shell Sort C++ Program to Implement Merge Sort Storage Classes in C Vector resize() in C++ Passing by Reference Vs. Passing by the pointer in C++ Free vs delete() in C++ goto statement in C and C++ C++ program to read string using cin.getline() C++ String Concatenation Heap Sort in C++ Swap numbers in C++ Input Iterators in C++ Fibonacci Series in C++ C ++ Program: Alphabet Triangle and Number Triangle C++ Program: Matrix Multiplication C++ Program to Print Fibonacci Triangle Stack in C++ Maps in C++ Queue in C++ C++ Bitset C++ Algorithms Priority Queue in C++ C++ Multimap C++ Deque Function Pointer in C++ Sizeof() Operators in C++ C++ array of Pointers free() Vs delete in C Timsort Implementation Using C++ CPP Templates C++ Aggregation C++ Enumeration C++ Math Functions C++ Object Class C++ Queue Initialize Vector in C++ Vector in C++ C++ STL Components Function overloading in C++ C++ Maximum Index Problem C++ find missing in the second array C++ Program to find the product array puzzle C++ Program To Find Largest Subarray With 0 Sum C++ Program To Move All Zeros To The End Of The Array C++ Program to find the element that occurs once C++ Program to find the largest number formed from an array Constructor Vs Destructor C++ Namespaces C++ OOPs Concept C++ Static C++ Structs C++ Try-Catch C++ User Defined Exceptions C++ Virtual Destructor C++ vs C# Malloc() and new in C++ Palindrome Number Program in C++ Snake Code in C++ Splitting a string in C++ Structure Vs Class in C++ Virtual Function Vs Pure Virtual Function C++ Bidirectional Iterators C++ Forward Iterators C++ Iterators C++ Output Iterators C++ Range-based For Loop Converting string into integer in C++ LCM Program in C++ Type conversion in C++ Add two numbers using the function in C++ Advantage and disadvantage friend function C++ Armstrong Number Program in C++ ATM machine program in C++ using functions Binary to Decimal in C++ Bit Manipulation in C++ C++ Constructor C++ Dijkstra Algorithm Using the Priority Queue C++ int into String C++ Signal Handling Decimal to Binary in C++ Decimal to Hexadecimal in C++ Decimal to Octal in C++ Factorial Program in C++ Function in C++ Hexadecimal to Decimal in C++ Octal to Decimal in C++ Reverse a Number in C++ Structure Vs Class in C++ C++ Forward Iterators C++ Output Iterators C++ Prime number program Char Array to String in C++ Constructor Overloading in C++ Default arguments in C++ Different Ways to Compare Strings in C++ Dynamic Binding in C++ Program to convert infix to postfix expression in C++ SET Data Structure in C++ Upcasting and Downcasting in C++ Reverse an Array in C++ Fast Input and Output in C++ Delete Operator in C++ Copy elision in C++ C++ Date and Time C++ Bitwise XOR Operator Array of sets in C++ Binary Operator Overloading in C++ Binary Search in C++ Implementing the sets without C++ STL containers Scope Resolution Operator in C++ Smart pointers in C++ Types of polymorphism in C++ Exception Handling in C++ vs Java Const Keyword in C++ Type Casting in C++ Static keyword in C++ vs Java Inheritance in C++ vs Java How to concatenate two strings in C++ Programs to Print Pyramid Patterns in C++ swap() function in C++ Structure of C++ Program Stringstream in C++ and its applications rand() and srand() in C / C++ C++ Ternary Operator C++ Scope of Variables While Loop Examples in C++ Star pattern in C++ using For Loops For Loop Examples in C++ Do-While Loop Examples in C++ Top 5 IDEs for C++ That You Should Try Once Assertions in C/C++ C++ Convert Int to String Continue in C++ While loop Diamond Pattern in C++ using For Loop How to Reverse a String in C++ using Do-While Loop How to Reverse a String in C++ using For Loop How to Reverse a String in C++ using While Loop Infinite loop in C++ Loops in C++ Returning Multiple Values from a Function using Tuple and Pair in C++ wcscpy(), wcslen(), wcscmp() Functions in C++

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.



ADVERTISEMENT
ADVERTISEMENT