1 / 59

CMP 131 Introduction to Computer Programming

CMP 131 Introduction to Computer Programming. Violetta Cavalli-Sforza Week 9. NEXT WEEK. Monday May 14 : Quiz Primarily on: Ch 2.5: Standard Functions Ch 4: Conditional Statements (except Section 4.6). THIS WEEK. Repeating statement execution and loops Thursday: Lab

gunther
Télécharger la présentation

CMP 131 Introduction to Computer Programming

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. 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 FORloop • 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 andWHILE … DOloops • Posttest or Exist Controlled Loop: • Tests the condition after the loop is gone through once. • The condition is a post condition • Example is: REPEAT … UNTILloop • 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 iterationhave 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 • Syntax:FOR <counter> := <initial value> TO <final value> DO <statement>FOR <counter> := <initial value> DOWNTO <final value> DO <statement>

  13. TO FOR variable expression expression := DOWNTO DO statement The FOR Statement • Syntax Diagram • Flowchart • Self-exercise/see book

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

  15. The FOR Statement • The value of <counter> • Starts out by being the value of <initial value> • Is incremented by 1 (if TO is used) or decremented by one (ifDOWNTO is used) after each loop repetition • Cannot be modified in the FOR statement • After loop exit, the value of the <counter> is considered undefined: You shouldn’t attempt to use the value of <counter> without reassigning to <counter> first. • [IGNORE: The counter variable should be declared as a local variable]

  16. The FOR Statement • <initial value> and <final value> may be constants, variables, or expressions of the same ordinal type as the <counter> • The value of <initial value> is computed once, just before loop entry • The value of <final value> is computed once, just before loop entry • If <final value> 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 :15:1); 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 := 10;FOR 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. WHILE condition DO statement The WHILE Statement • Syntax: WHILE <expression> DO <statement> • Syntax graph

  23. Start condition ? End The WHILE Statement • Flowchart statement true false

  24. The WHILE Statement • The WHILE statement is considered a single statement. • <statement> 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 • <expression> 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 <expression> 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 := 3;Count := 0;while Count < 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. • Example:VAR CountEmp : integer; {counter variable}NumEmp : integer; {num of employees} TotalPay : real; {output- cumulative pay} Pay : real; {pay for each employee} ….WHILE CountEmp =< NumberEmp DO BEGIN TotalPay := TotalPay + Pay; CountEmp := CountEmp + 1END; Or <, 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 > '); 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 < NumberEmp DO BEGIN write ('Hours> '); readln (Hours); write ('Rate > $'); readln (Rate); Pay := Hours * Rate; writeln ('Pay is $', Pay :4:2); writeln; TotalPay := TotalPay + Pay; CountEmp := CountEmp + 1 END; {WHILE} writeln; writeln('All employees processed'); writeln ('Total payroll is $', TotalPay :4:2) END. {CompanyPayroll}

  32. Example Output: Compute Company Payroll Enter number of employees > 3 Hours> 25 Rate > $25.00 Pay is $625.00 Hours> 40 Rate > $13.75 Pay is $550.00 Hours> 45 Rate > $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 := 1;Count := 0;WHILE Count < 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 := 1;WHILE Y > 0 DO BEGIN Product := Product * X; Y := Y - 1 END;writeln(‘Result = ‘, Product);

  36. Self-Check 5.7 • When Robin’s 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 child’s 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 <= 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 < final value DO BEGIN ... increase counter variable by 1 END • Template 2: Set counter variable to 1 WHILE counter variable =< 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 > '); readln (InitialDist); Distance := InitialDist; WHILE Distance >= WormLength do BEGIN writeln('The distance is ', Distance :4:2); Distance := Distance - WormLength END; {WHILE} writeln; writeln('The last distance before entering the apple is ', Distance:3:1) 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 >= 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 > 0.0 DO BEGIN writeln; write(‘Enter next creditor : ‘); readln(Creditor); writeln(‘Enter amount owed: ‘); readln(Bill); IF Balance >= Bill THEN BEGIN writeln(‘Issue check for $’,Bill:3:2,‘ to ‘, creditor); Balance := Balance – Bill; END ELSE writeln(‘No check issued – ‘, ‘Account balance is only $’, Balance:3:2); END; {WHILE} writeln(‘Insufficient funds to pay any more bills!’); END. {PayBills}

  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 := 0;write(‘Enter number of items to process :’);readln(Num);Count := 0;WHILE Count < Num DO BEGIN write(‘Enter a value :’); readln(Value); Last := Value END;writeln(‘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. REPEAT statement until expression ; The REPEAT Statement • Syntax: REPEAT <loop body> UNTIL <termination condition> • Syntax graph • Flowchart • Self-exercise/see book

More Related