Posted By:
2 Jul, 2013 6:14 am PDT

Implementation of while loop in C++

How to write a while loop?
Attachment:None


 Loops are generally used to repeat a block iteratively for a fixed number of times.

Syntax of while is:

        while (condition)

       {

                 statement;

       }

 

For a loop the three main expression are: initialization, condition and increment/decrement operation.

In while loop, initialization is done outside the loop and the increment/decrement operation is done inside the loop. Let us understand more clearly from the below example:

// To find the sum of ‘n’ numbers

#include<iostream.h>

void main()

{

int n,sum=0;

cout<<”\n Enter n:”;

cin>>n;

int i=0;       // Initialization

while(i<n)   // Condition

{

sum=sum + i;   // Statement

i++;               //Increment operation

}

cout<<sum;

}

The while loop is repeated till the condition becomes False.

 

Was it useful?  




Please login to reply to this problem.