Tuesday, May 12, 2009

While statements

The While Loop
It is a repetitive control structure, and executes the statements with the body until the condition becomes false.

Syntax:

while(condition)
{

. . . . . .

body of the loop; // statements

. . . . . .

}

Example:

while(n>0)
{

i=n+i;
n++

}
cout<< i;

The statements within the while loop will be executed till the condition is true, when the condition becomes false the control passes to the first statement that follow the body of the while loop.


Example Program to print sum of digits


void main()
{
int n;
int n1, sum=0;
cout<<"Enter the Number of N: ";
cin>> n;
while(n>0)
{

n1=n%10;
sum=sum+n1;
n=n/10;

}

cout<< sum;
getch();

}

Output will be

Enter the Number of N: 258
15

No comments:

Post a Comment