1
CMSC 104, Version 9/011 The while Looping Structure Topics The while Loop Program Versatility o Sentinel Values and Priming Reads Checking User Input Using a while Loop Reading Section 3.7

2
CMSC 104, Version 9/012 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
CMSC 104, Version 9/013 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.

5
CMSC 104, Version 9/015 Good Programming Practice Always place braces around the body of a while loop. Advantages: o Easier to read o Will not forget to add the braces if you go back and add a second statement to the loop body o Less likely to make a semantic error Indent the body of a while loop 3 to 5 spaces -- be consistent!

6
CMSC 104, Version 9/016 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? o the exam grades What are the program outputs? o the average exam grade

9
CMSC 104, Version 9/019 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 : o 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
CMSC 104, Version 9/0112 Why Bother to Make It Easier? Why do we write programs? o 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.

13
CMSC 104, Version 9/0113 Using a Sentinel Value We could let the user keep entering grades and when he’s done enter some special value that signals us that he’s done. This special signal value is called a sentinel value. We have to make sure that the value we choose as the sentinel isn’t a legal value. For example, we can’t use 0 as the sentinel in our example as it is a legal value for an exam score.

14
CMSC 104, Version 9/0114 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.