While Loops - University of Maryland, Baltimore County

While Loops - University of Maryland, Baltimore County

The while Looping Structure 2008/10/20: Lecture 11 CMSC 104, Section 0101 John Y. Park 1 The while Looping Structure Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Reading

Section 3.7 2 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. 3 The while Repetition Structure while ( condition ) { statement(s) } The braces are not required if the loop body

contains only a single statement. However, they are a good idea and are required by the 104 C Coding Standards. 4 Example while ( children > 0 ) { children = children - 1 ; cookies = cookies * 2 ; } 5 Good Programming Practice Always place braces around the body of a

while loop. Advantages: Easier to read Will not forget to add the braces if you go back and add a second statement to the loop body Less likely to make a semantic error Indent the body of a while loop 3 to 4 spaces -- be consistent! 6 Example

while ( children < 0 ) scanf("%d", &i); printf("Finally, got something positive\n"); 7 Example while ( children < 0 ) printf("Enter a positive number: "); scanf("%d", &i); printf("Finally, got something positive\n"); 8 Another while Loop Example Problem:

Write a program that calculates the average exam grade for a class of 10 students. What are the program inputs? the exam grades What are the program outputs? the average exam grade 9 The Pseudocode

= 0 = 1 While ( <= 10) Display Enter a grade: Read = + = + 1 End_while = / 10 Display Class average is: , 10

The C Code 1. 2. 3. 4. 5. #include int main ( ) { int counter, grade, total, average ; total = 0 ; counter = 1 ; while ( counter <= 10 ) { printf (Enter a grade : ) ; scanf (%d, &grade) ; 6. 7. 8. 9. 10. 11.

} 12. 13. 14. 15. } total = total + grade ; counter = counter + 1 ; average = total / 10 ; printf (Class average is: %d\n, average) ; return 0 ; 11 Versatile?

How versatile is this program? It only works with class sizes of 10. We would like it to work with any class size. A better way : Ask the user how many students are in the class. Use that number in the condition of the while loop and when computing the average. 12 New Pseudocode = 0 = 1 Display Enter the number of students: Read While ( <= 10) Display Enter a grade: Read = +

= + 1 End_while = / 10 Display Class average is: , 13 New Pseudocode = 0 = 1 Display Enter the number of students: Read While ( <= 10) Display Enter a grade: Read = + = + 1 End_while = / 10 Display Class average is: , 14 New Pseudocode

= 0 = 1 Display Enter the number of students: Read While ( <= ) Display Enter a grade: Read = + = + 1 End_while = / Display Class average is: , 15 New C Code 1. 2. 3. #include int main ( ) { int numStudents, counter, grade, total, average ;

total = 0 ; counter = 1 ; 4. 5. printf (Enter the number of students: ) ; scanf (%d, &numStudents) ; while ( counter <= numStudents) { printf (Enter a grade : ) ; scanf (%d, &grade) ; 6. 7. 8. 9. 10. total = total + grade ; counter = counter + 1 ; 11.

12. 13. } 14. average = total / numStudents ; printf (Class average is: %d\n, average) ; return 0 ; 15. 16. 17. } 16 Why Bother to Make It Easier? Why

do we write programs? So the user can perform some task The more versatile the program, the more difficult it is to write. BUT it is more useable. The more complex the task, the more difficult it is to write. But that is often what a user needs. Always consider the user first. 17 Using a Sentinel Value We could let the user keep entering grades and when hes done enter some special value that signals us that hes done. This special signal value is called a sentinel

value. We have to make sure that the value we choose as the sentinel isnt a legal value. For example, we cant use 0 as the sentinel in our example as it is a legal value for an exam score. 18 The Priming Read When we use a sentinel value to control a while loop, we have to get the first value from the user before we encounter the loop so that it will be tested and the loop can be entered. This is known as a priming read. We have to give significant thought to the initialization of variables, the sentinel value, and getting into the loop. 19 New Pseudocode

= 0 = 1 Display Enter a grade: Read While ( != -1 ) = + = + 1 Display Enter another grade: Read End_while = / Display Class average is: , 20 New C Code 1. 2. 3. #include int main ( ) { int counter, grade, total, average ;

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) ; } 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

average = total / counter ; printf (Class average is: %d\n, average) ; return 0 ; 14. 15. 16. 17. } 21 Final Clean C Code 1. #include 2. 3. 4. 5.

6. 7. int main ( ) { int counter ; int grade ; int total; int average ; /* counts number of grades entered */ /* individual grade */ /* total of all grades */ /* average grade */ 8. 9. 10. 11.

/* Initializations */ total = 0 ; counter = 1 ; 12. 13. 14. 15. /* Priming read to get initial grade from user printf(Enter a grade: ) ; scanf(%d, &grade) ; */ 22 Final Clean C Code (cont) /* Get grades until user enters -1. Compute grade total and grade count. */ while (grade != -1) { total = total + grade ;

counter = counter + 1 ; printf(Enter another grade: ) ; scanf(%d, &grade) ; } 16. 17. 18. 19. 20. 21. 22. 23. 24. /* Compute and display the average grade */ average = total / counter ; printf (Class average is: %d\n, average) ; 25. 26. 27.

28. return 0 ; 29. 30. } 23 Using a while Loop to Check User Input 1. 2. 3. 4. 5. #include int main ( ) { int number ; printf (Enter a positive integer : ) ;

scanf (%d, &number) ; while ( number <= 0 ) { printf (\nThats incorrect. Try again.\n) ; printf (Enter a positive integer: ) ; scanf (%d, &number) ; } printf (You entered: %d\n, number) ; return 0 ; 6. 7. 8. 9. 10. 11. 12. 13. } 24

Recently Viewed Presentations

  • Work Activities December 2010 1 Objectives  We will

    Work Activities December 2010 1 Objectives We will

    Secondary education for a person who does not have a high school diploma or General Equivalency Diploma (GED) This is a core plus activity . If the parent does not have a high school diploma or GED and the parent...
  • Linear Regression 1 - UCI Social Sciences

    Linear Regression 1 - UCI Social Sciences

    Use a non-linear regression model for discrete outcomes: Logit, Probit, etc. Dependent variable is a dummy for patient mortality Look for relationship between dosage and mortality Benefit: Easy. An analog of regression Limitation: Doesn't take timing into account All patients...
  • The Gilded Age - Northland Preparatory Academy

    The Gilded Age - Northland Preparatory Academy

    Era of Change The Gilded Age gets its name from a book by Mark Twain, criticizing political leaders of the day Formative days of the US- in both politics and business Massive agricultural expansion into the west= influx of goods...
  • MEET THE BOARD - Chino Valley Unified School District

    MEET THE BOARD - Chino Valley Unified School District

    IT'S EASY! INFORMATION IN YOUR ... AR program, Scholastic News, All Pro-Dad, Field Trips, Red Ribbon Week, Family Fun Night, Family Math Night, Bookfair, STEAM funds per grade level, Student Grants, Classroom Grants, Office Supplies, Health Office Supplies, Read Across...
  • Constitution Day 2017

    Constitution Day 2017

    Highlight why the public should care about who the judges are in their communities. Provide examples. Remind the audience of the following points: Courts protect your rights. Courts ensure the rule of law is upheld and that people are treated...
  • Bob Tabor | http://www.LearnVisualStudio.NET

    Bob Tabor | http://www.LearnVisualStudio.NET

    A path to learn the essentials of Azure … Microsoft Azure Fundamentals. Microsoft Azure Fundamentals: Data. Microsoft Azure Fundamentals: Websites
  • Architecture-Roof Styles and Distinguishing Features

    Architecture-Roof Styles and Distinguishing Features

    Architecture-Roof Styles and Distinguishing Features DDP-2010 Roof Types Roof shapes Roof Shapes Roofs are broken into two basic shape families: gabled and hipped. Gabled Gabled refers to the family of houses classified by the straight slope falling from ridge to...
  • CEV70854_06_Microsoft_PowerPoint_2016_Basics_NO_ASSESSMENT

    CEV70854_06_Microsoft_PowerPoint_2016_Basics_NO_ASSESSMENT

    SmartArt combines text, shapes, effects and other objects to create graphics. SmartArt can be formatted and edited to fit a user's needs using many of the tools which have been previously used to format other objects.