While Loop
While Loop
while (condition)
{
statements;
}
The condition (test-expression) is evaluated at the entry of the loop. If the condition returns true, the
statements block will be executed. Otherwise, the loop is terminated.
The control will be returned back to verifying the loop condition state after each iteration of
statements execution.
Eg. The following example reads the product quantity and price values, then calculates the bill
value of the product. It reads indefinite number of products data. The loop continuity will be
decided at run time based on user choice.
void main()
{
float q, p, bill, netbill=0.0;
char choice='y';
while (choice == 'y')
{
printf("\nEnter quantity :" );
scanf("%f", &q);
printf("Enter price : ");
scanf("%f", &p);
bill = q*p;
printf("Current product bill %.2f", bill);
netbill += bill;
printf("\nAny more products (y/n) ? ");
choice = getche();
}
printf("\n\nNet bill : %.2f", netbill);
}
void main()
{
int num, digit, sum;
#include <stdio.h>
void main()
{
int num, digit, rev;
rev = 0;
while (num > 0)
{
digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
printf("Reverse of number is :%d\n", rev);
}
#include <stdio.h>
void main()
{
int n, i, sum;
printf("Enter number : ");
scanf("%d", &n);
sum = 0;
for (i=1; i<n; i++)
if ( n % i == 0 )
sum += i;
if (sum == n )
printf("%d is perfect \n", n);
else
printf("%d is not perfect \n", n);
}
#include <stdio.h>
void main()
{
int num, temp, digit, i;
long int f, sum;
temp = num;
sum=0;
while (num > 0)
{
digit = num % 10;
f=1;
for(i=1; i<=digit; i++)
{
f *= i;
}
sum += f;
num /= 10;
}
if (temp == sum)
printf("%d is a strong number", temp);
else
printf("%d is not a strong number", temp);
void main()
{
int x, num, temp, digit, i;
long int f, sum;
f = 1;
for(i=1; i<=digit; i++)
{
f *= i;
}
sum += f;
num /= 10;
}
if (temp == sum)
printf("%5d", temp);
num = temp;
}
}