View Course Path

While loop in C – Full explanation with examples and tutorials

A while loop in C continuously executes the contents of its loop as long as a condition is true. The syntax for the while loop is as follows

while(condition)
{
statements;
}

These statements can be of any nature. The important thing is that the loop executes only if the condition statement beside while gives a boolean logic output of 1. So if you remove the condition statement and place a logic 1 bit there, the while loop becomes an infinite loop.

while loop in C flow chart

Write a program using the while loop in C to print the first 10 natural numbers

//print the first 10 natural numbers
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr;
int i=0;
while(i<=9)
{
printf("%d\n",++i);
}
getch();
}

Write a program in C to check if a number is same after reversing it

//take number from the user, reverse it and check whether it is the same as the original number
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,temp=0,b,c;
printf("Enter a number\n");
scanf("%d",&i);
c=i;
while(i>0)
{
b=i%10;
i=i/10;
temp=(temp*10)+b;
}
if(temp==c)
{
printf("This number is the same when reversed");
}
else
{
printf("This number is not the same when reversed");
}
getch();
}

WAP (Write a program) in C to take a number from a user and check if the product and sum of the number’s digits are same

//take number from user and find if sum and product of the digits is the same
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,b,mul=1,sum=0;
printf("Enter number\n");
scanf("%d",&i);
while(i>0)
{
b=i%10;
i=i/10;
mul=mul*b;
sum=sum+b;
}
if(mul==sum)
{
printf("The sum and product of the digits of this number are equal");
}
else
{
printf("The sum and product of the digits of this number are not equal");
}
getch();
}

Write a program in C to take print the series of numbers up to 10,000 whose product and sum of the digits are same

//print series of the numbers upto 10000 whose sum and product of the digits is the same
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,b,mul=1,sum=0,temp;
for(i=21;i<=10000;i++)
{
temp=i;
while(i>0)
{
b=i%10;
i=i/10;
mul=mul*b;
sum=sum+b;
}
if(mul==sum)
{
printf("%d\n",temp);
}
i=temp;
mul=1;
sum=0;
}
getch();
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.