Anda di halaman 1dari 11

CP5639 Week 4 PRACTICE on ITERATIONS

REPETITION USING THE WHILE STRUCTURE


The solution algorithms developed so far have one characteristic in common: they show the program
logic required to process just one set of input values. However, most programs require the same logic
to be repeated for several sets of data. The most efficient way to deal with this situation is to establish
a looping structure in the algorithm that will cause the processing logic to be repeated a number of
times. There are three different ways in which a set of instructions can be repeated, and each way is
determined by where the decision to repeat is placed:

• at the beginning of the loop (leading decision loop)

• a counted number of times (counted loop).

The WHILE construct was introduced as the pseudocode representation of a repetitive loop. Its format
is:

WHILE condition p is true


statement block
ENDDO

The WHILE construct is a leading decision loop – the condition is tested before any statements are
executed. In the above WHILE loop, the following processing takes place:

1 The logical condition p is tested.

2 If condition p is found to be true, the statements within the statement block are executed
once. The delimiter ENDDO then triggers a return of control to the retesting of condition p.

3 If condition p is still true, the statements are executed again, and so the repetition process
continues until the condition is found to be false.

4 If condition p is found to be false, control passes to the next statement after the delimiter
ENDDO and no further processing takes place within the loop.

There are two important considerations of which you must be aware before designing a WHILE loop:

• The testing of the condition is at the beginning of the loop. This means that it may be
necessary to perform some initial processing to adequately set up the condition before it can
be tested.

• The only way to terminate the loop is to render the WHILE condition false. This means
some process must be set up within the statement block that will eventually change the
condition so that the condition becomes false. Failure to do this results in an endless loop.

Using WHILE to repeat a set of instructions a known number of times When a set of instructions is to
be repeated a specific number of times, a counter can be used in pseudocode, which is initialised
before the WHILE statement and incremented just before the ENDDO statement.

1
EXAMPLE 1: Fahrenheit–Celsius conversion

Every day, a weather station receives 15 temperatures expressed in degrees Fahrenheit. A program is
to be written that will accept each Fahrenheit temperature, convert it to Celsius and display the
converted temperature to the screen. After 15 temperatures have been processed, the words ‘All
temperatures processed’ are to be displayed on the screen.

A Defining diagram

Having defined the input, output and processing, you are ready to outline a solution to the problem.
This can be done by writing down the control structures needed and any extra variables that are to be
used in the solution algorithm. In this example, you need:

• a WHILE structure to repeat the necessary processing

• a counter, called temperature_count, initialised to zero, that will control the 15 repetitions.

B Solution algorithm

This solution algorithm illustrates a number of points:

1 The temperature_count variable is initialised before the WHILE condition is executed.

2 As long as temperature_count is less than 15 (that is, the WHILE condition is true), the
statements between WHILE and ENDDO will be executed.

3 The variable temperature_count is incremented once within the loop, just before the
ENDDO delimiter (that is, just before it is tested again in the WHILE condition).

2
4 After 15 iterations, temperature_count will equal 15, which causes the WHILE condition to
become false and control to be passed to the state- ment after ENDDO.

C Desk checking

Although the program will require 15 records to process properly, at this stage it is only necessary to
check the algorithm with two valid sets of data.

3
=======

CLASS ACTIVITY WEEK 4: SAME ALGORITHM USING LISTS AND FOR LOOP

Validation:

LINE ftempList item Ctemp


1 ftempList = [0,0,0]
2 item = ftempList[0]
2.1 ftempList = item =
[200,0,0] getValidValue()
= 200
2.2 Ctemp =
getTempInCelsius(200)
Ctemp = 93
2.3 93 displayed
2 item = ftempList[1]
2.1 ftempList = item =
[200,250,0] getValidValue()
=250

2.2 Ctemp =
getTempInCelsius(250)
Ctemp = 121
2.3 Displayed 121

2 item = ftempList[2]

4
2.1 ftempList = item =
[200,250,300] getValidValue()
=300

2.2 Ctemp =
getTempInCelsius(300)
Ctemp = 149
2.3 Displayed 149
3

getValidValue LINE value


1 300
2 Condition false
2.1
2.2
3 300

getValidValue LINE value


1 200
2 conditionfalse
2.1
2.2
3 200

getTempInCelcius Ftemp ctemp


LINE
1 200 93
2 93

5
COUNTED REPETITION / COUNTED LOOP

Counted repetition occurs when the exact number of loop iterations is known in advance. The
execution of the loop is controlled by a loop index, and instead of using WHILE, or
REPEAT...UNTIL, the simple keyword DO is used as follows:
DO loop_index = initial_value to final_value
statement block
ENDDO

The DO loop does more than just repeat the statement block. It will:

1 initialise the loop_index to the required initial_value

2 increment the loop_index by 1 for each pass through the loop

3 test the value of loop_index at the beginning of each loop to ensure that it is within the
stated range of values

4 terminate the loop when the loop_index has exceeded the specified final_ value.

In other words, a counted repetition construct will perform the initialising, incrementing and testing of
the loop counter automatically. It will also terminate the loop once the required number of repetitions
has been executed.

Let us look again at the previous example which processes 15 temperatures at a weather station each
day. The solution algorithm can be rewritten to use a DO loop.

EXAMPLE 2: Fahrenheit–Celsius conversion

Every day, a weather station receives 15 temperatures expressed in degrees Fahrenheit. A program is
to be written that will accept each Fahrenheit temperature, convert it to Celsius and display the
converted temperature to the screen. After 15 temperatures have been processed, the words ‘All
temperatures processed’ are to be displayed on the screen.

6
Note that the DO loop controls all the repetition: Display ‘All temperatures processed’ to the screen
END

• It initialises temperature_count to 1.

• It increments temperature_count by 1 for each pass through the loop.

• It tests temperature_count at the beginning of each pass to ensure that it is within the range 1
to 15.

• It automatically terminates the loop once temperature_count has exceeded 15.

7
A requirement of counted repetition loops is that the exact number of input data items or records
needs to be known before the algorithm can be written. Counted repetition loops are used extensively
with arrays or tables.

8
PRACTICE

Construct a solution algorithm for the following problems. Your solution should contain, as needed:
• an IPO chart
• C/A decision table (if needed)
• a loop table
• a pseudocode algorithm
• a desk check of the algorithm.
• same for functions as needed

QUESTION 1
Design an algorithm that will output the seven times table, as follows:

7×1=7
7 × 2 = 14
7 × 3 = 21 . . .

QUESTION 2

Design an algorithm that will display to the screen the first 20 numbers, with their squares and cubes,
as follows

QUESTION 3
Design an algorithm that will prompt for, receive and total a collection of payroll amounts entered at
the terminal until a sentinel amount of 999 is entered. After the sentinel has been entered, display the
total payroll amount to the screen.

QUESTION 4
Design an algorithm that will read a series of integers at the terminal. The first integer is special, as it
indicates how many more integers will follow. Your algorithm is to calculate the sum and average of
the integers, excluding the first integer, and display these values to the screen.

9
QUESTION 5
Design an algorithm that will prompt for and receive the time expressed in 2400 format (e.g. 2305
hours), convert it to 12-hour format (e.g. 11:05pm) and display the new time to the screen. Your
program is to repeat the processing until a sentinel time of 9999 is entered.

main():

time = getValidTime()

while time != 9999

conversion = convertTime(time)

display conversion

time = getValidTime()

endwhile

getValidTime():

display “Enter time in 2400 format”

get time

//Conditions for valid time: 4 digits; < 2400; >= 0000; last 2 digits <60

While ((length of time is NOT 4 digits) OR (time >= 2400) OR (time < 0) or (last 2 digits of
time > 60)) and (time NOT 9999)

Display “Invalid input, please enter time in 2400 format”

Get time

Endwhile

Return time

convertTime ():

hours = first 2 digits of time

minutes = last 2 digits of time

if hours >= 12

converted = “pm”

else

converted = “am”

hours = hours mod 12

converted = hours with “:”with minutes with converted

10
return converted

IPO MAIN

Input Processing Output


- - for valid time values different -
than 9999 convert and show
result
IPO getValidTime()

Input Processing Output


- Check repeatedly for valid time time
format
IPO convertTime()

Input Processing Output


Time - converted

11

Anda mungkin juga menyukai