cmp 131 introduction to computer programming l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
CMP 131 Introduction to Computer Programming PowerPoint Presentation
Download Presentation
CMP 131 Introduction to Computer Programming

Loading in 2 Seconds...

play fullscreen
1 / 59

CMP 131 Introduction to Computer Programming - PowerPoint PPT Presentation


  • 109 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'CMP 131 Introduction to Computer Programming' - gunther


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
cmp 131 introduction to computer programming

CMP 131Introduction to Computer Programming

Violetta Cavalli-Sforza

Week 9

next week
NEXT WEEK
  • Monday May 14 : Quiz

Primarily on:

    • Ch 2.5: Standard Functions
    • Ch 4: Conditional Statements (except Section 4.6)
this week
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)
topics
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
repetition
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
why use repetition
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
loop talk terminology
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
loop talk terminology types of loops
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
loop talk terminology9
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
loop talk terminology10
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..
loop talk terminology11
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
the for loop statement
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>
the for statement

TO

FOR

variable

expression

expression

:=

DOWNTO

DO

statement

The FOR Statement
  • Syntax Diagram
  • Flowchart
    • Self-exercise/see book
the for statement14
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
the for statement15
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]
the for statement16
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
example squares square roots
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}

example squares square roots18
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}

example constant width rectangle
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.

self check 5 1
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?
self check 5 2
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
the while statement

WHILE

condition

DO

statement

The WHILE Statement
  • Syntax:

WHILE <expression> DO <statement>

  • Syntax graph
the while statement23

Start

condition ?

End

The WHILE Statement
  • Flowchart

statement

true

false

the while statement24
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)
the while statement25
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
self check 5 3
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?
self check 5 4
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.
uses of while statement
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

uses of while statement29
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;

example program compute company payroll
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}

slide31
….

{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}

example output compute company payroll
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.

example trace compute company payroll
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

self check 5 5
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?
self check 5 6
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);

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

for vs while statement
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

counter controlled loops
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

event driven loops example hungry worm
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.
example hungry worm
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
example program hungry worm
Example Program: Hungry Worm

PROGRAM WormApple; {WORMAPPL.PAS}

CONST

WormLength = 3.5;

VAR

InitialDist, {input}

Distance : Real; {output}

{continued}

example hungry worm42
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}

example hungry worm43
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
example paying monthly bills
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

example paying monthly bills45
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.

}

example paying monthly bills46
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}

example paying monthly bills47
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
self check 5 8
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)

self check 5 9
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.
the repeat statement

REPEAT

statement

until

expression

;

The REPEAT Statement
  • Syntax:

REPEAT

<loop body>

UNTIL <termination condition>

  • Syntax graph
  • Flowchart
    • Self-exercise/see book
the repeat statement51
The REPEAT Statement
  • <expression> 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 (DeMorgan’s Theorem)
demorgan s laws theorem
DeMorgan’s Laws/Theorem
  • NOT (A OR B) <==> (NOT A) AND (NOT B)
  • NOT (A AND B) <==> (NOT A) OR (NOT B)
  • Distributing the negation through an AND/OR operator.{See FILE: DEMORGAN.PAS)
example largest number
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 > LargestSoFar THEN

LargestSoFar := Item

UNTIL Item = MinVal;

writeln('The largest value entered was ', LargestSoFar);

readln;

END. {Largest}

example smallest number
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 < SmallestSoFar THEN

SmallestSoFar := Item

UNTIL Item = MaxVal;

writeln('The smallest value entered was ', SmallestSoFar);

readln;

END. {Smallest}

menu driven programs
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 user’s choice

Perform the user’s choice

UNTIL user’s choice is exit program

menu driven programs56
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.
menu driven programs57
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

self check 5 10
Self-Check 5.10
  • Use DeMorgan’s theorem to complement the following conditions
    • (X <= Y) and (X <> 15)
    • (X <= Y) or (Z = 7.5)
    • (X <> 15) or (Z = 7.5)
    • Flag or not (X <> 15.7)
    • not Flag and (X <= 8)
  • When would you use a REPEAT-UNTIL loop rather than a WHILE loop?
self check 5 11
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.