cmp 131 introduction to computer programming violetta cavalli-sforza week 10

29
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Upload: lynette-arnold

Post on 18-Jan-2016

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

CMP 131Introduction to Computer

Programming

Violetta Cavalli-Sforza

Week 10

Page 2: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

TODAY

• Finish loops (or almost)

• Homework #5 was posted on Monday Don’t wait to start on it!!!

Page 3: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Equivalent Statements• FOR loop

FOR Count := StartValue TO StopValue DO BEGIN ... END {FOR}

• Equivalent WHILECount := StartValue;WHILE Count <= StopValue DO

BEGIN ... ; Count := Count + 1; END {WHILE}

• Equivalent REPEATCount := StartValue;IF StartValue <= StopValue THEN

REPEAT ... Count := Count + 1;UNTIL Count > StopValue

Page 4: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Simple Applications of FOR Lopps

• Printing patterns– E.g. diagonal band– E.g. tree

• Generating numbers (e.g. tables)– E.g. table of powers of numbers

(sqr, sqrt, cubes)– E.g. Fibonacci numbers

Page 5: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Task: Draw Diagonal Band

***

***

***

***

***

***

***

***

Page 6: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Program: Diagonal Band

PROGRAM DiagonalBand;

VAR J : integer;

BEGIN

FOR J := 1 TO 8 DO

writeln('***':J + 3);

readln

END.

Page 7: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Task: Draw Tree

* * * * * * ***** **** * * * * ***

Page 8: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Program: Tree

PROGRAM Tree;VAR J : integer;BEGIN writeln('*':5); FOR J := 1 to 3 DO writeln('*':5 - J,'*':2 * J); writeln('**** ****'); FOR J := 1 to 2 DO writeln('* *':6); writeln('***':6); readlnEND.

Page 9: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Task: Fibonacci Numbers

• Print the first 20 Fibonacci numbers

• Fibonacci numbers function:

Page 10: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Program: FibonacciPROGRAM Fibonacci;CONST Number = 20;VAR J , {counter variable} N1, N2, N3 {counter variable} : integer;BEGIN N1 := 0; writeln('Fibonacci 0:', N1:5); N2 := 1; writeln('Fibonacci 1:', N2:5); FOR J := 2 TO Number – 1 DO BEGIN N3 := N1 + N2; writeln('Fibonacci',J:3,':',N3:5); N1 := N2; N2 := N3; END; readlnEND.

Page 11: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Output: FibonacciFibonacci 0: 0Fibonacci 1: 1Fibonacci 2: 1Fibonacci 3: 2Fibonacci 4: 3Fibonacci 5: 5Fibonacci 6: 8Fibonacci 7: 13Fibonacci 8: 21Fibonacci 9: 34Fibonacci 10: 55Fibonacci 11: 89Fibonacci 12: 144Fibonacci 13: 233Fibonacci 14: 377Fibonacci 15: 610Fibonacci 16: 987Fibonacci 17: 1597Fibonacci 18: 2584Fibonacci 19: 4181

Page 12: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Simple Applications of WHILE/REPEAT loops

• Accumulators– E.g. sums, means,

• Simulations

Page 13: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Loop Design

• Terminology– Loop control:

• Making sure that the loop exits when it is supposed to

– Loop processing:• Making sure that the body performs the required

operations

• To formulate loop control & loop processing, it is useful to list what we know about the loop

Page 14: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Loop Design

• Loop design can be approached in two ways:– Analyze requirements:

• Determine needed initialization, testing, and updating of the loop control variable

• Then formulate the loop control and loop processing steps

– Develop templates:• Make templates for frequently running forms• Use these templates as the basis for the new loop

Page 15: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Sentinel-Controlled Loops

• Sentinel:– An end marker that follows the last data item

• Frequently, you will not know exactly how many data items a program will process before it begins execution

• One way to handle this is to instruct the user to enter a unique data value (sentinel value) as the last data item. The program then tests each data item and terminates when the sentinel value is read.

• Sentinel value should be carefully chosen and must be a value that could not normally occur as data.

Page 16: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Sentinel-Controlled Loops

• Template:Read the first value of input variable

WHILE input variable is not equal to sentinel do

BEGIN

...

Read next value of input variable

END

Page 17: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Sentinel-Controlled Loops

• Example: Collecting Exam Scores:1.Initialize Sum to 0

2.Read the first score into Score

3.WHILE Score is not the sentinel (e.g. -1) do

BEGIN

4. Add Score to Sum

5. Read the next score into Score

END

Page 18: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Loops Controlled by Boolean Flags

• Flag: A Boolean variable whose value is changed from False to True when a particular event occurs

•  Boolean Flags Template:Initialize flag to false

WHILE flag is still false DO

BEGIN

...

Reset flag to true if event being monitored occurs

END

Page 19: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Loops Controlled by Boolean Flags

• Example: Reading data characters and save the first digit character read

DigitRead := false;WHILE ( not DigitRead ) DO BEGIN write ('Enter another data character >'); readln (NextChar); DigitRead := ('0'<=NextChar) AND (NextChar<='9') END {WHILE}

Page 20: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Task: Dropping Objects

• Problem definition:– Your physics professor wants you to write a

program that displays the effect of gravity on a free-falling object. You should build a table showing the height from a tower to every second.

Page 21: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Analysis: Dropping Objects

• Observations:– Assume

• time of free fall = t– At t = 0.0 {initialization}

• object height = tower height– While falling {updating-loop

body}• object height =

tower height - distance traveled– Free fall ends {testing -exit}

• when height <= 0.0

Page 22: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Program Segment: Dropping Objects

writeln ('Time' :10:2, 'Height' 10:2);{initialization}T := 0.0;Height := Tower;WHILE Height > 0.0 DO BEGIN {body}

writeln (T : 10:2, Height :10:2);T := T + DeltaT;Height := Tower - 0.5 * G *

Sqr(T) END {WHILE}writeln;writeln ('SPLATT!!!');

Page 23: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Example: Dropping Objects

• Observations – Before the loop is entered, a message

displaying the heading is printed.– The number of lines in the table depends on

the time interval between lines (DeltaT) and the tower height (Tower).

– During each loop iteration, the current elapsed time, t, and the current object height are displayed and new values are assigned to these variables.

Page 24: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Simple Loops Summary• Use FOR loop as a counting loop. The loop control

variable must belong to an ordinal type (not real).• REPEAT and WHILE-loops are conditional loops. Their

number of iteration depends on whether the value of a condition is true or false.

• WHILE loop is repeated as long as its loop repetition condition is true.

• REPEAT loop is repeated until its loop-termination condition becomes true.

• Usually a REPEAT loop can be written as a WHILE loop by complementing the condition.

• Not all WHILE loops can be written as REPEAT loops, because REPEAT loops executes at least once, whereas a WHILE loop body may be skipped entirely.

• WHILE loop is preferred over a REPEAT loop unless you are certain that at least one loop iteration must always be performed.

Page 25: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Exercises

• Write a while loop that counts the number of digits entered in a stream of characters. Exit when the character ‘X’ is entered. Make sure you don’t count the X

• Write a while loop that reads negative or positive numbers, keeping track of the largest in absolute terms. Exit when a zero is entered.

• Write a while loop that reads lines of text, and counts the characters entered. Exit when the string ‘Quit’ is entered. (Don’t count the characters in ‘Quit’).

Page 26: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Nested Loops

• It is possible to nest loops• Each time the outer loop is repeated, the inner

loops are reentered, their loop-control parameters are reevaluated, and all required iterations are performed

• Very useful in processing multi-dimensional arrays

Page 27: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Task: Draw Isosceles Triangle

*

***

*****

*******

*********

Page 28: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Program: Isosceles Triangle

PROGRAM Triangle;{Draw an isosceles triangle} CONST

NumLines = 5; {number of rows in triangle}Blank = ' '; {output character}Star = '*'; {output character}

VARRow, {control for outer loop}LeadBlanks, {control for first inner loop}CountStars: integer; {control for 2nd inner loop}

 {Continued}

Page 29: CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10

Nested Loops ExampleIsosceles Triangle

BEGIN {Triangle}

FOR Row := 1 TO NumLines DO {outer loop}

BEGIN {Draw each row}

{first inner loop}

FOR LeadBlanks := NumLines - Row DOWNTO 1 DO

write (Blank); {Print leading blanks}

{second inner loop}

FOR CountStars := 1 TO 2 * Row - 1 DO

write (Star); {Print asterisks}

writeln;

END {for Row}

end. {Triangle}