The While Loop in C – When in a program a single statement or a certain group of statements are to be executed repeatedly depending upon certain test condition, then while statement is used.
The While Loop syntax in C Language
while (test condition)
Here, the test condition is an expression that controls how long the loop keeps running. The body of the loop is a statement or group of statements enclosed in braces and are repeatedly executed till the value of test condition evaluates to true.
As soon as the condition evaluates to false, the control jumps to the first statement following the while statement. If condition initially itself is false, the body of the loop will never be executed. While loop is sometimes called as entry-control loop, as it controls the execution of the body of the loop depending upon the value of the test condition.
Program to illustrate while loop in C
Write a program to calculate the factorial of a given input natural number.
/* Program to calculate factorial of given number */
long int fact = 1;
printf(“Enter any number to find factorial:\n”); /*read the number*/
while (x > 0)
fact = fact * x; /* factorial calculation*/
printf(“Factorial is %ld”,fact);
Enter any number to find factorial:
Factorial is 24
Here, the condition in while loop is evaluated and body of the loop is repeated until the condition evaluates to false i.e. when x becomes zero. Then the control is jumped to the first statement following while loop and print the value of factorial.