chapter 4

36
1 CHAPTER 4 Iterative Structure

Upload: ledell

Post on 18-Feb-2016

47 views

Category:

Documents


0 download

DESCRIPTION

CHAPTER 4. Iterative Structure. Content. Introduction 3 types of iterative structure FOR-ENDFOR WHILEDO-ENDWHILE DOWHILE-ENDWHILE Pseudocode for iterative structure Q&A. Introduction . aka repetition/loop structure - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CHAPTER 4

1

CHAPTER 4Iterative Structure

Page 2: CHAPTER 4

2

Content Introduction 3 types of iterative structure

FOR-ENDFOR WHILEDO-ENDWHILE DOWHILE-ENDWHILE

Pseudocode for iterative structure Q&A

Page 3: CHAPTER 4

3

Introduction aka repetition/loop structure

Same logic steps (a set of instructions)

are repeated for several unique sets of

data.

Process in the loop is repeated a number

of times while the condition result is true

When the condition result is false, the

loop exited

Page 4: CHAPTER 4

4

Introduction A completion of the process

must be identified which will bring the loop into a stop, otherwise the program may have an infinite loop.

For e.g. end of file for input from file, for interactive program, the

user might indicate that the input is complete by typing an end value from the keyboard such as an ‘N’ at the “Do you wish to continue?” prompt

Page 5: CHAPTER 4

5

Introduction Consider a program to read and

calculate the age of all students. The age is calculated by having the current date minus the student’s birth date. These instructions are only written once and can be repeated over and over again for each student using a loop.

Page 6: CHAPTER 4

6

Introduction A simple example would be :

If you want to print “Hello World” 100 times, you will not use 100 print lines, i.e.,

print “Hello World” /* line 1print “Hello World”…print “Hello World” /* line 100

You would only use loop and only having a single print line, i.e.,

FOR counter = 1 to 100Print “Hello World”

END FOR

Page 7: CHAPTER 4

7

Repetition Structure Structure chart is represented by

an asterisk at the top-right corner of a rectangular box.

A Process*An asterisk to denote repetitive component

Processes

Page 8: CHAPTER 4

8

Types of Iterative Structure There are 3 types of iterative

structure

1. FOR-ENDFOR

2. WHILEDO-ENDWHILE

3. DOWHILE-ENDWHILE

Page 9: CHAPTER 4

9

FOR structure Used when the exact number of loop

iteration is known in advance. Requires lowest and highest value of

a range - initial_value and final_value e.g. 1 and 10 for execution of process for 10 times.

Can specify the increment value as well

Test the value of loop_index (loop-control variable) at the beginning of each loop to ensure that it is within the specified range of values

Page 10: CHAPTER 4

10

FOR structure General structure format

PROCESSES

A PROCESS*FOR loop_index = i to n [step m]

Initial value Final value Number of step

Condition is placed on top right side of the iterative component

Page 11: CHAPTER 4

11

FOR structure : ExampleEveryday, a weather station receives

15 temperatures expressed in degrees Fahrenheit. A program is to

be written which will accept each Fahrenheit temperature, convert it to

Celsius and display both temperatures on the screen. After 15 temperatures have been processed,

the word “all temperatures processed” are to be displayed on the

screen

Page 12: CHAPTER 4

12

Solution Algorithm: Example

1. FOR counter = 1 to 15i. Read fahrenheitii. Compute

celsius = (fahrenheit – 32) * 0.5555iii. Display fahrenheit, celsius

2. Display “All temperatures processed”

initializes the counter to 1 Loop is terminated once the counter exceeds 15

Thesestatementswill be repeated15 times

Page 13: CHAPTER 4

13

Solution Algorithm: Example The process of FOR loop:

It initializes the loop_index (in this case, is the counter) to 1

Execute the statements in the loop

Increments the loop_index by 1 as it passes through the loop

Tests the loop_index at the beginning of each pass so that it is within the range 1 to 15

Loop is terminated once the loop_index exceeds 15.

Then the statement after the loop (i.e. statement #2) will be executed

Algorithm:1. FOR counter = 1 to 15

i. Read fahrenheitii. Compute

celsius = (fahrenheit – 32) * 0.5555iii. Display fahrenheit,

celsius2. Display “All

temperatures processed”

Page 14: CHAPTER 4

14

FOR : Structure Chart

TEMPERATURE CONVERSION

PROCESS A TEMPERATURE

*

PROCESS TEMPERATURES

DISPLAY “All temperatures

processed”

DISPLAY FAHRENHEIT,

CELSIUS

CELSIUS=(FAHRENHEIT – 32)

* 0.5555READ

FAHRENHEIT

FOR counter = 1 to 15Steps are repeated 15 times

counter is initialized to 1 and keeps on incremented once all the stepsare executed

Page 15: CHAPTER 4

15

FOR : PseudocodeBEGIN TEMPERATURECONVERSION sequence

BEGIN PROCESSTEMPERATURES iterationFOR counter = 1 to 15

BEGIN PROCESSATEMPERATURE sequence

READ fahrenheit;celsius = (fahrenheit – 32) *

0.555;WRITE fahrenheit, celsius;

END PROCESSATEMPERATURE sequence

ENDFOREND PROCESSTEMPERATURES iterationWRITE “All temperatures processed”;

END TEMPERATURECONVERSION sequence

Page 16: CHAPTER 4

16

For Structure : example 2Design an algorithm to accept several numbers

from the keyboard. The number of input integers is indicated by the first number

entered, e.g. if the first number entered is 5, then 5 input integers will follow. Your

algorithm should be able to decide and display the even integers which have been entered (excluding the first integer). If there are no

even number entered, an appropriate message should be displayed instead.

Task :1. Do the problem analysis

2. Draw the structured chart3. Create the Pseudocode

Page 17: CHAPTER 4

17

Problem Analysis

A. Initialization • evenFound = 0

B. Input Definition• numOfInteger, integerValue

C. Output DefinitionEvenValues = 99 99 99 99

Page 18: CHAPTER 4

18

Problem Analysis

D. Processing Requirements1.READ numOfInteger2.FOR counter = 1 to numOfInteger2.1. READ integerValue2.2. Check Even Number IF number MOD 2 = 0 THEN

2.2.1 evenValues = evenValues + integerValue2.2.2 evenFound = 1

3.Check Even FoundIF evenFound = 1 THEN

DISPLAY evenValues ELSEDISPLAY “No even number found in the input data”

E. Processing Control numOfInteger and integerValue must be integer

MOD is use to find the remainder of a division

Page 19: CHAPTER 4

19

Problem Analysis

numOfInteger integerValue Output

5 10, 20, 15, 12, 3 10 20 12

3 13, 9, 5 No even number found in the input data

3.6 error Error

F. Test Data & Expected Result

Page 20: CHAPTER 4

20

Structured Chart INTEGERPROBLEM

PROCESS AN INTEGER

*

PROCESS INTEGERS DISPLAY Message

Check Even NumberREAD integerValue

FOR counter = 1 to numOfInteger

evenFound = 0

READ numOfInteger

EVEN NUMBERo

integerValue MOD 2 = 0

DISPLAY “No even number found

in the input data”

o

evenFound = 1

evenValues = evenValues + integerValue

evenFound=1

DISPLAY evenValueso

else

Page 21: CHAPTER 4

21

PseudocodeBEGIN INTEGERPROBLEM sequence

evenFound = 0;READ numOfInteger;BEGIN PROCESSINTEGERS iterationFOR counter = 1 to numOfIntegerBEGIN PROCESSANINTEGER sequenceREAD integerValue;BEGIN CHECKEVENNUMBER selectionIF integerValue MOD 2 = 0 THENBEGIN EVENNUMBER sequenceevenValues = evenValues + integerValue;evenFound = 1;END EVENTNUMBER sequenceEND IFEND CHECKEVENNUMBER selectionEND PROCESSANINTEGER sequenceENDFOREND PROCESSINTEGERS iterationBEGIN DISPLAY MESSAGE selectionIF evenFound = 1 THENWRITE evenValues;ELSEWRITE “No even number found in the input data”;END IFEND DISPLAYMESSAGE selection

END INTEGERPROBLEM sequence

Page 22: CHAPTER 4

22

WHILEDO structure Used when we do not know exactly how

many times to carry out the a process Condition is tested first before the block

of statements are executed will continue to repeat a group of

statements while a condition remains true.

When the condition becomes false, the loop is exited

Block of statements are executed 0 or many times

Page 23: CHAPTER 4

23

WHILEDO Structure start off by first testing the condition at

the beginning of the loop a variable will need to be initialised prior

to this test. In many programming languages, if you don’t provide an initial value for a variable, the variable value is unknown or garbage.

Since the loop will only terminates when the WHILE condition is false, some process must be set up within the statement block which will EVENTUALLY CHANGE the condition to becomes false.

Failure to do so results in an endless loop

Page 24: CHAPTER 4

24

WHILEDO structure

General structure format

PROCESSES

A PROCESS*WHILE continue = true

Condition expression

Page 25: CHAPTER 4

25

WHILEDO structure : ExampleEveryday, a weather station receives a number of temperatures expressed in degrees Fahrenheit. A program is to be written which will accept each

Fahrenheit temperature, convert it to celsius and display both

temperatures on the screen. After all temperatures have been processed,

the word “all temperatures processed” are to be displayed on the

screen

Page 26: CHAPTER 4

26

Solution Algorithm: Example1. continue = ‘Y’2. WHILE continue = ‘Y’

i. READ fahrenheitii. CALCULATE Celcius

Celsius = (fahrenheit – 32) * 0.5555iii. DISPLAY fahrenheit, celsiusiv. READ continue

3. Display “All temperatures processed”

Thesestatementswill be repeateduntil continueis not = Y

A variable named ‘continue’ must be initialized

This statement will be executed after continue value is not Y

Page 27: CHAPTER 4

27

WHILEDO : Structure ChartTEMPERATURE CONVERSION

PROCESS A TEMPERATURE

*

PROCESS TEMPERATURES

DISPLAY “All temperatures

processed”

DISPLAY fahrenheit,

celsius

celsius=(fahrenheit – 32)

* 0.5555READ

fahrenheit

WHILE continue = ‘Y’

continue =‘Y’

READ continue

Repeatedsteps

Page 28: CHAPTER 4

28

WHILEDO : pseudocodeBEGIN TEMPERATURECONVERSION sequence

continue = ‘Y’;BEGIN PROCESSTEMPERATURES iteration

WHILE continue = ‘Y’BEGIN PROCESSATEMPERATURE

sequenceREAD fahrenheit;celsius = (fahrenheit – 32) * 0.555;WRITE fahrenheit, celsius;READ continue ;

END PROCESSATEMPERATURE sequenceENDWHILE

END PROCESSTEMPERATURES iterationWRITE “All temperatures processed”;

END TEMPERATURECONVERSION sequence

Page 29: CHAPTER 4

29

DOWHILE structure Same as WHILEDO structure BUT

Condition is tested after the block of statements are executed once.

Block of statements are executed 1 or many times.

Page 30: CHAPTER 4

30

DOWHILE structure

General structure format

PROCESSES

A PROCESS*DOWHILE continue = true

Condition expression

Page 31: CHAPTER 4

31

DOWHILE structure : Example

Everyday, a weather station receives a number of temperatures expressed in degrees Fahrenheit. A program is to

be written which will accept each Fahrenheit temperature, convert it to celsius and display both temperatures on the screen. After all temperatures have been processed, the word “all temperatures processed” are to be

displayed on the screen

Page 32: CHAPTER 4

32

Solution Algorithm: Example

1. DOi.READ fahrenheitii.CALCULATE

Celsius = (fahrenheit – 32) * 0.5555

iii.DISPLAY fahrenheit, celsiusiv.READ continue

WHILE continue= ‘Y’2. DISPLAY “All temperatures

processed”

Thesestatementswill be executedand thenrepeateduntil continueis not = Y

Page 33: CHAPTER 4

33

DOWHILE : structured chartTEMPERATURE CONVERSION

PROCESS A TEMPERATURE

*

PROCESS TEMPERATURES

DISPLAY “All temperatures

processed”

DISPLAY fahrenheit,

celsius

celsius=(fahrenheit – 32)

* 0.5555READ

fahrenheit

DOWHILE continue = ‘Y’

READ reply

Page 34: CHAPTER 4

34

DOWHILE : PseudocodeBEGIN TEMPERATURE_CONVERSION sequence

BEGIN PROCESS_TEMPERATURES iterationDO

BEGIN PROCESS_A_TEMPERATURE sequence

READ fahrenheit;celsius = (fahrenheit – 32) * 0.555;WRITE fahrenheit, celsius;READ continue;

END PROCESS_A_TEMPERATURE sequence

WHILE continue = ‘Y’;END PROCESSTEMPERATURES iterationWRITE “All temperatures processed”;

END TEMPERATURE_CONVERSION sequence

Page 35: CHAPTER 4

35

Class Exercise 1Write the algorithm of a program which will compute and display sum of all odd numbers from 1 to 99 - 1,3,5,7,9…….99.

A manager of a cattle ranch is looking for the great sheep. The first input indicates how many ‘weight of sheep’ records to follow. Records , each containing the sheep number, age in years and weight in kilogram, follow the first input record. All weight must be validated so that the value is more than zero. The program should be able to find the average weight, the detail of the lightest and the heaviest sheep. Write down the algorithm.

Class Exercise 2

Page 36: CHAPTER 4

36

Solution for Exercise 21. totalweight = 0, lightest=1000, heaviest=02. READ noofsheep3. FOR count = 1 to noofsheep

3.1 Read sheepno, age3.2 DO3.2.1 Read weight3.2.2 IF weight <= 0 THEN Display “Invalid weight. Reenter weight” WHILE weight <= 03.3 totalweight = totalweight + weight3.4 If weight < lightestl_sheepno = sheepno, l_age=age, lightest = weight3.5 If weight > heaviesth_sheepno = sheepno, h_age = age, heaviest =weight

4. avgweight = totalweight/noofsheep5. Display avgweight6. Display l_sheepno, l_age, lightest7. Display h_sheepno, h_age, heaviest