while loop

http://install4install.com

While loop keeps on executing the given statements as long as the condition is true.When the condition  turns out to be false then set of statements in the block never gets executed and the control goes to first line after the while block.

Syntax

while(condition)

{

set_of_statements;

iteration statement;

}

If the condition is true,then set of statements are executed.The value of i is iterated and then control again returns to while condition.If condition is true again then same process is followed otherwise control exits the loop.

 

Example 1

Say we need to print  numbers from 0 to 100.while loop can also be used instead of for loop to fulfill this task.

Program 1

#include <stdio.h>

int main() 
{
int i=0;
while(i<=100)
{
	printf("%d \t",i);
	i++;
}
	return 0;
}

 

Run

 

 

Example 2

Say we want to print a table of a user entered number.

Program 2

#include <stdio.h>

int main()
{
int n,i=1;
int res;
//printf("Enter the number");
scanf("%d",&n);
while(i<=10)
{
	res = n * i;
	printf("%d * %d = %d\n",n,i,res);
	i++;
}
	return 0;
}

 

Run

 

Example 3

Say we want to print even numbers and odd numbers from 0-100  separately .

Program 3

#include <stdio.h>

int main() 
{
int i=0;
int j=1;
printf("The even numbers are:\n");
while(i<=100)
{
	printf("%d\t",i);
	i=i+2;
}
printf("\nThe odd numbers are :\n");
while(j<100)
{
	printf("%d\t",j);
	j=j+2;
}
	return 0;
}

 

 

Run

 

Example 4

Say we want to print series like  15625,3125,625,125,25,5.

Program 4

#include <stdio.h>

int main() 
{
int i=15625;
while(i>=5)
{
	printf("%d\t",i);
	i=i/5;
}
	return 0;
}

 

Run

 

 

Illustration 

The working of program 4 is explained in Fig 1.

Screen Shot 2014-07-08 at 11.09.51 AM

Fig 1 : Working of Program 4



Short URL: http://tinyit.cc/8489e9
Author: Cusp2207 on July 8, 2014
Category: Computer Science
Tags:

Leave a Reply

Last articles