Pages

Monday, October 19, 2009

The while loop

While is a conditional loop which is used when we want to do some repetitive task till a certain conditions evaluates to true. It is useful in conditions when do not know the exact number of times the task is to be repeated. For example : when we say that we are going to study till 5’o clock it is an example of for loop since 5 is a fixed value but if the sentence is changed to “till dark” instead of “till 5’o clock” this become while loop since we don’t know when it will get dark. Check out its syntax :

while(condition)

{

loop body

}

Lets understand this with a basic example

void main()

{

int a=1;

while(a<=10)

{

printf(“\n%d”,a);

a++;

}

}

The condition part has “a<=10” written which states that the loop will run till the value of a is less than 11. As soon as the condition becomes false the loop terminates. Therefore the values that will be printed as 1,2,3…10. This is not a perfect example of while since the value 10 is fixed but it is a good example to start with. Lets create some more sensible while examples.

Example 2 : program to accept numbers from the user till he enters a negative number

void main()

{

int num;

while(num>=0)

{

printf(“\nenter a number : “);

scanf(“%d”,&num);

}

}

The above program will prompt the user to enter any values. The user will continue to enter values as long as they are positive. The moment he enters a negative value the condition will become false and the loop will terminate.

Example 3: running the program as long as the user wishes

void main()

{

int num,square;

char ch=’y’;

while(ch==’y’)

{

printf(“\nenter a number : “);

scanf(“%d”,&num);

square=num*num;

printf(“\nsquare of the number is %d”,square);

fflush(stdin);

printf(“\ndo you want to continue : “);

scanf(“%c”,&ch);

}

Example 4 : Program to ask password from the user until he enters the correct password

void main()

{

int pass,cnt=0;

while(pass!=786)//assuming that the correct password is 786

{

printf(“\nguess the password : “);

scanf(“%d”,&pass);

cnt++;

}

printf(“\ncorrect. you took %d chances”,cnt);

}

0 comments:

Post a Comment