CMP 131 Introduction to Computer Programming - PowerPoint PPT Presentation

About This Presentation
Title:

CMP 131 Introduction to Computer Programming

Description:

and square roots. CONST. MaxI = 4; {largest integer in table} VAR. I, {counter variable} ... { Prints a list of integers, their squares & square roots} ... – PowerPoint PPT presentation

Number of Views:56
Avg rating:3.0/5.0
Slides: 60
Provided by: violettaca
Learn more at: http://www.cs.cmu.edu
Category:

less

Transcript and Presenter's Notes

Title: CMP 131 Introduction to Computer Programming


1
CMP 131Introduction to Computer Programming
  • Violetta Cavalli-Sforza
  • Week 9

2
NEXT WEEK
  • Monday May 14 Quiz
  • Primarily on
  • Ch 2.5 Standard Functions
  • Ch 4 Conditional Statements (except Section
    4.6)

3
THIS WEEK
  • Repeating statement execution and loops
  • Thursday Lab
  • Working on Assignment 4
  • Sunday May 13 Assignment 4due at midnight (NO
    LATE HOMEWORK ACCEPTED)
  • May start looking at the debugger in the Pascal
    IDE (if not, next week)

4
Topics
  • General Loops Ideas Terminology
  • Pascal statements for dealing with loops
  • WHILE loops
  • FOR loops
  • REPEAT-UNTIL loops
  • Types of loops
  • counter-controlled
  • event-driven loops
  • menu-driven loops
  • sentinel-controlled
  • Loop design
  • Common programming errors

5
Repetition
  • Repeating execution of one or more statements
  • One or more statements enclosed inside a
    programming structure that causes them to be
    executed 0 or more times until some condition is
    met or no longer met.
  • The programming structures associated with
    repetitions are called loops.
  • Pascal (like many other languages) has 3 kinds of
    loops
  • FOR loop FOR DO
  • WHILE loop WHILE DO
  • REPEAT loop REPEAT UNTIL

6
Why Use Repetition?
  • Examples
  • Evaluating the gross net pay for the employees
    in a company
  • Evaluating the grades for all students in a
    class,...etc.
  • We can write the process for one individual and
    then ask Pascal to repeat the process for all
    participants

7
Loop Talk/Terminology
  • 2 General Kinds of Repetition
  • Fixed repetition
  • It can be determined in advance how many times a
    segment of code will be repeated
  • The number of times the segment of code is
    repeated is independent of what happens inside
    the loop
  • Variable repetition
  • It cannot be determined in advance how many times
    a segment of code will be repeated
  • The value (true false) of the condition
    determining whether a segment of code will be
    repeated or not changes as a result of what
    happens inside the loop

8
Loop Talk/Terminology Types of Loops
  • Counter-controlled loops
  • Also called Counting loops
  • Repetition is controlled by a variable whose
    value represents a counter
  • E.g. the FOR loop
  • These loops implement fixed repetition
  • Event-driven loops
  • Also called Conditional loops
  • Repetition is controlled by a condition (a
    Boolean variable or expression) whose value
    changes as the loop is executed
  • E.g. the WHILE loop and the REPEAT loop
  • These loops implement variable repetition

9
Loop Talk/Terminology
  • Pretest vs. Posttest Loops
  • Pretest or Entrance Controlled Loop
  • Tests the condition before determining whether to
    go through the loop even once.
  • The condition is a pretest condition
  • If the condition is true the loop is entered
  • If the condition is false the loop is skipped
  • Examples are FOR DO and WHILE DO loops
  • Posttest or Exist Controlled Loop
  • Tests the condition after the loop is gone
    through once.
  • The condition is a post condition
  • Example is REPEAT UNTIL loop
  • If the condition is true the loop exits
    (terminates).
  • If the condition is false the contents of the
    loop are repeated

10
Loop Talk/Terminology
  • Repetition is sometimes called iteration
  • Fixed repetition definite iteration
  • Variable repetition indefinite iteration
  • However the terms repetition and iteration have
    another importatant meaning one time through a
    loop
  • E.g. On the first iteration, the value 5 is
    assigned to the variable X, on the second
    iteration, the value 6 is assigned to the
    variable X, etc..

11
Loop Talk/Terminology
  • Loop parts
  • Loop body
  • Contains the steps to be repeated.
  • Loop repetition condition
  • The condition that controls the loop repetition
  • Loop-control variable (or expression)
  • The variable whose value controls loop repetition
  • Must be initialized, tested, and updated for the
    loop to execute properly

12
The FOR Loop Statement
  • Most efficient way of implementing
    counter-controlled (fixed repetition) loops
  • SyntaxFOR ltcountergt ltinitial valuegt TO
    ltfinal valuegt DO ltstatementgtFOR
    ltcountergt ltinitial valuegt DOWNTO ltfinal valuegt
    DO ltstatementgt

13
The FOR Statement
  • Syntax Diagram
  • Flowchart
  • Self-exercise/see book

14
The FOR Statement
  • The FOR statement is considered a single
    statement.
  • ltstatementgt comprises the loop body.
  • It is executed once for each value of the counter
    between ltinitial valuegt and ltfinal valuegt,
    inclusive
  • It is not executed if ltfinal valuegt is smaller
    (for TO) than or greater than (for DOWNTO)
    ltinitialgt
  • It is indented for clarity
  • It is a single statement simple or compound

15
The FOR Statement
  • The value of ltcountergt
  • Starts out by being the value of ltinitial valuegt
  • Is incremented by 1 (if TO is used) or
    decremented by one (if DOWNTO is used) after each
    loop repetition
  • Cannot be modified in the FOR statement
  • After loop exit, the value of the ltcountergt is
    considered undefined You shouldnt attempt to
    use the value of ltcountergt without reassigning to
    ltcountergt first.
  • IGNORE The counter variable should be declared
    as a local variable

16
The FOR Statement
  • ltinitial valuegt and ltfinal valuegt may be
    constants, variables, or expressions of the same
    ordinal type as the ltcountergt
  • The value of ltinitial valuegt is computed once,
    just before loop entry
  • The value of ltfinal valuegt is computed once, just
    before loop entry
  • If ltfinal valuegt is an expression, any change in
    the value of that expression will have no effect
    on the number of iterations performed

17
Example Squares, Square Roots
  • PROGRAM Squares
  • Prints a list of integers, their squares
  • and square roots
  • CONST
  • MaxI 4 largest integer in table
  • VAR
  • I, counter variable
  • Square integer output - square of I
  • Root real output - square root of I
  • Continued

18
Example Squares, Square Roots
  • BEGIN Squares
  • Prints a list of integers, their squares
    square roots
  • writeln ('I' 10, 'I I' 10, 'Square root'
    15)
  • FOR I 1 TO MaxI DO
  • BEGIN
  • Square sqr(I)
  • Root sqrt(I)
  • writeln (I 10, Square 10, Root 151)
  • END FOR
  • END. Squares

19
Example Constant Width Rectangle
  • PROGRAM ConstantSizeRectangles RECTCNST.PAS
  • CONST Line ''
  • VAR Size integer input- height of
    rectangle
  • I integer internal- loop counter
  • BEGIN
  • writeln('Type a positive integer ')
  • readln(Size)
  • writeln
  • FOR I 1 TO Size DO writeln(Line)
  • writeln
  • FOR I Size DOWNTO 1 DO writeln(Line)
  • writeln
  • readln
  • END.

20
Self-Check 5.1
  • Trace the following program fragment
  • J 10FOR I 1 to 5 DO BEGIN
    writeln(I, J) J J - 2 END FOR
  • How many times will the loop body be executed?

21
Self-Check 5.2
  • Write FOR loop headers that process all values of
    Celsius (type integer) in the following ranges
  • -10 through 10
  • 100 through 1
  • 15 through 50
  • 50 through -75
  • What types can be used as FOR loop counters?
  • Write a FOR statement that computes the sum of
    the ODD integers in the range 0 to 100 inclusive

22
The WHILE Statement
  • Syntax
  • WHILE ltexpressiongt DO ltstatementgt
  • Syntax graph

23
The WHILE Statement
  • Flowchart

statement
true
false
24
The WHILE Statement
  • The WHILE statement is considered a single
    statement.
  • ltstatementgt comprises the loop body
  • Is executed zero or more times, depending on the
    value of the condition (and this, in turn, on the
    loop variable)
  • It is indented for clarity
  • Is a single statement (simple or a compound)

25
The WHILE Statement
  • ltexpressiongt is a condition to control the loop
    process
  • It depends on a loop control variable (sometimes
    more than one variable)
  • Caution If the value of the loop control
    variable is not modified inside the loop, the
    loop will execute forever
  • If ltexpressiongt evaluates to
  • true, the statement is executed.
  • false, the first time it is tested, statement
    will not be executed
  • false, after one or more iterations, the WHILE
    loop is exited and the next program statement is
    executed

26
Self-Check 5.3
  • For the following loop
  • X 3Count 0while Count lt 3 do begin
    X X X writeln(X)
    Count Count 1 end while
    writeln(Count)
  • How many times is the loop body repeated?
  • What is printed during each repetition of the
    loop body, and at the very end?
  • What happens if the last statement in the loop
    body is Count Count 2
  • What happens if the last statement in the loop
    body is removed?

27
Self-Check 5.4
  • Write a while loop that displays each integer
    from 1 to 5 on a separate line, along with its
    square.
  • Write a while loop that displays each integer
    from 4 down to -6 on a separate line. Display the
    values in the sequence 4, 2, 0, and so on.

28
Uses of WHILE Statement
  • Accumulating a Sum or a Product
  • Often we use loops to accumulate the sum or
    product by repeating an addition or
    multiplication operation.
  • ExampleVAR CountEmp integer counter
    variable NumEmp integer num of
    employees TotalPay real
    output- cumulative pay Pay real
    pay for each employee .WHILE
    CountEmp lt NumberEmp DO BEGIN TotalPay
    TotalPay Pay CountEmp CountEmp
    1END

Or lt, depends on how CountEmp is initialized
29
Uses of While Statement
  • Maybe the number of elements (times through the
    loop) is known, as in previous
  • Maybe it is not
  • Pseudo-code example
  • WHILE There are more employees DO
  • BEGIN
  • Get employee pay
  • TotalPay TotalPay Pay
  • END

30
Example Program Compute Company Payroll
  • PROGRAM CompanyPayroll
  • Compute the payroll for a company
  • VAR
  • NumberEmp, CountEmp integer
  • Hours, Rate, Pay, TotalPay real
  • BEGIN
  • Enter number of employees.
  • write ('Enter number of employees gt ')
  • readln (NumberEmp)
  • loop repetitions determined by the user
  • continued

31
  • .
  • Compute each employee's pay add
    it to the payroll.
  • TotalPay 0.0
  • CountEmp 0
  • WHILE CountEmp lt NumberEmp DO
  • BEGIN
  • write ('Hoursgt ')
  • readln (Hours)
  • write ('Rate gt ')
  • readln (Rate)
  • Pay Hours Rate
  • writeln ('Pay is ', Pay 42)
  • writeln
  • TotalPay TotalPay Pay
  • CountEmp CountEmp 1
  • END WHILE
  • writeln writeln('All employees processed')
  • writeln ('Total payroll is ', TotalPay 42)
  • END. CompanyPayroll

32
Example Output Compute Company Payroll
  • Enter number of employees gt 3
  • Hoursgt 25
  • Rate gt 25.00
  • Pay is 625.00
  • Hoursgt 40
  • Rate gt 13.75
  • Pay is 550.00
  • Hoursgt 45
  • Rate gt 8.25
  • Pay is 371.25
  • All employees processed
  • Total payroll is 1546.25.

33
Example Trace Compute Company Payroll
  • Number of employees 3
  • Employee Number of hours Rate
  • 1 25 25.00
  • 2 40 13.75
  • 3 8.25 45.00 
  • Iteration TotalPay Pay
  • 1 0.0 625.0
  • 2 625.0 550.0
  • 3 1175.0 371.25 
  • After the end of the loop TotalPay 1546.25

34
Self-Check 5.5
  • What output values are displayed when X is 5?
  • write(Enter an integer )readln(X)Product
    1Count 0WHILE Count lt 4 DO BEGIN
    writeln(Product) Product
    Product X Count Count 1 END
  • What happens if the writeln statement is moved to
    the bottom of the loop body?

35
Self-Check 5.6
  • What mathematical operation does this compute?
  • write(Enter X ) readLn(X)write(Enter Y
    ) readLn(Y)Product 1WHILE Y gt 0 DO
    BEGIN Product Product X Y
    Y - 1 ENDwriteln(Result , Product)

36
Self-Check 5.7
  • When Robins new baby was born, she opened a
    savings account with 1,000.00. On each birthday,
    starting with the first, the bank added an
    additional 4.5 of the balance, and Robin added
    another 500.00 to the account.
  • Write a loop that will determine how much money
    was in the account on her childs 18th birthday.

37
FOR vs. WHILE Statement
  • The following two statements behave in the same
    way. Which you think is easier?
  • print n blank lines print n blank lines
  • Line 1 FOR Line 1 TO N DO
  • WHILE Line lt N DO writeln
  • BEGIN
  • writeln
  • Line Line 1
  • END
  • Event-driven Counter-Controlled Loop Loop

38
Counter-Controlled Loops
  • Template 1
  • Set counter variable to 0
  • WHILE counter variable lt final value DO
  • BEGIN
  • ...
  • increase counter variable by 1
  • END
  • Template 2
  • Set counter variable to 1
  • WHILE counter variable lt final value DO
  • BEGIN
  • ...
  • increase counter variable by 1
  • END

39
Event-Driven Loops ExampleHungry Worm
  • Problem Definition
  • A hungry worm approaching an apple. Each time it
    moves, the worm cuts the distance between itself
    and the apple by its own body length until the
    worm is close enough to enter the apple.

40
Example Hungry Worm
  • Questions
  • What initialization must be performed?
  • Distance must be equal to InitialDistance
  • How to process within loop body?
  • Distance during passi must be less than that
    during passi-1 by the length of the worm.
  • When to exit?
  • Distance must lie between zero worm's body
    length

41
Example Program Hungry Worm
  • PROGRAM WormApple WORMAPPL.PAS
  • CONST
  • WormLength 3.5
  • VAR
  • InitialDist, input
  • Distance Real output
  • continued

42
Example Hungry Worm
  • BEGIN
  • write ('Enter initial distance between worm and
    apple in inches gt ')
  • readln (InitialDist)
  • Distance InitialDist
  • WHILE Distance gt WormLength do
  • BEGIN
  • writeln('The distance is ', Distance
    42)
  • Distance Distance - WormLength
  • END WHILE
  • writeln
  • writeln('The last distance before entering
    the apple is ',
  • Distance31)
  • end. WormLength

43
Example Hungry Worm
  • Observations
  • If the initial distance 12.0 the loop will be
    repeated 3 times
  • Distance is
  • Initialized before the loop header is reached
  • Tested before each iteration
  • Updated during each iteration

44
Example Paying Monthly Bills
  • Algorithm (Pseudocode)
  • 1.      Initialize Balance to InitBal
  • 2.      WHILE Balance gt 0.0 DO
  • BEGIN
  • 3. Read data for current bill
  • 4. Display check-writing
  • information, if bill can be paid
  • 5. Balance Balance Bill
  • END

45
Example Paying Monthly Bills
  • PROGRAM PayBills
  • Authorizes payment of each bill as there are
    sufficient funds in the checking account. Assume
    bills are entered in order starting with the
    smallest and the total amount owed exceeds the
    initial account balance
  • VAR
  • creditor string input-name of creditor
  • bill, input-amount of bill
  • InitBal, input-starting balance
  • Balance real current balance
  • BEGIN
  • write(Enter initial account balance )
  • readln(InitBal)
  • Pay each bill as long as the account is not
    overdrawn.
  • Decrease the balance by the bill amount after
    each bill is processed.

46
Example Paying Monthly Bills
  • PROGRAM PayBills
  • . . .
  • Balance InitBal
  • WHILE Balance gt 0.0 DO
  • BEGIN
  • writeln
  • write(Enter next creditor )
  • readln(Creditor)
  • writeln(Enter amount owed )
  • readln(Bill)
  • IF Balance gt Bill
  • THEN
  • BEGIN
  • writeln(Issue check for ,Bill32, to
    , creditor)
  • Balance Balance Bill
  • END
  • ELSE
  • writeln(No check issued ,
  • Account balance is only , Balance32)

47
Example Paying Monthly Bills
  • Observations
  • Balance is the loop-control variable
  • Balance must equal to InitBal just before the
    loop begins
  • Pay the current bill if the account has
    sufficient funds
  • Balance of next pass equals to Balance of current
    pass minus the amount of current bill
  • Stop paying bills when Balance becomes negative

48
Self-Check 5.8
  • When would the output of the following segment be
    erroneous? How could it be fixed?
  • Total 0write(Enter number of items to
    process )readln(Num)Count 0WHILE Count
    lt Num DO BEGIN write(Enter a value
    ) readln(Value) Last
    Value ENDwriteln(The last value entered
    was , Last)

49
Self-Check 5.9
  • There are 9870 people in a town whose population
    increases by 10 each year. Write a loop that
    determines how many years (CountYears) it would
    take for the population to exceed 30,000.

50
The REPEAT Statement
  • Syntax
  • REPEAT
  • ltloop bodygt
  • UNTIL lttermination conditiongt
  • Syntax graph
  • Flowchart
  • Self-exercise/see book

51
The REPEAT Statement
  • ltexpressiongt is the loop termination test
  • After each execution of the loop body,
    termination condition is evaluated
  • The loop body (between REPEAT and UNTIL) is zero
    or more statements
  • If termination condition evaluates to
  • true, loop exit occurs and next program statement
    is executed
  • false, loop-body is repeated
  • The test is the logical complement of the test in
    the WHILE loop (DeMorgans Theorem)

52
DeMorgans Laws/Theorem
  • NOT (A OR B) ltgt (NOT A) AND (NOT B)
  • NOT (A AND B) ltgt (NOT A) OR (NOT B)
  • Distributing the negation through an AND/OR
    operator.See FILE DEMORGAN.PAS)

53
Example Largest Number
  • PROGRAM Largest
  • Finds the largest number in a sequence of
    integer values
  • CONST
  • MinVal -MaxInt
  • VAR
  • Item, data value
  • LargestSoFar integer largest value so
    far
  • BEGIN
  • LargestSoFar MinVal
  • REPEAT
  • write('Enter an integer or ', MinVal, ' to
    stop ')
  • readln(Item)
  • IF Item gt LargestSoFar THEN
  • LargestSoFar Item
  • UNTIL Item MinVal
  • writeln('The largest value entered was ',
    LargestSoFar)
  • readln
  • END. Largest

54
Example Smallest Number
  • PROGRAM Smallest
  • Finds the largest number in a sequence of
    integer values
  • CONST
  • MaxVal MaxInt
  • VAR
  • Item, data value
  • SmallestSoFar integer largest value so
    far
  • BEGIN
  • SmallestSoFar MaxVal
  • REPEAT
  • write('Enter an integer or ', MaxVal, ' to
    stop ')
  • readln(Item)
  • IF Item lt SmallestSoFar THEN
  • SmallestSoFar Item
  • UNTIL Item MaxVal
  • writeln('The smallest value entered was ',
    SmallestSoFar)
  • readln
  • END. Smallest

55
Menu-Driven Programs
  • Menu-driven program
  • A program containing a loop that displays a menu
    of operations. The user selects the next
    operation from the menu.
  • Template for menu-driven loops
  • REPEAT
  • Display the menu
  • Read the users choice
  • Perform the users choice
  • UNTIL users choice is exit program

56
Menu-Driven Programs
  • A REPEAT statement is often used to control a
    menu-driven program, which prints a list of
    choices from which the user selects an operation.
  • Example
  • 1. Compute an average.
  • 2. Compute a standard deviation.
  • 3. Find the median.
  • 4. Find the smallest and largest values.
  • 5. Plot the data.
  • 6. Exit the program.
  • A CASE statement can be used to process the
    choices.
  • Use the ELSE / OTHERWISE clause to catch a bad
    choice.

57
Menu-Driven Programs
  • program segment
  • REPEAT
  • DisplayMenu Display the menu choices
  • writeln('Enter a number between 1 and ',
    ExitChoice 1)
  • readln(Choice)
  • Perform the user's choice
  • UNTIL Choice ExitChoice

58
Self-Check 5.10
  • Use DeMorgans theorem to complement the
    following conditions
  • (X lt Y) and (X ltgt 15)
  • (X lt Y) or (Z 7.5)
  • (X ltgt 15) or (Z 7.5)
  • Flag or not (X ltgt 15.7)
  • not Flag and (X lt 8)
  • When would you use a REPEAT-UNTIL loop rather
    than a WHILE loop?

59
Self-Check 5.11
  • What would the following REPEAT statement
    display?
  • REPEAT writeln(False conditional
    example.)UNTIL false
  • What is the difference between REPEAT...UNTIL
    false and WHILE false DO ?
  • Write a program fragment that continues to read
    data values as long as they are not decreasing.
    Write two versions using REPEAT and WHILE.
Write a Comment
User Comments (0)
About PowerShow.com