VKS-LEARNING HUB

Home » Class-XI » C++ XI » Loops

Loops

Using a loop in C++ it is possible to repeat statement or block. C++ supports three (3) types of loops: while loop, for loop and dowhile loop. Generally any loop in C++ has three (3) components:

a)   Control Variable and its Initialisation: Generally a loop in C++ has a control variable. Control variable is generally an integer type or character type or floating point type. But we can have loop in C++ without a control variable. We will discuss such loops later. If a loop has a control variable then the control variable has to be initialized.

b)   Terminating Condition: Generally a loop should terminate after certain number of iterations. Terminating condition of the loop in C++ is a condition (logical expression) involving the Control Variable. Condition or logical expression plays a very important in the working of a loop in C++ since number of times loop is repeated depends on the condition.

c)   Updation of Control Variable: Every C++ loop repeats statement or block. Inside the block or statement of a loop, control variable is updated (value of the control variable is either incremented or decremented), so that the loop terminates after certain number of iterations.

While loop has two format 1. While   2  Do- While

while do-while

The while Loop – Repetition Control Structure, Iteration

Executes a block of statements as long as a specified condition is true.

The general form:

while(Loop Control Condition)

{

C++ Statements;

Updation of control variable before the close

//  Updation statement should be present anywhere between{  } other wise it      become infite loop

 }

  • The (condition) may be any C/C++ valid expression.
  • The statement(s) may be either a single or a compound (a block) C/C++ statement.
  • When program execution reaches a while statement, the following events occur:
  1. The (condition) is evaluated.
  2. If (condition) evaluates as false (that is zero), the while statement terminates and execution passes to the first statement following statement(s)that is the next_statement.
  3. If (condition) evaluates as true (that is non zero), the C/C++ statement(s) are executed.
  4. Then, the execution returns to step number 1.

// demonstrates a simple while statement

#include <stdio.h>

int main()

{

int  calculate;

// print the numbers 1 through 12, set the initial value…

calculate = 1;

// set the while condition…

while(calculate <= 12)

{

// display…

cout;<<calculate;

// increment by 1…repeats

calculate++;

}

cout<<‘\t’;

return 0;

}

Output

1    2   3    4    5   6    7    8    9   10    11   12

 

 

Repetition: The do-while Loop, Iteration

  • Executes a block of statements as long as a specified condition is true.
  • Test the condition at the end of the loop rather than at the beginning, as is done by the for loop and the while loop.
  • The do-while loop construct is:

do  

                 {

C++ Statements;

Updation of control variable before the close

/*  Updation statement should be present anywhere between{  }

other wise it  become infite loop*/

}while(Loop Control Condition);

  • (condition) may be any C/C++ valid expression.
  • statement(s) may be either a single or compound (a block) C/C++ statement.
  • When the program execution reaches the do-while statement, the following events occur:
  1. The statement(s) are executed.
  2. The condition is evaluated.  If it is true, execution returns to step number 1.  If it is false, the loop terminates and the next_statement is executed.
  • This means the statement in the do-while will be executed at least once.
  • The following is a flow chart for the do-while loop:

A program example:

// a program to illustrate a do-while loop

#include <iostream.h>

int main()

{

int   selection;

do

{

// true for 1, 2 and 3 ONLY, then repeat

// false for other numbers including 0, then stop…

// the do loop is repeated if the while expression is true.

cout<<“\n     Menu”<<“\n”;

cout<<“\n   0.    Exit”;

cout<<“\n   1.    Append”;

cout<<“\n   2.    Delete”;

cout<<“\n   3.    Modify”;

cout<<“\n\n      Enter selection: “;

cin>>selection;

}while((selection > 0) && (selection < 4));

return 0;

}

Note : That the loop body is always executed at least once. One important difference between the while loop and the do-while loop the relative ordering of the conditional test and loop body execution. In the while loop, the loop repetition test is performed before each execution the loop body; the loop body is not executed at all if the initial test fail. In the do-while loop, the loop termination test is Performed after each execution of the loop body. hence, the loop body is always executed least once.

Usage of while loop:

#include<iostream.h>

void main()

{

int k=1;

while (k<=8)

{

cout<<k<<endl;

k++;

}

}

Running of the program produces following output:

1

2

3

4

5

6

7

8

Explanation of output and working of the program:

Initial value of k=1

k<=8 cout<<k<<endl; k++
TRUE 1 2
TRUE 2 3
TRUE 3 4
TRUE 4 5
TRUE 5 6
TRUE 6 7
TRUE 7 8
TRUE 8 9
FALSE 9  

The while loop is an example of entry controlled loop, since first the Condition is tested and then the Block or the Statement is executed.

Use of while loop

#include<iostream.h>

void main()

{

int n;

cout<<“Input a positive integer? “;

cin>>n;

int k=2;

while (k<=n)

{

cout<<k<<endl;

k+=2;

}

}

Running of the program

Input a positive integer? 20

2

4

6

8

10

12

14

16

18

20

Explanation of output and working of the output

Inputted value of n is 20 and initial value of k=2.

k<=20 cout<<k<<endl; k+=2
TRUE 2 4
TRUE 4 6
TRUE 6 8
TRUE 8 10
TRUE 10 12
TRUE 12 14
TRUE 14 16
TRUE 16 18
TRUE 18 20
TRUE 20 22
FALSE    

Running of the program

Input a positive integer? 9

2

4

6

8

Explanation of output and working of the output

Inputted value of n is 9 and initial value of k=2.

k<=9 cout<<k<<endl; k+=2
TRUE 2 4
TRUE 4 6
TRUE 6 8
TRUE 8 10
FALSE    

Running of the program

Input a positive integer? -5

Explanation of output

Inputted value of n is -5 and initial value of k=2. Therefore condition is FALSE and the loop is not executed at all and hence no output.

 

#include<iostream.h>

void main()

{

int n, sum=0;

cout<<“Input positive integer? “; cin>>n;

int x=1;                //Initialisation of control variable

while (x<=n)            //Terminating Condition

{

sum+=x*x;

x++;                  //Update of control variable

}

cout<<“Sum=”<<sum<<endl;

}

Usage of dowhile

#include<iostream.h>

void main()

{

int n, k=1, fact=1;

cout<<“Input positive integer? “; cin>>n;

do

{

fact*=k;

k++;

}

while (k<=n);

cout<<“Factorial=”<<fact<<endl;

}

Running of the program

Input positive integer? 10

Factorial=3628800

Explanation of output and working of the output

Inputted value in n is 10 and initial value of k=1

k fact*=k k++ k<=10
1 1 2 TRUE
2 2 3 TRUE
3 6 4 TRUE
4 24 5 TRUE
5 120 6 TRUE
6 720 7 TRUE
7 5040 8 TRUE
8 40320 9 TRUE
9 362880 10 TRUE
10 3628800 11 FALSE

//Program to find HCF and LCM of two integers

#include<iostream.h>

void main()

{

int a, b;

cout<<“Input 1st integer? “;cin>>a;

cout<<“Input 2nd integer? “;cin>>b;

int prod=a*b, r;

do

{

r=a%b;

a=b;

b=r;

}

while(r>0);

cout<<“HCF=”<<a<<endl;

cout<<“LCM=”<<(prod/a)<<endl;

}

//Count digits, sum of digits, product of digits

#include<iostream.h>

void main()

{

int n, digit=0, sum=0, prod=1;

cout<<“Input an integer? “;cin>>n;

while (n!=0)

{

int r=n%10;

digit++;

sum+=r;

prod*=r;

n/=10;

}

cout<<“Number of digits=”<<digit<<endl;

cout<<“Sum of digits=”<<sum<<endl;

cout<<“Product of digits=”<<prod<<endl;

}

//Program to reverse an inputted integer

#include<iostream.h>

void main()

{

int n, m=0;

cout<<“Input an integer? “;cin>>n;

while (n!=0)

{

m=10*m+n%10;

n/=10;

}

cout<<“Reversed integer=”<<m<<endl;

}

//Check for Prime Number

#include<iostream.h>

void main()

{

int n;

cout<<“Input an integer? “;cin>>n;

int k=2, prime=1;

while (k<n && prime==1)

{

if (n%k==0)

prime=0;

k++;

}

if (prime==1)

cout<<n<<” Prime Number”<<endl;

else

cout<<n<<” Composite Number”<<endl;

}

//Check for Armstrong Number

#include<iostream.h>

void main()

{

int n;

cout<<“Input an integer? “;cin>>n;

int t=n, s=0;

while (n!=0)

{

int digit=n%10;

s+=digit*digit*digit;

n/=10;

}

if (s==t)

cout<<t<<” Armstrong Number”<<endl;

else

cout<<t<<” Not Armstrong Number”<<endl;

}

//Check for Palindromic Integer

#include<iostream.h>

void main()

{

int n;

cout<<“Input an integer? “;cin>>n;

int t=n, m=0;

while (n!=0)

{

m=10*m+n%10;

n/=10;

}

if (t==m)

cout<<t<<” Palindromic integer”<<endl;

else

cout<<t<<” Not Palindromic integer”<<endl;

}


include<iostream.h>  //Same program using while loop

void main()

{

int k=1;

while (k<=4)                 //Start of Outer loop

{

int j=1;

while (j<=k)               //Start of Inner loop

{

cout<<‘*’;

j++;

}                              //End of Inner loop

cout<<endl;

k++;

}                                     //End of Outer loop

}

#include<iostream.h>  //Same program using dowhile loop

void main()

{

int k=1;

do                                                       //Start of Outer loop

{

int j=1;

do                             //Start of Inner loop

{

cout<<‘*’;

j++;

}

while (j<=k);         //End of Inner loop

cout<<endl;

k++;

}

while (k<=4);          //End of Outer loop

}

For loop

It is a count controlled loop in the sense that the program knows in advance how many times the loop is to be executed.

syntax of for loop

for (initialization; decision; increment/decrement)

{
statement(s);
}

The flow diagram indicates that in for loop three operations take place:

for_loop

  • Initialization of loop control variable
  • Testing of loop control variable
  • Update the loop control variable either by incrementing or decrementing.

Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test whether the condition is true or false. If the condition is true, the program executes the body of the loop and then the value of loop control variable is updated. Again it checks the condition and so on. If the condition is false, it gets out of the loop.

// Sum of square of natural number

#include<iostream.h>

void main()

{

int n, sum=0;

cout<<“Input positive integer? “;

cin>>n;

for (int k=1; k<=n; k++)          //all together

sum+=k*k;

cout<<“Sum=”<<sum<<endl;

}

// Fibonacci Series

#include<iostream.h>

#include<conio.h>

int main()

{

int f=0,s=1,t,n;

cout<<“Enter Number of terms of Series : “;

cin>>n;

cout<<f<<” “<<s<<” “;

for(int i=3;i<=n;i++)

{

t=f+s;

cout<<t<<” “;

f=s;

s=t;

}

getch();

return 0;

}

Output

0 1 1 2 3 5 8……..

//Write a program to calculate the sum of following series where n is input by user.
1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n

#include<iostream.h>
#include<conio.h>

int main()
{
            int i,n;
            float sum=0;

            cout<<"Enter the value of n ";
            cin>>n;

            for(i=1;i<=n;i++)
                        sum += 1.0/i;

            cout<<"Sum : "<<sum;

            getch();
            return 0;
}

//

#include <iostream.h>

 

void main()

{

    int i, j;

   cout<<“Enter an integer: “

    cin>>i;

    cout<<“Table”;

    for(j = 0; j <= 12; j = j + 1)

    {

     cout<< j<<” *”<< i<<“=”<< j*i <<endl;

    }

  }

// the pyramid of $ using nested for loops

#include <iostream>

// replace any occurrences of VIEW with character $

#define VIEW ‘$’

using namespace std;

int main(void)

{

int i, j;

cout<<“Let have a money pyramid!\n”<<endl;

// first for loop, set the rows…

for(i=1; i<=20; i++)

{

// second for loop, set the space…

for(j=1; j<=20-i; j++)

cout<<” “;

// third for loop, print the $ characters…

for(j=1; j<=2*i-1; j++)

// print character

cout<<VIEW;

// go to new line

cout<<“\n”;

}

return 0;

}

Output example:

Let have a money pyramid!
                   $
                  $$$
                 $$$$$
                $$$$$$$
               $$$$$$$$$
              $$$$$$$$$$$
             $$$$$$$$$$$$$
            $$$$$$$$$$$$$$$
           $$$$$$$$$$$$$$$$$
          $$$$$$$$$$$$$$$$$$$
         $$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$
       $$$$$$$$$$$$$$$$$$$$$$$$$
      $$$$$$$$$$$$$$$$$$$$$$$$$$$
     $$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
   $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
  $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
Press any key to continue . . .

Previous

Solved Examples

Unsolved Questions for Practice

Next

 

Leave a comment