70 likes | 87 Views
Learn how to work around the limitations of FOR-DO loops with WHILE loops, sentinels, and proper prime values. Avoid infinite loops and optimize your code effectively. Update programs to handle upper and lower case letters with a period signal.
E N D
Shortcoming of the FOR-DO loop • When you use the FOR-DO loop you must know how many times you want to perform an action. What if you didn’t know how many times an action was to be performed? • For example, suppose you wanted to know how many times an action needed to be repeated before a certain condition was met.
The WHILE loop WHILE (some Boolean expression is true) DO some particular action i := 0; {initialization of i} WHILE i < 100 DO BEGIN Write (i, ‘ ‘); i = i + 3; End;
The WHILE loop (con’t) • The identifiers in the Boolean expression that controls the WHILE loop must all be defined. If they are not defined by an earlier part of the program, you must initialize them (the book calls this priming) before the loop begins.
The WHILE loop (con’t) • At least one of the statements in the loop must change the value of the Boolean expression so it will eventually become false. Otherwise, the loop will execute forever (this is called an infinite loop). • In Pascal we stop an infinite loop by pressing Ctrl-Break • Poor logic can also cause an infinite loop.
Sentinels • A sentinel is a piece of data that ends a set of data but isn’t a possible value of the data • For example, if we write a program that a police officer uses to enter the speed of each car (s)he gave a speeding ticket to during a week, the end of the data can be indicated by a -1.
Priming the values • Initializing values which will be used in a while loop is called “priming the values.” Incorrect priming can cause subtle bugs. Read(testScore); While (testScore <> -1) DO BEGIN totalScore := totalScore + testScore; Read (testScore); END;
Homework due April 4 • Marateck’s hw #6 • change program to take upper case and lower case letters • Use a WHILE loop to look for the end of the data. The end of the data will be signaled by a period.