0% found this document useful (0 votes)
323 views30 pages

Computer Science Coursebook-132-161

This document discusses algorithms and their expression. It begins by defining an algorithm as a sequence of steps to solve a problem. It then discusses different ways to express algorithms, including structured English, pseudocode, and flowcharts. It also outlines the four basic constructs used in algorithms: assignment, sequence, selection, and repetition. Finally, it discusses the common input-process-output structure of many algorithms.

Uploaded by

api-470106119
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
323 views30 pages

Computer Science Coursebook-132-161

This document discusses algorithms and their expression. It begins by defining an algorithm as a sequence of steps to solve a problem. It then discusses different ways to express algorithms, including structured English, pseudocode, and flowcharts. It also outlines the four basic constructs used in algorithms: assignment, sequence, selection, and repetition. Finally, it discusses the common input-process-output structure of many algorithms.

Uploaded by

api-470106119
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Learning objectives

By the end of this chapter you should be able to:


• show understanding that an algorithm is a solution to a • derive pseudocode or a program flowchart from a
problem expressed as a sequence of defined steps structured English description of a problem
• use suitable identifiers for the representation of data • derive pseudocode from a given program flowchart
used by a problem and summarise identifiers using an • show an appreciation of why logic statements are used to
identifier table define parts of an algorithm solution
• show understanding that many algorithms are expressed • use logic statements to define parts of an algorithm
using the four basic constructs of assignment, sequence, solution
selection and repetition • use the technical terms associated with arrays including
• show understanding that simple algorithms consist of upperandlowerbound
input, process, output at various stages • select a suitable data structure (lD or 2D array) to use for
• document a simple algorithm using: structured English, a given task
pseudocode, program flowchart • write algorithms to process array data including sorting
using a bubble sort and searching using a linear search . .
Cambridge International AS and A level Computer Science

11.01 What is an algorithm?

Algorithm: a sequence of steps that can be carried out to perform a task

We use algorithms in everyday life. If you need to change a whee l on a car, you might need to
follow instructions (the algorithm) from a manual:
1 Take a spanner and loosen the wheel nuts.
2 Position a jack in an appropriate place.
3 Raise the car.
4 Take off the wheel nuts and the wheel.
5 Lift replacement w heel into position .
6 Replace wheel nuts and tighten by hand.
7 Lower the car.
8 Fully t ighten wheel nuts.
This might sound all very straightforward. However, if th e instructions are not followed in the
correct logical sequence, the process might become much more difficult or even impossible.
Fo r example, if you tried to do Step 1 after Step 3, the w heel may spin and you can't loosen
the whee l nuts. You can't do Step 4 before Step 3.


If you want to bake a cake, you follow a recipe:

1 Measure th e fol lowing in gredient s: 200g sugar, 200g butter, 4 eggs, 200g flour, 2 teaspoons
baking powder and 2 tablespoons of milk.
2 Mix the ingredients together in a large bowl, until the consistency of the mixture is
smooth.
3 Pour the mixture into a cake tin.
4 Bake in th e oven at 190° C for 20 minutes.
5 Check it is fully cooked.
6 Turn cake out of the tin and cool on a wire rack.
The recipe is an algorithm. The ingredients are the input and the cake is the output. The
process is mixing the ingredients and cooking the mixture in the oven .

Sometimes a step might need breaking down into smaller steps. For example Step 2 can be
more detailed :

2.1 Beat the sugar and butter together until fluffy.


2.2 Add the eggs, one at a time, mixing constant ly.
2.3 Sieve the flo ur and baking powder and stir slowly into the egg mi xture.
2.4 Add milk and mix to give a creamy consistency.
- - - --- - - ---- -~~ - - - -

r
_ Chapter 11: Algorithm Design and Problem Solving
I

Sometimes there might be different st eps depending on some other conditions. For example,
consider how to get from one place to another using the map of the London Underground
system in Figure 11.01.

Nott\n&
WllGat•
oueenswaY ""::~~·
pherd'S
Jush

- - Piccadilly
- - Victoria
- - Jubilee

Figure 11.01 Underground map of London, UK

To travel from King's Cross St. Pancras to Westminster, we consider two routes:


Route A: Take the Victoria Line to Green Park (4 stations); then take the Jubilee Line to
Westm inster (1 station).
Route B: Take the Piccadilly Line to Green Park (6 stations); then take the Jubilee Lin e to
Westm in ster (1 stati on).
Route A loo ks li ke the best route. If there are engineering wo rks on the Victoria Lin e and

trains are de layed, Route B might turn out to be t he quicker route.

The directions on how to get from King's Cross St. Pancras to Westm inster can be written as:

IF there are engin eering works on the Victoria Line

THEN
Take the Piccadilly Li ne to Green Park (6 stat ions)
Take the Jubilee Line to Westm in ster (1 station)
ELSE
Take the Victoria Line to Green Park (4 stations)
Take the Jubilee Line to Westminster (1 station)

TASKll.01
Write the steps to be followed to:

make a sandwich
walk from your school/college to th e nearest shop
log on to your computer.

Many problems have more than one solution. Sometimes it is a personal preferen ce which
solution to choose . Sometimes one sol ution will be better than another.
Cambridge International AS and A level Computer Science

11.02 Expressing algorithms

TIP
Computer scientists are interested in finding good solutions. A good solution gives the correct
results, takes up as little computer memory as possible and executes as fast as possib le. The
solution should be concise, elegant and easy to understand.

In computer science, when we design a solution to a problem we express the solution


(the algorithm) using seque nces of steps written in structured English or pseudocode.
Structured English is a subset of the Engli sh language and consists of command statements.
Pseudocode resembles a programming language w ithout following the syntax of a particular
programming language. A flowchart is an alternative method of representing an algorithm . A
flowchart consists of specific shapes, linked together.
An algorithm consists of a sequence of steps. Under certain condition5 we may wish not to

Structured English: a subset of the English language that consists of command statements used to
describe an algorithm
Pseudocode: a way of using keywords and identifiers to describe an algorithm without following the
syntax of a particular programming language
Flowchart: shapes linked together to represent the sequential steps of an algorith m

perform some steps. We may wish to repea t a number of steps. In computer science, when
writi ng algorithms, we use four basic types of construct:

• Assignment:
a value is given a name (identifier) or the value associated with a given identifier is
changed.
• Sequence:
a number of steps are performed, one after the other.
• Selection:
under certain conditions some steps are performed, otherwise different (or no) steps are
performed.
Repetition:
a sequence of steps is performed a number of times. This is also known as iteration or
looping.
Many problems we try to so lve with a computer involve data . The solution involves inputting
data to the computer, processing the data and outputting results (as shown in Figure 11.02) .

.___'_n_
pu_t_ _,,____ _ _
,1 Pcocess 1-----•I Output

Figure 11.02 lnput- process- output

We therefore also need input and output statements.

We need to know the constructs so we know how detailed our design has to be.
These constructs are represented in each of th e three notations as shown in Table 11.01.

-- --- -- -- ---
i
( Chapter 11: Algorithm Design and Problem Solving

Structured English Pseudocode Flowchart


Assignment and SET A TO 34
Sequence INCREMENT B

Set A to 34

Increment B

Selection IF A IS GREATER THAN B IF A> B


THEN THEN
ELSE ELSE
ENDIF

Repetition REPEAT UNTIL A IS EQUAL TO B REPEAT

UNTIL A= B

,
'
Input INPUT A INPUT "Prompt: 11 A

t
,,
~
INPUT "Prompt : " A

I OUTPUT "Message " OUTPUT "Message" B


r
Output

OUTPUT B t
• OUTPUT "Message" B

Table 11.01 Constructs for computing algorithms


Cambridge International AS and A level Computer Science

In this book, algorithms and program code are typed using the courier font.

11.03 Variables
When we input data for a process, individual values need to be stored in memory. We need
to be able to refer to a specific memory location so that we can write statements of what to
do with the va lue stored there. We refer to these named memory locations as variables. You
can imagine these variables like boxes w ith name labels on them. When a value is input, it is
stored in the box with the spec ified name (id entifier) on it.

Variable: a storage location for a data value that has an identifier

For example, the variable used to store a count of how many guesses have been made might
be given the identifier NumberOfGuesses and the player's name might be stored in a variable
called Thi sPl ayer, as shown in Figure 11.03.

NumberOfGuesses ThisPlayer

Figure 11.03 Variables

Variab le identifiers shou ld not contai n spaces, on ly letters, digits and_ (the underscore
symbo l). To make algorithms easier to understand, the naming of a variab le shou ld reflect
th e va riable's use. This means often that more than one word is used as an identifier. The
formatting conven tion used here is known as Camel Caps. It makes an iden tifi er easier to read.

11.04 Assignments
Assigning a value
The fo llow ing pseudocode stores the value The fol lowing pseudocode stores t he
that is input (for example 15) in a variab le w ith value 1 in the variable with t he identifier
the id entifi er Number (see Figure ll.04(a)). NumberOfGuesses (see Fi gu re ll.04(b)).

INPUT Number NumberOfGuesses ~ 1

Number

(a) (b)

Figure 11.04 Va ria bles being assigned a value


-- - -- --- --- ---- ~- -- ---- -

Chapter 11: Algorithm Design and Problem Solving

Updating a value
The following pseudocode takes the value stored in NumberOfGuesses (see Figure 11.05 (a)),
adds 1 to that value and then stores the new value back into the variable NumberOfGuesses
(see Figure 11.05 (b)).

NumberOfGuesses ~ NumberOfGuesses + 1

I NumberOfGuesses
NumberOfGuesses

(a) (b)

Figure 11.05 Updating the value of a variable

Copying a value
Values can be copied from one variable to another.
The following pseudocode takes the value stored in valuel and copies it to value2


(see Figure 11.06).
Value2 ~ Valuel

Valuel Value2

(a)

Va l uel Value2

(b)

Figure 11.06 Copying the value of a variable

The value in valuel remains the same until it is assigned a different value.

Swapping two values


If we want to swap the contents of two variables, we need to store one of the values in
another variable temporarily. Otherwise the second value to be moved wil l be overwritten by
the first value to be moved.

---------
Cambridge International AS and A level Computer Science

In Fi gu re ll.07(a), we copy the content from value l into a tempo rary va riable called Temp.
Then we copy the content from value2 into valuel Figure ll.07(b)). Fina lly we can copy the
value from Temp into v alue 2 (Figure ll.07(c)).

Figure l l.07 Swapping the values of two variables

Using pseu docode we write :

Temp ... Valuel


Valuel <- Value 2
Value 2 <- Temp

WORKED EXAMPLE 11.01

Using input, output, assignment and sequence constructs


The problem to be solved: Convert a distance in mi les and output t he equ ivalent distance in km .

Step 1: Write t he problem as a series of structured English statements:


INPUT number of miles
Ca l cu late number o f km
OUTPUT calculat ed result as k m

Ste p 2: Analyse the dat a values that are needed.

We need a variable to st ore t he original distance in mi les and a variable to store t he resul t
of multiplying t he number of mi les by 1.61. It is helpful to construct an identifier table to
list the va ria bles.

Identifier Explanation
Miles Distance as a whole number of miles
Km The result from using the given
formula : Km= Miles * 1.61
Table l l.02 Identifier table for miles to km conversion
, -
i
~ Chapter 11: Algorithm Design and Problem Solving
I

Step 3: Provi de more detail by drawing a flowchart or writing pseudocode.

The deta il given in a flowchart should be t he same as the detail given in pseudocode. It
should use the basic constructs listed in Table 11.01.

Figure 11.08 represents our algorithm using a flowchart and the equivalent pseudocode.

I NPUT "Enter mi l es :" Mile s


Km -M ile s * 1 . 61
OUTPUT "km: " Km

INPUT "En te r mi l es : "


Mi l e s

Km - Miles* 1 .6 1

OUTPUT " Km: "


Km

End

Figure 11.08 Flowchart and pseudocode for miles to km conversion

Identifier table: a table listing the variable identifiers required for the solution, with explanations

TASKll.02
Consider the following algorithm steps:
1 Input a length in inches.
2 Ca lcu late the equiva lent in centimetres.
3 Output the resu lt.
List t he variables required in an identifier table.
Write pseudocode or draw a flowchart for the algorithm.

- - -- - - -- -
Cambridge International AS and A level Computer Science

11.05 Logic statements


In Section 11.01, we looked at an algo rithm with different steps dependin g on so me other
condition:

IF t here are engineering works on the Victoria Li ne

TH EN
Take t he Piccadilly Li ne to Gree n Park (6 stati ons)
Take t he Jubil ee Lin e to Westmin st er (1 st ation)
ELSE
Take the Victoria Li ne to Gree n Park (4 stati ons)
Take t he Jubilee Lin e to Westm inste r (1 st ati on)

Th e selecti on const ruct in Table 11.01 uses a co ndition to fol low eith er the first grou p of steps
or th e seco nd group of steps (see Figure 11.09).

Simple condition
IF A< B
THEN
<statement ( s) >
ELSE
<statement ( s) >
END IF

Figure 11.09 Structured English fo r the selection construct

A cond iti on consist s of at least o ne logic propositi on (see Chapter 4, Sect io n 4.01). Logic
proposit ions use th e relati onal (compariso n) operato rs shown in Table 11.03.

Operator Comparison
= ls equal to
< ls less than
> ls greater than
<= Is less than or equal to
>= ls greater than or equal to
<> ls not equal to

Table 11.03 Relational operators

Co ndit ions are eit her TRUE or FALSE. In pse ud ocod e, we distingui sh bet ween t he relational
operator= (which tests for equ ality) and t he assign ment sy mbol.-.

A person is classed as a ch ild if t hey are under 13 and as an adu lt if th ey are ove r 19. If t hey are
bet ween 13 and 19 in cl usive th ey are classed as tee nage rs. We ca n write these statem ents as
logic statem ents:

• If Age< 13 t hen perso n is a chi ld


• If Age> 19 t hen perso n is an adult
• If Age >= 13 AN D Age <= 19 t hen pe rson is a teenage r
( Chapter 11: Algorithm Design and Problem Solving

TASKll.03
A town has a bus service where passengers under the age of 12 and over the age of 60 do not
need to pay a fare. Write the logic statements for free fares.

A number- guessing game fo llows different steps dependi ng on cert ain cond itions. Here is a
description of t he algorithm:

The player inputs a number to guess the secret number stored .


If the guess was correct, output a congratulations message.
If the number in put was larger than the secret number, output message "secret num ber is
smaller".
If the number input was smalle r than the secret number, output message "secret number
is greater".
We can re-write the number-guessing game steps as an algorithm in ·structured English:

SET value for secret number


INPUT Guess
IF Guess= SecretNumber
THEN
OUTPUT "Well done. You have guessed the secret number"
I ELSE
r

IF Guess> SecretNumber
THEN

I
OUTPUT "secret number is smaller"
ELSE
OUTPUT "secret number is greater"
ENDIF
ENDIF

! More comp lex cond itions can be formed by using the logical ope rators AND, OR and NOT. For
examp le, the number-guessing game might allow the player multiple guesses; if the player
has not guessed the secret number after 10 guesses, a different message is output.

( IF Guess= SecretNumber
THEN
OUTPUT "Well done. You have guessed the secret number"
t ELSE Complex condition

IF Guess <> SecretNumber AND NumberOfGuesses 10


THEN
OUTPUT "You still have not guessed the secret number"
ELSE
IF Guess> SecretNumber
THEN
OUTPUT "The secret number is smaller"
ELSE
OUTPUT "The secret number is greater"
END IF
END IF
END IF
Cambridge International AS and A level Computer Science

WORKED EXAMPLE 11.02

Using selection constructs


The problem to be solved : Take three numbers as input and output the largest number.

There are several different methods (algorithms) to solve this problem. Here is one method:

1 Input all three numbers at the beginning.


2 Store each of the input values in a separate variable (the identifiers are shown in Table
11.04).
3 Compare the first number with the second number and then compare the bigger one
of these with the third number.
4 The bigger number of t his second comparison is output.
See Worked Example 11.03 for another so lution.

Identifier Explanation
Numberl The first number to be input
Number2 The second number to be input
Number3 The third number to be input
Table 11.04 Identifier table for biggest number problem

The algorithm can be expressed in the following pseudocode:


INPUT Numberl
INPUT Number2
INPUT Number3
IF Numberl > Number2
THEN II Numberl is bigger
IF Numberl > Number3
THEN
OUTPUT Numberl
ELSE
OUTPUT Number3
ENDIF
ELSE II Number2 is bigger
IF Number2 > Number3
THEN
OUTPUT Number2
ELSE
OUTPUT Number3
END IF
ENDIF

When an IF statement contains another IF statement, we refer to these as nested IF


statements.

Nested IF statements: condi ti ona l st atement s within condi ti onal statements


' ~ - - - - ~--

{
Chapter 11: Algorithm Design and Problem Solving

Question: 11.01
What changes do you need to make to output the smallest number?

WORKED EXAMPLE 11.03

Using selection constructs (alternative method)


The problem to be solved: Take three numbers as input and output the largest number.

This is an altern ative method to Worked Example 11.02.

1 Input t he first number and store it in BiggestSoFar


2 In put t he second number and compare it with the value in BiggestSoFar.
3 If the second number is bigger, assign its val ue to BiggestSoFar
4 In put t he third number and compare it with the va lue in BiggestSoFar
5 If the third number is bigger, assign its value to BiggestSoFar
6 The va lue stored in BiggestSoFar is output.
The id entifiers required forth is solution are shown in Table 11.05.

Identifier Explanation
BiggestSoFar Stores the biggest number input so far
NextNumber The next number to be input

Table 11.05 Identifier table for the alternative solution to the biggest number problem

The algorithm can be expressed in the following pseudocode:


INPUT BiggestSoFar
INPUT NextNumber
IF NextNumber > BiggestSoFar
THEN
BiggestSoFar (- NextNumber

ENDIF
INPUT NextNumber
IF NextNumber > BiggestSoFar
THEN
BiggestSoFar (- NextNumber
ENDIF
OUTPUT BiggestSoFar

Note t hat when we inpu t the third number in this method the second number get s
ove rwritten as it is no longer needed.

There are several advantages of using the method in Worked Example 11.03 co mpared to the
method in Worked Example 11.02:

• Only t wo variab les are used .


• The cond itional statements are not nested and do not have an ELSE part. This makes
th em eas ier to understan d.
• This algorithm can be adapted more easily if further numbers are to be compared (see
Worked Example 11.04).
The disadvantage of the method in Worked Example 11.03 compared to the method in
Wo rked Example 11.02 is that the re is more work involved with t his algorithm. If the second
number is bigger than the first number, the va lue of BiggestSoFar has to be changed . If
the third nu m ber is bigger than t he value in BiggestSoFar the n the value of BiggestSoFar

-- -- -----
Cambridge International AS and A level Computer Science

has to be changed again. Depending on the input values, this could resu lt in two extra
assignment instructions being carried out.

11.06 Loops
Look at the pseudocode algorithm in Worked Example 11.03. The two IF statements are
identical. To compare 10 numbers we would need to write this statement nine times.
Moreover, if the problem changed to having to compare, for example, 100 numbers, our
algorithm would become very tedious. If we use a repetition construct (a loop) we can avoid
writing the same lines of pseudocode over and over again .

WORKED EXAMPLE 11.04

Repetition using REPEAT ... UNTIL


The problem to be so lved : Take 10 numbers as input and output the largest number.

We need one further variable to store a counter, so that we know when we have
compared 10 numbers.

Identifier Explanation
BiggestSoFar Stores the biggest number input so far
NextNumber The next number to be input
Counter Stores how many numbers have been input so far

Table 11.06 Identifier table for the biggest number problem using REPEAT .. . UNTIL

The algorithm can be expressed in the following pseudocode:


INPUT BiggestSoFar
Counter.,_ 1
REPEAT
INPUT NextNumber
Counter.,_ Counter+ 1
IF NextNumber > BiggestSoFar
THEN
BiggestSoFar .,_ NextNumber
ENDIF
UNTIL Counter= 10
OUTPUT BiggestSoFar

Question: 11.02
What changes do you need to make to t he algorithm in Worked Example l l.04:
• to compare 100 numbers?
• to take as a first input the number of numbers to be compared?
There is another loop construct that does the counting for us: the FOR ... ENDFOR loop.
-

, Chapter 11: Algorithm Design and Problem Solving


(

WORKED EXAMPLE 11.05

Repetition using FOR ... ENDFOR


The problem to be solved: Take 10 numbers as input and output the largest number.

We can use the same identifiers as in Worked Example 11.04. Note that the purpose of
Counter has cha nged.

Identifier Explanation
BiggestSoFar Stores the biggest number input so far
NextNumber The next number to be input
Counter Counts the number of t imes round the loop

Table 11.07 Identifier table for biggest numbe r problem using a FOR loop

The algorithm can be expressed in t he following pseudocode:


INPUT BiggestSoFar
FOR Counter f--- 2 TO 10
INPUT NextNumber
IF NextNumber > BiggestSoFar
THEN
BiggestSoFar f--- NextNumber
ENDIF
END FOR


OUTPUT BiggestSoFar

Th e first time round the loop, counter is set to 2. The next time round the loop,
counter has automatically in creased to 3, and so on. The last time round the loop,
Counter has the value 10.

A rogue value is a value used to t erminate a sequence of values. The rogue va lu e is of the
sa m e data type but outside the range of normal expected vatues.

Rogue value: a value used to terminate a sequence of values

WORKED EXAMPLE 11.06

Repetition using a rogue value


The problem to be so lved: A sequence of non-zero numbers is term inated by 0. Take this
seque nce as input and o utput the largest number.

Note: In this example the rogue value chosen is 0. It is very important to choose a rogue va lue
that is of the same data type but out side the range of normal expected values. For exampte, if
the input might norma tly include Othen a negat ive va lue, such as -1, might be chosen.

Look at Worked Example 11.05. Instead of counting the numbers input, we need to check
whether the number input is Oto terminate the loop. The identifiers are shown in Table 11.08.

Identifier Explanation
BiggestSoFar Sto res the bi ut so far
NextNumber

Table 11.08 Identifier table for biggest number problem using a rogue value
Cambridge International AS and A level Computer Science

A possible pseudocode algorithm is:


INPUT BiggestSoFar
REPEAT
INPUT NextNumber
IF NextNumber > BiggestSoFar
THEN
BiggestSoFar ~ NextNumber
ENDIF
UNTIL NextNumber = 0
OUTPUT BiggestSoFar

This algorithm works even if the sequence consists of only one non -zero input. However,
it wi ll not work if the only inpu t is 0. In that case, we don't want to perform the statements
wit hi n the loop at all. We can use an alternative construct, t he WHILE ... ENDWHILE loop.
INPUT NextNumber
BiggestSoFar ~ NextNumber
WHILE NextNumber <> O II sequence terminator not encountered
INPUT NextNumber
IF NextNumber > BiggestSoFar
THEN
BiggestSoFar ~ NextNumber
ENDIF
ENDWHILE
OUTPUT BiggestSoFar

Before we enter the loop we check whet her we have a non-zero number. To make this
work for the first number, we store it in NextNumber and also in BiggestSoFar. If this
first number is zero we don't follow the instructions w ith in the loop. For a non -zero first
number th is algorithm has the same effect as the algorithm using REPEAT . .. UNTIL.

WORKED EXAMPLE 11.07

Implementing the number-guessing game with a loop


Consider th e number guessin g game aga in, this time allowing repeated guesses:
1 The player repeatedly inputs a number to guess the secret number stored.
2 If the guess is correct, the number of guesses made is out put and the game stops.
3 If the number input is larger than the secret number, the player is given the message to
input a smaller number.
4 If the number input is smaller than the secret number, the player is given the message
to input a larger number.
The algorithm is expressed in structu red English, as a flowchart and in pseudocode.

Algorithm for t he number-guessing game in structured English


SET va l ue for secret number
REPEAT the following UNTIL correct guess
INPUT guess
COMPARE guess wi th secret number
OUTPUT comment
We need variables to store the following values:
the secret number (to be set as a random number)
the number input by the player as a guess
the count of how many guesses the player has made so far.
· Chapter 11: Algorithm Design and Problem Solving
1

We represent this information in t he identifier table shown in Table ll.09.

Identifier Explanation
SecretNumber The number to be guessed
NumberOfGuesses The number of guesses the player has made
Guess The number the player has input as a guess

Table 11.09 Identifier table for number-guessing game

Algorithm for the number-guessing game as a flowchart

SET SecretNumber
to a random number

INPUT "Guess
the secret
number:"
Guess

SET NumberOfGuesses
To 1


No SET NumberOfGuesses
">-------;..i TO NumberOfGuesses
+ 1

Yes


a larger
number:" number:"
Guess Guess

"guesses"

( _ E n - d)
Cambridge International AS and A level Computer Science
'

Pseudocode for the number-guessing game with a post-condition loop

SecretNumber ~ Random
NumberOfGuesses ~ 0
REPEAT
INPUT Guess
NumberOfGuesses ~ NumberOfGuesses + 1
IF Guess> SecretNumber
THEN
the player is given the message to input a smaller number
ENDIF
IF Guess< SecretNumber
THEN
the player is given the message to input a larger number
ENDIF
UNTIL Guess= SecretNumber

Pseudocode for the number-guessing game with a pre-condition loop


Th e above solution uses a post-condition (REPEAT ... UNTIL) loop. An alternative so lution
uses a pre-cond ition (WHILE ... ENDWHILE) loop:

SecretNumber ~ Random
INPUT Guess
NumberOfGuesses ~ 1
WHILE Guess<> SecretNumber
IF Guess> SecretNumber
THEN
the player is given the message to input a smaller number
END IF
IF Guess< SecretNumber
THEN
the player is given the message to input a larger number
END IF
INPUT Guess
NumberOfGuesses ~ NumberOfGuesses + 1
ENDWHILE

WORKED EXAMPLE 11.08

· Calculating running totals and averages


The prob lem to be solved: Take 10 numbers as input and output the sum of these
numbers and the ave rage.

Identifier Explanation
RunningTotal Stores the sum of the numbers input so far
Counter How many numbers have been input
NextNumber The next number input
Average The average of the numbers input

Table 11.10 Identifier table for running total and average algorithm
i Chapter 11: Algorithm Design and Problem Solving

The following pseudocode gives a possible algorithm:


RunningTotal <- O
FOR Counter <- 1 TO 1 0
INPUT NextNumber
RunningTotal <- RunningTotal + NextNumber
ENDFOR
OUTPUT Running Tota l
Average<- Runn ingTotal I 10
OUTPUT Average

It is very impo rtant that the value sto red in Runn ingTota l is initialised to zero before we
start adding the numbers being input.

TASKll.04
Change the algorithm in Worked Example 11.08 so that the sequence 0f numbers is
terminated by a rogue value of 0.

WORKED EXAMPLE 11.09

Using nested loops


The problem to be so lved: Take as input two numbers and a symbol. Output a grid made
up entirely of the chosen symbol, with the number of rows matchi ng the first number
input and the number of columns matching the second number input.

For example the three input values 3, 7 and&, result in the output:
&&&&&&&
&&&&&&&

&&&&&&&

We need two variables to store the number of rows and the number of columns. We also need a
variab le to store the symbol. We need a counter for the rows and a counter for the columns.

Identifier Explanation
NumberOfRows Stores the number of rows of the grid
NumberOfColumns Stores the number of columns of the grid
Symbol Stores the chosen character symbol
RowCounter Counts the number of rows
ColumnCounter Counts the number of columns

Table 11.11 Identifier table for the nested loop example


INPUT NumberOfRows
INPUT NumberOfColumns
INPUT Symbol
FOR RowCounter <- 1 TO NumberOfRows
FOR ColumnCounter <- 1 TO NumberOfColumns
OUTPUT Symbol II wi thout moving to n ext li ne
END FOR
OUTPUT Newline II move to the next line
END FOR
Cambridge International AS and A level Computer Science

Each time round the outer loop (counting the number of rows) we complete the inner loop,
outputting a symbol for each count of the number of columns. Thi s type of construct is
called a nested loop.

Nested loop: loop con taining another loop

11.07 Working with arrays


WORKED EXAMPLE 11.10

Working with a one-dimensional array


The problem to be solved: Take seven numbers as input and store t~em for later use.

We could use seven separate variab les. However, if we wanted ou r algorithm to work with
70 numbers, for exa mple, then this would become very tedious. We can make use of a
data structure, known as a 'linear list' or a one-d imensiona l (lD) array.

This array is given an identifier, for example MyList, and each element with in the array
is referred to using this identifier and its position (index) within the array. For example,
MyList[4J refe rs to the fourth element in the MyList ar ray.

We can use a loop to access each array element in tu rn . If the numbers input to the
pseudocode algorithm below are 25, 34, 98, 7, 41, 19 and 5 then t he algorithm will
produce t he result in Fi gure 11.10.

FOR Index~ 1 T O 7
INPUT MyList [Index]
END FOR

Index MYList
[l] 25
[2] 34
[3] 98
[4] 7
[SJ 41
[6] 19
[7] 5

Figure 11.10 MyL ist array populated by a loop

-- -- --- -------
-
Chapter 11: Algorithm Design and Problem Solving
1

TASKll .05
Set up two arrays, one for you r friends' names and one for t heir ages as shown in Fi gure ll.ll.

Name Age

[1] Matt
.____ _ _ _____. [1] 15

[2] Fred [2] 16

(3] Anna [3] 14

[20] Xenios [20] 17

Figure 11.11 Arrays for names and ages

WORKED EXAMPLE 11.11

Searching a 1D array


Th e problem to be solved: Take a number as input. Search for this number in an existin g
1D array of seve n numbers (see Wo rked Exa mple 11.10).

St art at t he fi rst ele ment of the array and check eac h elem ent in t urn unt il the search
va lue is fo und or t he end of the array is reached . This method is ca ll ed a linear search.

Identifier Explanation
MyList Data stru cture (lD array) to store seven numbers
Max Index The number of elements in th e array
SearchValue The value to be searched for

Found TRUE if t he val ue has bee n fou nd

FALSE if th e va lue has not been fo und


Index Index of the array element currently being processed

Table 11.13 Identifier table for linear search algorithm


Cambridge International AS and A level Computer Science

Maxindex .... 7
INPUT SearchValue
Found .... FALSE
Index <-- 0
REPEAT
Index<-- Index+ 1
IF MyList[Index]= SearchValue
THEN
Found E- TRUE
ENDIF
UNTIL FOUND= TRUE OR Index>= Maxindex
IF Found= TRUE
THEN
OUTPUT "Value found at location:" Index
ELSE
OUTPUT "Value not found"
END IF

The complex condition to the REPEAT ... UNTIL loop allows us to exit the loop when
the search value is found. Using the variable Found makes the algorithm easier to
understand. Found is initialised to FALSE before entering the loop and set to TRUE if the
value is found.

If the value is not in the array, the loop terminates when Index is greater than or equa l to
Maxindex That means we have come to the end of the array. Note that using Maxindex
in the logic statement to terminate the loop makes it much easier to adapt the algorithm
when the array consists of a different number of elements. The algorithm only needs to
be changed in the first line, where Maxindex is given a value.

Linear search: checking each element of an array in turn for a requ ired value

TASKll.06
Use the algorithm in Worked Example 11.11 as a design pattern to search for a friend's name
and output their age.

WORKED EXAMPLE 11.12

Sorting elements in a lD array


Th e simplest way to sort an unordered list of values is the following method:

1 Compare the first and second values. If the first value is larger than the second value,
swap them .
2 Compare the second and th ird values. If the second value is larger than the third value,
swap them .
3 Compare the third and fourth values. If the third va lue is larger than the fourth value,
swap them.
4 Keep on comparing adjacent values, swapping them if necessary, unti l the last two
values in the list have been processed.
'
Chapter 11: Algorithm Design and Problem Solving

Fi gure 11.12 shows what happens to the values as we work down t he array, fo llowin g t his
algo rithm .
Compare Compare Compa re Compare coirpare Compare Sorted
1" Pair 2"d Pa ir 3'd Pair 4'' Pair st Pai r 6'' Pa ir list
25 No 25 25 25 25 25 25
swa p
34 34 No 34 34 34 34 34
swap
98
7
98
7
98
7
[X 7

98
swa p
7

41
7

41
7

41
41 41 41 41
>< 98
swap

X
19 19

19

5
19

5
19

5
19

5
19

5
98

5 t>< 5
'""·'"'·"'"'

Figu re 11.12 Swapping values working down the array

When we have completed the first pass t hro ugh the entire array, the largest va lue is in t he
correct position at the end of the array. The other values may or may not be in t he correct order.

We need to work t hrough t he array agai n and again . Afte r each pass t hro ugh t he array t he
next largest value wi ll be in its correct posit ion, as shown in Figure l l.13.

Original After After After After After After


list pass 1 pass 2 pass3 pass4 passs pass6


25 25 25 7 7 7 5
34 34 7 25 19
98 7 34 19 5
7 41 19 5

41 19 5

19 5

Figu re 11.13 States of the array after each pass

In effect we perfo rm a loo p w ithin a loop, a nested loop. Thi s method is kn own as a
bubble sort . The name comes from t he fac t that sma ller va lu es slow ly rise to t he top, like
bubb les in a liqu id.
Th e ident ifi ers needed fo r the algorith m are listed in Tab le l l.13.

Identifier Explanation
MyLi s t (1 .. 7 ] Data structu re (lD array) to store seven numbers
Max Inde x The number of elements in the array
n The number of elements to compare in each pass
i Counter for outer loop
j Counter for inner loop
Te mp Variable for temporary storage w hile swapping values

Tab le 11.13 Identifier table for bubble so rt algorit hm


Cambridge International AS and A level Computer Science

The algorithm in pseudocode is:

n <- Maxlndex - 1
FOR i <- 1 TO Maxlndex - 1
FOR j <- 1 TO n
IF MyList[j] > MyList[j + 1]
THEN
Temp <- MyList[j]
MyLi st[j] <- MyList[j + l]
MyList[j + 1] <- Temp
ENDIF
END FOR
n <- n - 1 II this means the next time round the inner loop, we don ' t
II look at the values already in the correct positions.
END FOR

The valu es to be sorted may already be in the correct order before the outer loop has
been through all its iterations. Look at the list of valu es in Figure 11.14. It is only slightly
different from the fi rst list we sorted.

Original After After After After After After


list pass 1 pass 2 pass3 pass4 pass 5 pass6

5 5 5 5 5 5 5


I
34 34 7 7 7 7 7

98 7 34 19 19 19 19

7 41 19 25 25 25 25

41 19 25 34 34 34 34

19 25 41 41 41 41 41

25 98 98 98 98 98 98

Figure 11.14 States of the list after each pass

After the third pass the values are all in the correct order but our algorithm will carry on
with three fu rt her passes through the array. This means we are making comparisons w hen
no further comparisons need to be made.

If we have gone through the whole of the inner loop (one pass) without swapping any
va lues, we know that the array elements must be in the correct order. We can therefore
replace the outer loop wit h a conditional loop.

We can use a variable NoMoreSwaps to store whether or not a swap has taken place
du ring the current pass. We in itialise the variable NoMoreSwaps to TRUE When w e swap a
pair of va lues we set NoMoreswaps to FALSE. At the end of the pass through the array we
can check whether a swap has take n place.
- -

, Chapter 11: Algorithm Design and Problem Solving

The identifier table for t his improved algorithm is shown in Table 11.14.

Identifier Explanation
MyList (1 .. 7] Data structure (lD array) to store seven numbers
Max Index The number of elements in the array
n The number of elements to compare in each pass
NoMoreSwaps TRUE w hen no swaps have occurred in current pass

FALSE when a swap has occurred


j Counter for inner loop
Temp Variable for temporary storage whi le swapping values

Table 11.14 Identifier table for improved bubble sort algorithm

This improved algorithm in pseudocode is:


n <- Maxindex - 1
REPEAT
NoMoreSwaps <- TRUE
FOR j <- 1 TO n
IF MyList [j] > MyList [j + l]
THEN
Temp .... MyList[j)
MyList[j] <- MyList[j + 1]
MyList[j + 1] .... Temp

END FOR
n <-
ENDIF

n - 1
UNTIL NoMoreSwaps
NoMoreSwaps <- FALSE

TRUE

Bubble sort: a sort method where adjacent pairs of values are compared and swapped

Discussion Point:
What happens if the array elements are already in the correct order?

TASKll.07
Rewrite the algorithm in Worked Example 11.12 to sort the array elements into descending order.

WORKED EXAMPLE 11.13

Working with two -dimensional arrays and nested loops


A 1D array is like a linea r li st. The nth eleme nt within the array MyList is referred to as
MyList (n].

A two -dimensional (2D) array is like a table or matrix. The element in row x and co lumn y
of ThisTable is referred to as ThisTable [x, yl.

For example to store the va lue 5 in the element in the fo urth row and second co lu mn, we write:

This Table [ 4, 2] .... 5


Cambridge International AS and A level Computer Science

When we want to access each element of a 1D array, we use a loop to access each element
in tu rn. When working w it h a 2D array, we need a loop to access each row. With in each row
we need to access each column. This means we use a loop within a loop (nested loops).

In structured English our algorithm is:


For each row
For each column
Assign the initial v alue to the element at the current position

We need th e identifiers shown in Table 11.15.

Identifier Explanation
ThisTable[l .. 4, 1 .. 6] Table data structure (2 D array) to store values
MaxRows The number of rows in the table (4 in this example)
MaxColumns The number of columns in the table (6 in this example)
Row Counter for the row index
Column Counter for the column index

Table 11.15 Identifier table for working with a table

Using pseudocode, the algorith m to set eac h element of array ThisTable to zero is:

FOR Row~ 1 TO MaxRows


FOR Column~ 1 TO MaxColumns
ThisTable[Row, Column] ~ O
END FOR
END FOR

When we want to output the contents of a 2D array, we aga in need nested loops. We want
to output all t he va lues in one row of th e array on the same line. At t he end of the row, we
wa nt to output a new line.

FOR Row~ 1 TO MaxRows


FOR Column~ 1 TO MaxColumns
OUTPUT ThisTable[Row, Column] II stay on same line
END FOR
OUTPUT Newline II move to next line for next row
END FOR

An algorithm is a sequence of steps that can be carried out to solve a problem.

• Algorithms are expressed using the four basic constructs of assignment, sequence, selection and
repetition.

• Algorithms can be documented using structured English, pseudocode or a program flowchart.

• Logic statements use the relational operators=, <, >, <>, <=and>= and the logic operators AND,
OR and NOT.

Selection constructs and conditional loops use conditions to determine the steps to be followed .
. Chapter 11: Algorithm Design and Problem Solving

Exam-style Questions
1 The Modulo-11 method of calcu lati ng a check digit for a sequence of nin e digits is as fo llows:

Ea ch digit in the sequence is given a weight depending on its position in the sequence . Th e leftmost digit has a weight of 10.
The next digit to the ri ght has a we ight of 9, th e next one 8 and so on . Va lu es are calculated by multip lying each digit by its
weight. These va lues are added together and th e sum is divi ded by 11. The rema inder from th is division is subtracted from 11
and t his va lue is the check digit. If this va lu e is 10, th en th e check digit is X. Note th at x MOD y gives th e remainder from the
division of x by y.

Comp lete the flowchart using t he stateme nts in the table.

Start

Statement Statement
number
1
2
3
4
5
CheckDigit +- 1 1
CheckDigit +- X
CheckDi git
Count +-1
Count +- Count + 1
=
-

10 ?
Remainder


6 Count = 9 ?

7 INPUT Digit
8 Remainder +- Total MOD 11
No
9 Total +- 0
10 Total +- Tota l + Va l ue

11 Value +- Digit * Weight i ng


12 Weight i ng +- Weigh ting - 1
13 Weighting +-10

(~E-nd___,)
[9]
Cambridge International AS and A level Computer Science

2 Draw a flowc hart for t he foll owi ng pro blem given in structure d En gli sh.

REPEAT the following UNTIL the number i nput is zero


INPUT a number
Check whether number is positive or negative
Increment positive number count if the number is positive
Increment negative number count if the number is negative [7)

3 Wri te pseud ocode from t he given flowchart. Use a WHILE loo p.

(_~start_)

i
RogueValue ... -1

Total<- O

Co unt <- 0

• Input Number

Count ... Count+ 1 Average<- Total I Count

Total ... Total+ Number OUTPUT Av erage

INPUT Number

( __
End~)
[BJ
- - --- - - - ~ ~ - -~- -

0
_ Chapter 11: Algorithm Design and Problem Solving

4 Ala n uses two lD arrays, UserList and Password Li st. Fo r twen t y users, he sto res each user
ID in UserList and the correspond ing password in Password List. For exam ple, the person
wi t h use r ID Fredl 2 has password rzt4 56.

UserList PasswordList

[ 1] Mattos [1] pqklmn4

[ 2] Fred12 [2] rzt456

[3] Anna9 [3 ] j edd321

[20] Xenios4 [2 0 ] wkl @tmp6

Alan wants to write an algorithm to check whet her a user ID and password, entered by a user,
are co rrect. He designs the algorithm to search u s erLi s t for the user ID. If t he user ID is
fo und, t he passwo rd stored in Pass wordL ist is to be compa red to t he ente red password. If
t he passwords match, t he login is successfu l. In all ot her cases, login is uns uccessfu l.

a Complete the identifier ta ble. [4]

Identifier Expla nation


UserList (1 .. 2 0 ] 1D array to sto re user IDs
... .. . . . .. . . .... . . . . .. .. .... ..... ... . .... .... .. . .. .. 1D array to st ore passwo rds
Max Ind ex Num ber of elem ents in each array
MyUs erID User ID ent ered to log in
MyPass word .. . .. . . . .. .. .. .. . .. . . .... .. .
UseridFound FALSE if user ID not found in
Use r Li st
TRUE if . . . .. . . . . . .. . . . . . . . .
LoginOK FALSE if . . . . . . . . . . .. .. . . . . .
TRUE if . . . ' ..... ' ... . .. . ...
Index Pointer to curre nt array elemen t
.
Cambridge International AS and A level Computer Science

b Complete the pseudocode for Alan 's algorithm:


Maxinde x <- 20
INPUT MyUserID
INPUT MyPassword
UseridFound <- FALSE
LoginOK <-
Index<- 0
REPEAT
INDEX <- ... ........ .. . .
IF UserList [ ............ ... )
THEN
UseridFound <- TRUE
END IF
UNTIL ........ . . ..... OR
IF UseridFound = TRUE
THEN
IF Pass wordList [. .............. )
THEN
LoginOK <- TRUE

END IF
IF . .... .. ..... . . .
THEN
OUTPUT "Log in successful"
ELSE
OUTPUT "User ID and/or password incorrect "
ENDIF [10]

You might also like