|
while Loop
The while construct repeats the body of the loop as long as
the loop condition holds.
The following program illustrates the usage of the while
construct:
//Program 2.2
//This program calculates the square of integer numbers
#include<iostream.h>
void main()
{
char cReply;
int iNum, iSquare;
cout<<"Do you want to find the square of a number (y/n)?";
cin>>cReply;
while(cReply == 'y')
{
cout<<"Enter a number:";
cin>>iNum;
iSqure = iNum * iNum;
cout<<"The square of "<<iNum<<"is"<<iSquare<<endl;
cout<<"Do you want to find the square of another number
(y/n)?";
cin>>cReply;
}
}
In Program 2.2 the body of the while loop is executed as
long as cReply is 'y'.
The sample output of Program 2.2 is:
Do you want to find the square of a number (y/n)? y
Enter a number: 9
The square of 9 is 81
Do you want to find the squre of another number (y/n)? n |