360 likes | 515 Views
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
E N D
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 • 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
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
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.
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
Repetition Structure • 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
Types of Iterative Structure • There are 3 types of iterative structure • FOR-ENDFOR • WHILEDO-ENDWHILE • DOWHILE-ENDWHILE
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
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
FOR structure : Example Everyday, a weather station receives 15temperatures 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
Solution Algorithm: Example • FOR counter = 1 to 15 • Read fahrenheit • Compute celsius = (fahrenheit – 32) * 0.5555 • Display fahrenheit, celsius • Display “All temperatures processed” Loop is terminated once the counter exceeds 15 initializes the counter to 1 These statements will be repeated 15 times
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) * 0.5555 • Display fahrenheit, celsius • Display “All temperatures processed”
counter is initialized to 1 and keeps on incremented once all the steps are executed PROCESS A TEMPERATURE * FOR : Structure Chart TEMPERATURE CONVERSION PROCESS TEMPERATURES DISPLAY “All temperatures processed” FOR counter = 1 to 15 Steps are repeated 15 times READ FAHRENHEIT CELSIUS= (FAHRENHEIT – 32) * 0.5555 DISPLAY FAHRENHEIT, CELSIUS
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
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
Problem Analysis • Initialization • evenFound = 0 • Input Definition • numOfInteger, integerValue • Output Definition EvenValues= 99 99 99 99
Problem Analysis • Processing Requirements • READ numOfInteger • FOR counter = 1 to numOfInteger 2.1. READ integerValue 2.2. Check Even Number IF number MOD 2 = 0 THEN 2.2.1 evenValues= evenValues+ integerValue 2.2.2 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 MOD is use to find the remainder of a division
Test Data & Expected Result Problem Analysis
PROCESS AN INTEGER * Structured Chart INTEGER PROBLEM evenFound = 0 READ numOfInteger PROCESS INTEGERS DISPLAY Message evenFound = 1 else FOR counter = 1 to numOfInteger o o 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
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 IF END DISPLAYMESSAGE selection END INTEGERPROBLEM sequence
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
WHILEDO Structure • start off by first testing the condition at the beginning of the loop • a variable will need to be initialisedprior 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
WHILEDO structure • General structure format Condition expression PROCESSES WHILE continue = true * A PROCESS
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
Solution Algorithm: Example A variable named ‘continue’ must be initialized • continue = ‘Y’ • WHILE continue = ‘Y’ • READ fahrenheit • CALCULATE Celcius Celsius = (fahrenheit – 32) * 0.5555 • DISPLAY fahrenheit, celsius • READ continue • Display “All temperatures processed” These statements will be repeated until continue is not = Y This statement will be executed after continue value is not Y
PROCESS A TEMPERATURE * WHILEDO : Structure Chart TEMPERATURE CONVERSION continue =‘Y’ PROCESS TEMPERATURES DISPLAY “All temperatures processed” WHILE continue = ‘Y’ Repeated steps READ fahrenheit celsius= (fahrenheit – 32) * 0.5555 DISPLAY fahrenheit, celsius READ continue
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
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.
DOWHILE structure • General structure format Condition expression PROCESSES DOWHILE continue = true * A PROCESS
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
Solution Algorithm: Example • DO • READ fahrenheit • CALCULATE Celsius = (fahrenheit – 32) * 0.5555 • DISPLAY fahrenheit, celsius • READ continue WHILE continue= ‘Y’ • DISPLAY “All temperatures processed” These statements will be executed and then repeated until continue is not = Y
PROCESS A TEMPERATURE * DOWHILE : structured chart TEMPERATURE CONVERSION PROCESS TEMPERATURES DISPLAY “All temperatures processed” DOWHILE continue = ‘Y’ READ fahrenheit celsius= (fahrenheit – 32) * 0.5555 DISPLAY fahrenheit, celsius READ reply
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
Class Exercise 1 Write 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. 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.
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