While Loop In C Language With Examples
While Loop :
The while statement is typically used in situations where it is not known in advance how many iterations are required.
Syntax
while ( condition )
{
statement body ;
}
For Example : Program to sum all integers from 100 down to 1.
CODE/PROGRAM/EXAMPLE
#include <stdio.h>
void main()
{
int sum = 0, i = 100 ;
while ( i )
sum += i-- ;// note the use of postfix decrement operator!
printf( "Sum is %d \n", sum ) ;
}
where it should be recalled that any non-zero value is deemed TRUE in the condition section of the statement.
A for loop is of course the more natural choice where the number of loop iterations is known beforehand whereas a while loop caters for unexpected situations more easily.
For example if we want to continue reading input from the keyboard until the letter 'Q' is hit we might do the following.
Syntax
char ch = "\0" ; /* initialise variable to ensure it is not “Q” */
while ( ch != "Q" )
ch = getche() ;
or more succinctly
while ( ( ch = getche() ) != "Q" ) ;
It is of course also possible to have nested while loops.
For Example : Program to guess a letter.
CODE/PROGRAM/EXAMPLE
#include <stdio.h>
void main()
{
char ch, letter = “c” ; // secret letter is ‘c’
char finish = ‘\0’ ;
while ( finish != ‘y’ || finish != ‘Y’ )
{
puts( "Guess my letter -- only 1 of 26 !" );
while( (ch=getchar() ) != letter )// note use of parentheses
{
printf( "%c is wrong -- try again\n", ch );
_flushall() ; // purges I/O buffer
}
printf ( "OK you got it \n Let’s start again.\n" );
letter += 3 ;// Change letter adding 3 onto ASCII value of letter
// e.g. ‘c’ + 3 = ‘f’
printf( “\n\nDo you want to continue (Y/N) ? “);
finish = getchar() ;
_flushall() ;
}
}