C Programming Tutorial
Computer Tutorial

The While Loop



The While Loop

The while loop is used in programming to execute something or some lines of code for a fixed number of times.
The loop iterates while the condition is true. When the condition becomes false, program control passes to the line of code immediately following the loop.

The general form of while is :


initialise loop counter ;
while ( test condition  )
{
Statements to be execute ;
.
.
Increment/decrement loop counter ;
}
where,
» Initilise loop counter value will initialize the beginning of the loop.
» The test condition may be any expression and true is any nonzero value.
» The statement is either an empty statement, a single statement, or a block of statements which will be executed if the condition is true.
» The Increment/decrement loop counter will increase or decrease the iteration value as per requirement.

Diagram to show the functionality of The while loop

Flow diagram to show the functionality of while Loop

Some Inportant points about while Loop :

1. The statements within the while loop would keep on getting executed till the condition being tested remains true.
2. The condition being tested may use relational or logical operators.
3. The statement within the loop may be a single line or a blank of statement. In the first case the parentheses are optional.
4. It is not necessary that a loop counter must only be an int. It can even be a float.
5. As a rule the while must test a condition that will eventually become false, otherwise the loop would be executed forever.

C Program to show the use of while Loop :

\* C Program to show the use of while Loop *\
# include < stdio.h >
int   main( )
{

int   i  ;
i = 0 ;/* initialise loop counter */
while ( i < = 10  )/* Check condition */
{

printf("\n %d ",   i) ;
i = i + 1 ;/* Increment of loop counter */

}
return ( 0 );

}