L 11 While Loops
L 11 While Loops
Topics
The while Loop
Program Versatility
Sentinel Values and Priming Reads
Checking User Input Using a while Loop
Reading
Section 3.7
Review: Repetition Structure
A repetition structure allows the programmer to specify
that an action is to be repeated while some condition
remains true.
There are three repetition structures in C, the while loop,
the for loop, and the do-while loop.
The while Repetition Structure
while ( condition )
{
statement(s)
}
/* Initializations */
total = 0 ;
counter = 1 ;
/* Get grades from user */
/* Compute grade total and number of grades */
printf(“Enter a grade: “) ;
scanf(“%d”, &grade) ;
while (grade != -1) {
total = total + grade ;
counter = counter + 1 ;
printf(“Enter another grade: “) ;
scanf(“%d”, &grade) ;
}
return 0 ;
}
Using a while Loop to Check User Input
#include <stdio.h>
int main ( )
{
int number ;
printf (“Enter a positive integer : “) ;
scanf (“%d”, &number) ;
while ( number <= 0 )
{
printf (“\nThat’s incorrect. Try again.\n”) ;
printf (“Enter a positive integer: “) ;
scanf (“%d”, &number) ;
}
printf (“You entered: %d\n”, number) ;
return 0 ;
}