The While Loop in C Language

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)
{
body_of_the_loop;
}

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.

 

The While Loop in C
While Loop in C

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 */

#include <stdio.h>

#include <math.h>

#include <stdio.h>

main( )

{

int x;

long int fact = 1;

printf(“Enter any number to find factorial:\n”); /*read the number*/

scanf(“%d”,&x);

while (x > 0)

{

fact = fact * x; /* factorial calculation*/

x=x-1;

}

printf(“Factorial is %ld”,fact);

}

OUTPUT

Enter any number to find factorial:
4
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.

 

One thought on “The While Loop in C Language

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: