while Statement in C

The while-loop is an entry-controlled loop in which first the condition is checked, and if it is True then the statements are executed. However, if the condition is False, the control is transferred to the statement immediately after the body of loop. The condition can be any constant, variable or expression that evaluates to True or False.

However, the general syntax of while-loop requires a counter variable to be initialized before while statement. Then, within the condition, this counter variable needs to be checked against some value. If the condition evaluates to True, the statements within the body of loop will be executed. After this, the control is transferred back to condition. If this time the condition is again True, then the body of loop will be executed same way and control will be transferred back to the condition. However, if the condition is False, then the control will be transferred to the statement immediately following the loop body. The general flow of an entry-controlled loop is shown in figure 1.

Screenshot from 2020-07-16 16-32-00

Figure 1: General flow of an entry-controlled loop

This means the while construct has a condition statement that decides whether the statements of loop body will be executed or not. Also, it has a counter variable to keep the count of number of times the statements within body of loop are executed. However, this counter variable needs to be modified during iteration within the body of loop. The counter modification statement should be the last statement of the body of the loop. The general syntax of while looping statement is as follows;

counter-initialisation;
while ( condition )
{
statements;
counter-modification;
}

It should be noted that if the initialization of counter variable is skipped, then there will be no syntax error but a logical error. This is because of the fact that un-initialized variables contain bogus value which will be checked against some value in condition. Depending upon bogus value, the condition will evaluate to True or False.

It is worth mentioning here that if the statement to modify counter variable is skipped, there will be no syntax error. However, this may result into an infinite loop. An infinite loop is a loop in which statements are executed infinite number of times. This is true for all types of loops. Program 1 shows how to display a multiplication table of any number entered by a user using while loop. It is followed by the output of the program.

#include <stdio.h>
void main()
{
int number, count, mul;
printf(“Please enter the number? ”);
scanf(“%d”, &number);
count = 1;
while ( count <= 10 )
{
mul = number * count;
printf(“\n%d x %d = %d”,
number, count, mul);
count ++;
}
}

Program 1: Program to display multiplication table of a number using while loop.

Screenshot from 2020-07-16 16-34-16