1 / 7

Shortcoming of the FOR-DO loop

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.

Download Presentation

Shortcoming of the FOR-DO loop

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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.

  2. 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;

  3. 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.

  4. 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.

  5. 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.

  6. 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;

  7. 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.

More Related