Tuesday 12 February 2013

The while Loop in C Programming Language


The function below shows the use of the while loop in accepting an input as 'y' or 'n' only. Any other input is rejected by the function until a valid input is provided.

#include <stdio.h>
main()
{
char inp, valid = 'n';
while(valid == 'n')
{
valid ='';
puts("Enter y or n");
inp = getchar();
fflush(stdin);
if(inp=='y')
puts("Valid input");
else if(inp=='n')
puts("Valid input");
else
{
valid='n';
puts("Invalid Data");
}
}
}

In a while block of statements, the condition is evaluated first and, if it is true, the loop body is executed. After execution of the loop body, the condition in the while statement is evaluated again. This repeats until the condition becomes false.

0 comments:

Post a Comment

Powered by Blogger.