Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Topics
• The while Loop
• Program Versatility
• Sentinel Values and Priming Reads
• Checking User Input Using a while Loop
Reading
• Sections 5.1 – 5.3, 5.5-5.7
while ( condition )
{
statement(s)
}
<total> = 0
<grade_counter> = 1
/* Initializations */
total = 0 ;
counter = 1 ;
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 ;
}
CMSC 104, Version 8/06 L12WhileLoops.ppt 2
Using A while Loop To Check User Input
#include <stdio.h>
int main ( void )
{
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 ;
}
CMSC 104, Version 8/06 L12WhileLoops.ppt 2
Wrong Way To Check User Input
#include <stdio.h>
int main ( void )
{
int number ;
printf (“Enter a positive integer : “) ;
scanf (“%d”, &number) ;
if ( 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 ;
}
CMSC 104, Version 8/06 L12WhileLoops.ppt 2
Why Is It Wrong?
#define DAYS_IN_WEEK 7
int nr_days = 1;
float total = 0;
float sales;
#include <stdio.h>
int main( void )
{
int x = 13;
while ( x < 10 )
{
printf("x = %d\n" );
x = x + 1;
}
return 0;
}
CMSC 104, Version 8/06 L12WhileLoops.ppt 2
What Is The Output? (cont’d)
• Nothing!
• The reason is the condition was never true,
so the body of the loop is never executed.
#include <stdio.h>
int main( void )
{
int x = 1;
while ( x < 10 )
{
printf("x = %d\n" );
}
return 0;
}
CMSC 104, Version 8/06 L12WhileLoops.ppt 2
Another Infinite Loop
#include <stdio.h>
int main( void )
{
int x = 1;
while ( x != 10 )
{
printf("x = %d\n" );
x = x + 2;
}
return 0;
}
CMSC 104, Version 8/06 L12WhileLoops.ppt 3