Download presentation
Presentation is loading. Please wait.
1
CHAPTER 4 Iterative Structure
2
Content Introduction 3 types of iterative structure FOR-ENDFOR
WHILEDO-ENDWHILE DOWHILE-ENDWHILE Pseudocode for iterative structure Q&A
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
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
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.
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 1 print “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 100 Print “Hello World” END FOR
7
Repetition Structure Processes A Process
Structure chart is represented by an asterisk at the top-right corner of a rectangular box. Processes An asterisk to denote repetitive component * A Process
8
Types of Iterative Structure
There are 3 types of iterative structure FOR-ENDFOR WHILEDO-ENDWHILE DOWHILE-ENDWHILE
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
10
FOR structure General structure format
Condition is placed on top right side of the iterative component PROCESSES FOR loop_index = i to n [step m] A PROCESS * Initial value Final value Number of step
11
FOR structure : Example
Everyday, 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
12
Solution Algorithm: Example
Loop is terminated once the counter exceeds 15 initializes the counter to 1 FOR counter = 1 to 15 Read fahrenheit Compute celsius = (fahrenheit – 32) * Display fahrenheit, celsius Display “All temperatures processed” These statements will be repeated 15 times
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: FOR counter = 1 to 15 Read fahrenheit Compute celsius = (fahrenheit – 32) * Display fahrenheit, celsius Display “All temperatures processed”
14
FOR : Structure Chart counter is initialized to 1
and keeps on incremented once all the steps are executed TEMPERATURE CONVERSION PROCESS TEMPERATURES DISPLAY “All temperatures processed” FOR counter = 1 to 15 Steps are repeated 15 times PROCESS A TEMPERATURE * READ FAHRENHEIT CELSIUS= (FAHRENHEIT – 32) * DISPLAY FAHRENHEIT, CELSIUS
15
FOR : Pseudocode BEGIN TEMPERATURECONVERSION sequence BEGIN PROCESSTEMPERATURES iteration FOR counter = 1 to 15 BEGIN PROCESSATEMPERATURE sequence READ fahrenheit; celsius = (fahrenheit – 32) * 0.555; WRITE fahrenheit, celsius; END PROCESSATEMPERATURE sequence ENDFOR END PROCESSTEMPERATURES iteration WRITE “All temperatures processed”; END TEMPERATURECONVERSION sequence
16
For Structure : example 2
Design 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 : Do the problem analysis Draw the structured chart Create the Pseudocode
17
Problem Analysis evenFound = 0 numOfInteger, integerValue
Initialization evenFound = 0 Input Definition numOfInteger, integerValue Output Definition EvenValues =
18
Problem Analysis Processing Requirements Processing Control
MOD is use to find the remainder of a division Processing Requirements READ numOfInteger FOR counter = 1 to numOfInteger 2.1. READ integerValue 2.2. Check Even Number IF number MOD 2 = 0 THEN evenValues = evenValues + integerValue evenFound = 1 Check Even Found IF evenFound = 1 THEN DISPLAY evenValues ELSE DISPLAY “No even number found in the input data” Processing Control numOfInteger and integerValue must be integer
19
Problem Analysis Test Data & Expected Result numOfInteger integerValue
Output 5 10, 20, 15, 12, 3 3 13, 9, 5 No even number found in the input data 3.6 error Error
20
Structured Chart o o o evenFound = 1 else integerValue MOD 2 = 0
PROBLEM evenFound = 0 READ numOfInteger PROCESS INTEGERS DISPLAY Message evenFound = 1 else FOR counter = 1 to numOfInteger o o PROCESS AN INTEGER * DISPLAY evenValues DISPLAY “No even number found in the input data” READ integerValue Check Even Number integerValue MOD 2 = 0 o EVEN NUMBER evenValues = evenValues + integerValue evenFound=1
21
Pseudocode BEGIN INTEGERPROBLEM sequence evenFound = 0; READ numOfInteger; BEGIN PROCESSINTEGERS iteration FOR counter = 1 to numOfInteger BEGIN PROCESSANINTEGER sequence READ integerValue; BEGIN CHECKEVENNUMBER selection IF integerValue MOD 2 = 0 THEN BEGIN EVENNUMBER sequence evenValues = evenValues + integerValue; evenFound = 1; END EVENTNUMBER sequence END IF END CHECKEVENNUMBER selection END PROCESSANINTEGER sequence ENDFOR END PROCESSINTEGERS iteration BEGIN DISPLAY MESSAGE selection IF evenFound = 1 THEN WRITE evenValues; ELSE WRITE “No even number found in the input data”; END DISPLAYMESSAGE selection END INTEGERPROBLEM sequence
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
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
24
WHILEDO structure General structure format Condition expression
PROCESSES WHILE continue = true A PROCESS *
25
WHILEDO 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
26
Solution Algorithm: Example
continue = ‘Y’ WHILE continue = ‘Y’ READ fahrenheit CALCULATE Celcius Celsius = (fahrenheit – 32) * DISPLAY fahrenheit, celsius READ continue Display “All temperatures processed” A variable named ‘continue’ must be initialized These statements will be repeated until continue is not = Y This statement will be executed after continue value is not Y
27
WHILEDO : Structure Chart
TEMPERATURE CONVERSION continue =‘Y’ PROCESS TEMPERATURES DISPLAY “All temperatures processed” WHILE continue = ‘Y’ Repeated steps PROCESS A TEMPERATURE * READ fahrenheit celsius= (fahrenheit – 32) * DISPLAY fahrenheit, celsius READ continue
28
WHILEDO : pseudocode BEGIN TEMPERATURECONVERSION sequence continue = ‘Y’; BEGIN PROCESSTEMPERATURES iteration WHILE continue = ‘Y’ BEGIN PROCESSATEMPERATURE sequence READ fahrenheit; celsius = (fahrenheit – 32) * 0.555; WRITE fahrenheit, celsius; READ continue ; END PROCESSATEMPERATURE sequence ENDWHILE END PROCESSTEMPERATURES iteration WRITE “All temperatures processed”; END TEMPERATURECONVERSION sequence
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.
30
DOWHILE structure General structure format Condition expression
PROCESSES DOWHILE continue = true A PROCESS *
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
32
Solution Algorithm: Example
These statements will be executed and then repeated until continue is not = Y DO READ fahrenheit CALCULATE Celsius = (fahrenheit – 32) * DISPLAY fahrenheit, celsius READ continue WHILE continue= ‘Y’ DISPLAY “All temperatures processed”
33
DOWHILE : structured chart
TEMPERATURE CONVERSION PROCESS TEMPERATURES DISPLAY “All temperatures processed” DOWHILE continue = ‘Y’ PROCESS A TEMPERATURE * READ fahrenheit celsius= (fahrenheit – 32) * DISPLAY fahrenheit, celsius READ reply
34
DOWHILE : Pseudocode BEGIN TEMPERATURE_CONVERSION sequence BEGIN PROCESS_TEMPERATURES iteration DO 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 iteration WRITE “All temperatures processed”; END TEMPERATURE_CONVERSION sequence
35
Class Exercise 1 Class Exercise 2
Write the algorithm of a program which will compute and display sum of all odd numbers from 1 to ,3,5,7,9…….99. Class Exercise 2 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.
36
Solution for Exercise 2 totalweight = 0, lightest=1000, heaviest=0
READ noofsheep FOR count = 1 to noofsheep 3.1 Read sheepno, age 3.2 DO 3.2.1 Read weight 3.2.2 IF weight <= 0 THEN Display “Invalid weight. Reenter weight” WHILE weight <= 0 3.3 totalweight = totalweight + weight 3.4 If weight < lightest l_sheepno = sheepno, l_age=age, lightest = weight 3.5 If weight > heaviest h_sheepno = sheepno, h_age = age, heaviest =weight avgweight = totalweight/noofsheep Display avgweight Display l_sheepno, l_age, lightest Display h_sheepno, h_age, heaviest
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.