The while loop is particularly useful when the number of iterations is not known or cannot be determined in advance. The general syntax of the while loop is as follows:
while (expr) statement ;
where expr is the loop control or test expression that may be any valid C expression such as arithmetic, relational or logical and the statement is the body of the loop that is to be executed repeatedly. Note that the body of a while loop will usually be a block statement as shown below.
while(expr){ statement; statement ; ..... }
The while loop is an entry-controlled or top-tested loop as the loop control or test appears in the beginning of the loop. The flowchart of the while loop is given in fig.
The execution of the while loop proceeds as follows: Initially, test expression expr is evaluated. If it evaluates as true (i. e., non-zero), the body of the loop is executed and the control is transferred to the beginning of the loop where expression expr is evaluated again. However, if the test expression evaluates as false (i. e., zero), the control leaves the loop. Thus, the body of the loop is executed while (as long as) test expression expr evaluates as true (non-zero). Note that if the expression expr evaluates as false (i.e., zero) when the loop is entered, the body of the loop is not executed at all.
Illustrates while loop for determining squares and cubes of numbers.
#include<stdio.h> void main() { int n , Square, Cube , k = 1 ; clrscr(); printf("Enter a small integer:"); scanf("%d", &n); printf("Number\t Square\t Cube\n"); while (k <=n) { Square = k*k; Cube = k*k*k; printf("%d \t %d \t %d\n", k, Square, Cube); k++; } }
A while loop is illustrated in Program in which squares and cubes of numbers from 1 to n are calculated and displayed. The value of n is entered by the user of the program. Four integer variables are declared:
(i) the variable n the value of which is entered by the user, (ii and iii) square and cube are other two variables whose values are calculated in the program and (iv) a controlling integer k, which counts and controls the iterations. As long as k is less than the value of n entered by the user, the expression will evaluate true. The statements following the while expression will be executed, i.e., the square and cube of the number will be calculated and displayed on the monitor.
After each iteration, the value of k is incremented by 1 and the process is repeated. This goes on till k becomes equal ton. In Program, the number entered by the user is 4. Therefore, squares and cubes of numbers 1, 2, 3, and 4 are calculated and displayed. The statements following the while expression are enclosed between { } and hence all these become part of the while loop. So, for every value of k all these statements are repeated.