Computer Science Coursebook-132-161
Computer Science Coursebook-132-161
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 :
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
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:
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
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.
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
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
Set A to 34
Increment B
UNTIL A= B
,
'
Input INPUT A INPUT "Prompt: 11 A
t
,,
~
INPUT "Prompt : " A
OUTPUT B t
• OUTPUT "Message" B
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.
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
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)).
Number
(a) (b)
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)
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)
The value in valuel remains the same until it is assigned a different value.
---------
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)).
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
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.
Km - Miles* 1 .6 1
End
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
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
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
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:
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:
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
There are several different methods (algorithms) to solve this problem. Here is one method:
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
{
Chapter 11: Algorithm Design and Problem Solving
Question: 11.01
What changes do you need to make to output the smallest number?
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
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:
-- -- -----
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 .
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
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.
-
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
•
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.
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
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.
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
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
'
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
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
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
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.
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
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.
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
-- -- --- -------
-
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
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
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.
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
'""·'"'·"'"'
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.
•
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
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
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.
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
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.
- -
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
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.
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:
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).
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
Using pseudocode, the algorith m to set eac h element of array ThisTable to zero is:
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.
• Algorithms are expressed using the four basic constructs of assignment, sequence, selection and
repetition.
• 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.
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
(~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.
(_~start_)
i
RogueValue ... -1
Total<- O
Co unt <- 0
• Input Number
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
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.
•
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
END IF
IF . .... .. ..... . . .
THEN
OUTPUT "Log in successful"
ELSE
OUTPUT "User ID and/or password incorrect "
ENDIF [10]