Shortcoming of the FOR-DO loop - PowerPoint PPT Presentation

1 / 7
About This Presentation
Title:

Shortcoming of the FOR-DO loop

Description:

... a set of data but isn't a possible value of the data ... if we write a program that a police officer uses to enter the speed of each car ... Priming the values ... – PowerPoint PPT presentation

Number of Views:22
Avg rating:3.0/5.0
Slides: 8
Provided by: evank
Learn more at: http://cs.nyu.edu
Category:
Tags: for | loop | shortcoming

less

Transcript and Presenter's Notes

Title: Shortcoming of the FOR-DO loop


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 didnt 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 lt 100 DO BEGIN
  • Write (i, )
  • i i 3
  • End

3
The WHILE loop (cont)
  • 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 (cont)
  • 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 isnt 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 ltgt -1) DO BEGIN
  • totalScore totalScore testScore
  • Read (testScore)
  • END

7
Homework due April 4
  • Maratecks 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.
Write a Comment
User Comments (0)
About PowerShow.com