The while statement is typically used in situations where it is not known in advance how many iterations are required.
while ( condition )
statement body ;
For Example : Program to sum all integers from 100 down to 1.
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.
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.
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() ;
All Rights Reserved. © 2020 BookOfNetwork
Design By : Elite Webz