0 ratings 0% found this document useful (0 votes) 81 views 29 pages Ch4-Algorithms and Flowcharts
This document introduces algorithms and flowcharts as essential tools for programming, explaining how algorithms are step-by-step instructions that a computer can follow. It covers the representation of algorithms through pseudocode and flowcharts, detailing the symbols used and the processes involved in input and output. Additionally, it discusses mathematical operations and selection statements in algorithms, emphasizing the importance of structured programming.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Ch4-Algorithms and flowcharts For Later ae of instructions for Some,
Do you have experience of folowing Inst
follow? has Scratch, OF of controlling 3
languages $¥°
+ Do youhave any experience of block programming I" 9)
turtle on sereen such as through Logo?
Introduction 4
In this chapter you will learn how to develop algorithms eT
to solve problems in a form that a computer ‘could |_| +
follow. All computer programs are simply a series of
algorithms that are written in a specific way that the
computer's processor can then follow one at a time. Ei
4.1 Algorithms
An algorithm is a series of steps that are followed
‘You follow lots of algorithms without even realising
it, for example, following a recipe or following a list of
Figure 4.1: Maze 1, start
you would need to follow thes se
To get to ‘Finis!
instructions. These are both examples of algorithms . a
Before you write algorithms on a computer, you can Step: FD7 Step 5: FD?
eer vm using a flowchart and/or using pseudocode. Step2: RT9O Step 6: RT90
Peeudocode simply means there is no specific symtax that Gey, DG Step: FDI
you have to use. It doesn’t have to follow a set format,
Step 4: LT90
‘but it is more structured than English sentences.
WORKED EXAMPLE 4.01
flowchart: a set of symbols put together with You are on Start, faci
commands that are followed to solve a problem Facing to the right.
Write an algorithm to move from Start to Finish
pseudocode: a language that is used to display
‘an algorithm =H
{A simple form of an algorithm is a series of steps to
move someone (or something) through a maze. The
instructions you can use are:
FDS Move forward 5 spaces
BK2 Move backward 2 spaces
Stn
RT9O Turn right 90 degrees
LT90 Turn left 90 degrees Figwe 4.2: Mi
jure 4.2: Maze 2
You startin the space labelled ‘Start’ in this maze, faci
to the right. mens
[Eee
Scanned with CamScanner4. Algorithms and flowcharts
facing to the right so need to count how many
You need to face to the right again, so:
grey spaces there are until you need to turn. There are
4 spaces, so the command is: RT90
FD4 To the next turn is 3 spaces:
FD3
=a
Figure 4.
Maze 2, FDS,
Figure 4.5: Maze 2, £04, L790, FD2, R190, FO3
You need to tum so you are facing up, this means
turing to the left, 90 degrees. The command is You need to face up, so you are turning left again:
1790 1790
How many spaces forward? 2 ‘Now you need to move forward 5 spaces:
FD2 Be
Fe] [rnen] a
Son San
Figure 4.4:
faze 2, FD4, LT90, FD2. Figure 4.6: Maze 2, FD4, LT90, FD2, RT90, FD3, LT90, FOS.
BP ae
Scanned with CamScannerthe al,
gorithm becomes;
FD4, LT9\
0, FD2, RT90, FD3, 1190, FDS, LT90, FD7
Questions
1 What is meant by an algorithm?
2 How can an algorithm be represented?
Lt Neuer NW Xe UI NOG
Write an algorithm
to move from Start to Finish
in this maze:
stan
=
Maze 3, Start
er
4.2 Flowcharts and
pseudocode
A flowchart is a diagram that uses
arrows to produce an
SPecifi;
algorithm that song %*>
then follow,
At Someone. Md
Pseudocode does not use s
statements. There is no
must follow, but it shoul
diagrams) such as INPUT, OU"
Ymbols, but struc,
Flowchart structure
[hte are set symbols throughout a flowchart
Peintroduced to these in each section: Every fj
begins and ends with a terminator
box (a Star
the beginning and a Stop box at the end),
w Tine, When following a flowchat
Algorithms don’t go straight
Y also need input, output
id loops,
ws,
from start to stop. The
Processes, decisions an
input: putting data into an algorithm
output: dis
to the user
Playing data from an algorithm
Process: an
0
action performed to some data
make a char
inge
decision: a com
iteod?
Parison is used to decide if
is run, or not
loop: code that is repeated
Scanned with CamScanner4 Algorithms and flowcharts
Input and output
Alponthms often need to output messages (such as text)
to the screen. and therefore to the user. They may also
need to take in data from the user, for example from
the keyboard.
Flowcharts
If you want the algorithm to output something to the
user. for example a word, a sentence or a number, then
you will need an output box.
Mer the word OUTPUT you put the text you want
to display. If you want to output “Hello World",
you use this,
Figure 4,11: Output box wth tert
Notice how the words being output are in speceh
marks This is because you want those actual words
‘output, without them “Hello” could be a variable, or
command word,
no
Af you want to input (or tead) data from the user
the alonthm, you use an input box
a
Figure 4.12: input box
When data is input into an algorithm it needs to be
Mored somewhere. This ts done using a variable, A
Vanable is a name (identifier) that ts given to a space in a
sompater’s memory that stores a value. Think of it like
a box, with a name, You could call the box ry
You can then put data into cySurber. You can get data
OU Of sytunbex, and so on
a space in the memory of a computer,
that has an identifier where you can store data;
this data can be changed
identifier: the name given to a variable,
subroutine or function
concatenate: to join two strings together
Here’s the symbol for inputting a value into mytiunber.
box woth identifier
Figure 4.13: Ins
these together with the Start and Stop to create a
chart
Figure 4.14: Flow
ant *Hello World
Once you have a variable, you can output this by
using its name
| ort mparee |
Figure 4.15: Output box with enter
You might want to output a variable and some text. You
can combine them by using an ampersand (4). This 1 to
concatenate (join) the values together. For example,
>
Scanned with CamScannerSUTPUT "He110 worian
The words "Hello Wortan are a string as in the
fowcharts, so are stil Speech marks. There are many
aitferent words that you see Use to output data, but they
all Perform the task, for example all of these have the
same result,
OUTPUT *He1io»
WRITE "Helio
PRINT "Hello
weharts, this will need to be
Stored somewhere such as in.a Variable, for example,
or you could combine the input and ‘output, for example,
num =
INPUT("Enter a number")
An algorithm needs to ask a user to enter their
ame. It should take their name as an input and then
Welcome them by name, for example, "Welcome
Sasha",
Draw a flowchart for the algorithm,
Start by identifying the steps required,
Step 1: Ask them to enter their name,
Step 2: Take their name as input,
Step 3: Welcome them by their name.
Then identify what type of symbols these steps need,
Step
Ask them to enter their name.
Output
: COURSEBOOK
Step 2: Take their name as input,
Input and store in variable
Step Welcome them by their name,
Output including variable
Draw the lowchart following the steps iden,
OUTPUT “Welcome
name
Figure 4.17: Flowchart- Welcomes,
i
Convert the flowchart into pseudocode,
Take each statement from within the flowchart!
write it on its own fine,
OUTPUT “Enter your name"
INPUT name
OUTPUT “Welcome” & name
ie eS
Questions
3 Adentify the symbol for Start and Stop in?
flowchart.
4 Describe the stages in this flowchart.
Scanned with CamScannerFigure 4.18: Flowchan-Enter a number.
Raneule Ween
1 Convert the flowchart in Question 4 into
pseudocode.
2 Analgorithm needs to take @ word as an
input, and then output the same word.
Draw a flowchart for this algorithm,
4n algorithm needs to tell a joke. It should
output the joke, and let the user give an
answer, before outputting the actual answer.
Create a pseudocode algorithm for the
problem.
Processes
A process is an action that is performed. In a program
itusually means that a change is being made to
something. If you have a number stored in a variable,
you could change this; you might add something to it,
or subtract from it.
4 Algorithms and flowcharts
‘There are different types of processes
Table 4.1 shows the different mathematical provestes
that be performed.
‘Operator | Description
+ [Addition
= [Subtraction
Multiplication
Division
Power of
MOD | Modulus
division (gives
the remainder)
Div [integer
division (gives
the whole
number)
Table 4.1: Mathematical (arithmetic) operators.
modulus division: when the remainder is given |
from a division
integer division: where only the whole number is
given from a division
Flowcharts
Processes are in rectangular boxes.
Process
Figure 4.1
Process box.
RET TIN YT}
59
Scanned with CamScanner> CAMBRIDGE INTERNATIONAL AS & A LEVEL IT: COURSEBOOK
The mathematical calcula
numbers, and/or y;
myNumber = 19
Hons can make use of
‘ariables. For example,
ie myNumber now stores 13
myNumber now stores 16
(it already had 13 in and
“Number = myNumber 4 3
now has another 3)
Phytecker M™mber
32 (it already had 16 in
it, and it was added to
itself, so 16 + 16 = 32)
Putting a value into
@ variable is called assignment
KEY WORD.
@ssignment: giving a variable a value
In this process box two
and stored in a variable,
numbers are multiplied together
newNumber = 3 * 8
igure 4.20: Assignment in process by
Follow this flowchart. What does it do?
Answer = numt /num2
OUTPUT The esut
Is" & answer
Figure 4.21: Flowchart-Arithmetic calculation
Notice that anew symbol has been introgyg
circle with a letter inside. This isa connect
Sometimes if a owehart is long, then i
to split it into smaller portions (pert
on one page). The connector letter
flowchart continues.
haps to
Shows wien
The algorithm takes in two numbers (aug,
divides numa by num2 and stores the resul, ine
W then outputs the message * The result ign” =
value in answer, Ye
Pseudocode
Processes use the same structure as in
a flowe!,
without the box. Therefore this:
newNumber = 3 *
would become this:
ewNumber = 3 + g
A program needs to ask a person’s age, then tellite
how old they will be in 50 years,
Draw a flowchart for the algorithm,
Start by identifying the steps required.
Step 1: Ask them to enter their age,
Step2: Take the age as input
Step 3: Add 50 to their age.
Step 4: Output the new age.
Identify what type of symbols these steps nest:
Step 1: Ask them to enter their age.
Output
Step2: Take the age as input.
Anput and store in a variable
Step3: Add 50 to their age. .
Add 50 10 the variable and store the
Step 4: Output their new age.
Output variable
a
Scanned with CamScanner|
|
|
|
4 Algorithms and flowcharts
the flow
+
Dr steps ide
rentge = gn +50
paeee
eercserd
5
Figure 4.23: Flowchart-New age calculator.
SS
Convert the flowchart into pseudocode.
Take each line and write it on a separate line.
ourPUT “Enter you age"
wT age
newkge = age + 50
OUTPUT "In 50 years your will be" & newAge
Co
Questions
5
6
7
8
What is a process?
What action does the operator * process?
Write a statement to multiply 3 by 7,
Describe the stages in this flowchart
[OUTPUT amt =
rane
peeseeee Seana
Convert the algorithm in Question 8 into
pseudocode.
2 Analgorithm needs to take 3 numbers as
input. Add them together and output the
result. Then divide the total by the quantity
of numbers and output the average.
Draw a flowchart for this algorithm.
3 Convert your algorithm from part 2 into
pseudocode.
Scanned with CamScanner> cAmanioge INTERNATIONAL AS & A LEVEL IT: COURSEBOOK
Flowcharts
Single selection
the form of
‘The selection must be int 8 ques:
example ‘is 10 > 5? This is because it has ty. >
true and false. i
The selection flowchart symbol i a diamon,
Selection: use of 3 conditional statement to
decide @ course of action or which section of
code to run
Figure 4.25: Selection box,
$$
There are two options from a selection bon
and False, or Yes and No. This means select
. Pe TONS (two flow lines), that need to bs
‘ comparison needs two sides : for example
2 comparison symbol. Table 4. shows common "
Yes
Greater‘than
10 > Sistrue
No
S$ > 10is false
10 < Sis false
“Slre 4.26: Selection box with options
aes
$< l0istrue
Follow this flowchart, What does it do?
Greater than Sis true
or equal to ; a)
4 10 >= lois true ar
S >= 10is false
less hove pois eatse | PUT age
Less thanor |i0 <= Sis false
equal to
4 10 <= lois true
3 <= l0istrue CuTPuTsmuendt
Equalsto [10 = Sistaise
10 = 20is true
10s false
Not equal to
5 <> l0istrue
a
Table 4.2: Comparison operators.
: Le
Either side of the operator can be a number or
a variable.
chart with selection poxree
Scanned with CamScanner‘This flowchart starts by the user inputting an age, The
decision statement asks if age is greater than, or equal
to, 18. If the result is Yes, then it outputs “You are old
enough”. if it is No it outputs “You are too young”.
Multiple selection
If you have multiple options, then you will need multiple
decisions. For example,
lowchart with multiple selection boxes.
The first decision is “If age is less than 107" If itis not,
then it goes straight to another decision, and asks
whether age is less than 20,
Pseudocode
Selection uses the keyword IF and THEN. The questi
“Is'in the flowchart is replaced with TF, and the “? with
THEN, All the code that runs when the condition is true
goes beneath the TF and this is finished with an ENDIF
to show where it ends.
For example, if the value in age is more than 18, then
the output message will be displayed.
IF age > 18 THEN
ouTPUT("You are old enough")
ENDIF
An TF statement can have an ELSE. This is what happens
if the condition is true. For example, if the age is not
more than 18, then * You are not old enough” will be
displayed.
IF age > 18 THEN
OUTPUT("You are old enough")
ELSE
OUTPUT("You are not old enough")
ENDIF
4 Algorithms and flowcharts
Multiple conditions
These can be created using ELSETF statements. Each
condition has its own ELSETF. You can even put an
ELSE on the end in case none of the conditions are
true. For example, each of the conditions are checked
in the order they are written. If one of the conditions is,
found to be true, then the code within it runs, and thea
it jumps to the ENDIF; the other conditions after it are
not checked.
IF cost >= 100 THEN
OUTPUT "That is far too expensive"
ELSEIF cost >= 80 THEN
OUTPUT “That's a bit too expensive"
ELSEIF cost >= 60 THEN
OUTPUT "That is reasonable"
ELSEIF cost >= 40 THEN
OUTPUT “That looks like a good deal"
ELSE
OUTPUT "I think that is too cheap"
ENDIF
CASE...END CASE
This is a different selection statement. This is used when
you are checking the value of one variable and you have
many different values you want to check it against.
Pseudocode
CASE uses the keyword SeLEcT, followed by the
identifier of the variable you are checking. Then it has
the keyword CASE followed by the condition.
For example, if you are checking if a menu choice is
1.2013:
SELECT menuChoice
CASE 1: OUTPUT “You chose 1”
CASE 2: OUTPUT "You chose 2"
CASE 3: OUTPUT "You chose 3"
A CASE statement can perform comparisons other than
equals to, but this time you need to include the variable
name to make it clear what the comparison is.
SELECT age
CASE age < 12: OUTPUT "You can watch PG
films"
CASE (age >= 12 and age < 15): OUTPUT “You
can watch PG and PG12 films"
CASE (age >= 15 and age < 18): OUTPUT “You
can watch PG, PG12 and 15 rated films’
Scanned with CamScannera
>
+ OUTPUT "You can watch all
ea also a default keyword for CASE, the code in
NI run if none of the conditions have been met.
SELECT symbol
CASE "40,
result = valuel + value2
An algorithm needs to take two numbers as input, and
output which is the largest.
Draw a flowchart for the algorithm,
Start by identifying the steps required.
Step 1: Ask the user to input two numbers,
Step 2: Input two numbers,
Step 3: Check if the first number is larger than the
second.
Step 4: Output the first number if itis.
Step 5: Output the second number if it isn't.
Identify what type of symbols these steps need.
Step 1: Ask the user to input two numbers
Output
Step 2: Input two numbers.
Input the store ina variable
Step 3: Check if the first number is larger than the
second.
If first > second
Output the first number if itis.
Output first number
Step 4:
CAMBRIDGE INTERNATIONAL AS & A LEVEL IT: COURSEBOOK
case *
result = valuel ~ vaiues
CASE "#":
result = valuel * values
CASE "/":
result = valuel / value2
CASE DEFAULT:
OUTPUT "Invalid symbo1"
Step S: Output the second number if it js
Output second number
Yes
‘scum
FTPUT nun
uma? our
No
| cureurmina
eeemee eeee
Figure 4.29: Flowchart-Compare two numbers.
Figure 4.29: Flowchart-Compare two numbers
Bs
Scanned with CamScannerConvert the flowchart into pseudocode.
Write each line separately. Only one value can be input
atatime
Replace Is with an IF statement.
oorPuT "Enter two nunbers
INPUT nun
INPUT nun2
YP mum) > mum? THEN
ourpuT num
ELSE
ourPUT nunz
ENDIF
Questions
9 How many arrows must come out of a selection
symbol in a flowchart?
10 Define selection.
11 13956 >= 8567
12 Is 123 != 123?
13 = 662
Piteron Wa cnUEnacnes?
Describe the stages in the flowchart opposite.
Convert the flowchart in part 1 into
pseudocode.
An algorithm needs to take three numbers
3s input, and output the smallest.
Draw a flowchart for this algorithm.
Convert your flowchart {rom part 3 into
pseudocode.
An algorithm needs to take two numbers
as input, then subtract the smallest from
the largest.
Create a pseudocode algorithm for the
problem using an IF statement.
Replace the IF statement in task 5 with a
SELECT CASE statement.
4. Algorithme and flowcharts
CONTINUED
(OUTPUT Ex
OUTPUT Morr
Figure 4,30: Flovichart with comments,
Loops
‘A loop means repetition: doing the same thing several
times. Its technical term is iteration,
iteration: a loop to repeat a section of code
for a fixed number of times or until a required
‘outcome is achieved
Re ET
6 >
——
Scanned with CamScannerE90 are mainly used in two scenarios
6 ie ee You want to repeat the
SOUS. THis might be 10 times or sec uimecahore
Court Variable that stores a valug), This ine
count-controlled loo
2
Nou don’t know the number of times, but want
to keep go)
'g until something happens. Thi
trolled loop,
isa
condition-coy
the mcontrolled loop: a loop where you know.
the number of times it will ros
Count controlled
Flowcharts
number of repetiti
loops). The counter will be a v:
the loop, the counter needs to
(usually 0 or 1). Then inside t
Reed to increment the counte
(the number of
‘ariable. Before you start
fhe code that loops, you
(this means add 1 to it),
be set to the starting value
Pseudocode
A.roR lonp is a count-controlled loo
know what number to start with, a
The loop increments the number ¢;
OU ne
ind whey yt
ACH time |
Ou
increment: add 1 to something a
FOR loop: a count-controlled loop
ae
In this example, the variable counter start dant
continues until itis 9.
FOR counter = 0 to $
OUTPUT counter
NEXT counter
An algorithm needs
marks of its student:
Draw
to ask the user to inp:
sand then output the
flowchart for the algorithm,
Start by identifying the steps required.
Step: Repeat 10 times
Step2: Ask the user to input a mark.
Step 3:
Input the mark.
Step4: Add the mark to a total
Step: Afterall the marks are entered, cl
[om ] the average,
Sten6: Ourput the average.
. Kdentify what type of symbols these steps need
Loop 10 times
7 Step2: Ask the user to input a mack
Step3 Input the mark.
‘igure 4.31: Flowchart with counter. me
priate. -3t Clocio ——_ Input and store in variable
In his example, the counter variables num. numisset 4g | Step: Add the mark to a total
Start at 0. Following the arrows, it keeps increasing ty Add input t0 total seu
until num is greater than 5, at which point the alge BOP AS saat oe etd,
stops average. Total divided by 10
Step 6;
Output the average.
Output
R
Scanned with CamScanner4 Algorithms and flowcharts
| curpur “emer
I
|]
Figure 4.32: Flowchart-Caleulating average.
else se ata)
Convert the flowchart into pseudocode.
Write each line separately. Replace the count and
selection with a FoR loop.
FOR count
0 7010
“Enter a mark"
ovr:
INPUT mark
total = total + mark
EXT count
verage = total / 10
OUTPUT average
Questions
14 Whats iteration?
15. What is a count-controlled loop?
16 When is it appropriate to use a count-
controlled loop?
17, What three elements do you need in a count-
controlled loop?
Ta
ew Nenad
1 Describe the stages in this flowchart
(OUTPUT counter
2 Convert the flowchart from part 1 into
pseudocode,
3 Analgorithm needs to output the 12-times
table using iteration.
Create a flowchart for the algorithm.
4 An algorithm needs to ask the user how
many numbers to output. The algorithm
should then print out the numbers from 1 to
that number input.
Create a pseudocode algorithm for
the problem.
Condition controlled
A condition-controlled loop has the same structure as
a count-controlled loop, but it doesn't need a counting
variable, because something else is controlling it. This
could be controlled by an input from the user (you could
Joop untit itis a valid input), or until a specific number
is greater than another.
Flowehart
‘The flowchart looks similar to a count controlled due
to the condition, but it would be missing the variable
counter and does not run a set number of times.
22)
BO ee ee
>
Scanned with CamScannerure
Flowchart with condition-contrlled loop 1
The following flowchart isan
UNTIL loop. This is a type of
The code inside the loop will
the condition is at the end of
alue * 2 repeats until
-——
value = value * 2
example of a REPEAT
condition controlled loop.
always run once because
the code. So the statement
i the value is >= 109,
I
No
Figure 4.35: Flovichart with concltion-controlled loop 2
in this examp! keeps on going until the number
is example, the loop keeps on going until mi
i is variable value is greater than or equal 10 100,
in
> CAMBRIDGE INTERNATIONAL AS & A LEVEL IT: COURSEBOOK
Pseudocode
Joop is a condition-co;
the condition is 4,
ntrolle
rug, op
REPEAT UNTIL loop: a condition
I “cont
that runs until the condition is try
le
WHILE loop: a condition-
controlled jo,
runs while the condition i
is true
In this example the looy
enters an age greater th
age = 0
P will continue unti}
han or equal to 18,
Use
WHILE age < 18
INPUT age
ENDWHILE,
In this example, the loo;
greater than 100,
value = 2
P Continues until loo»
WHILE value <= 199
value = value + value
ENDWHILE,
An algorithm needs to continually ask the Pe
input numbers, and add them to a total, untit
'S more than 100, then output the total
Draw a flowchart for the algorithm,
Start by identifying the steps required.
Step 1s Repeat until the total is more tha!
Step2: Ask the user to input a number.
Step3: Input the number,
Step: Add the number to the total. }
Step S: When total is more than 100, out?
total, fi
Tdentify what type of symbols these stePs mot
Step 1: Repeat until the total is more tht?
Loop untit total > 100
_d
Scanned with CamScanner4 Algorithms and flowcharts
LD vestion
48 When should a condition-controlled loop be used?
step 2: 8 umber.
step2: Ask the user to input a nur
Dutput
eur —s PRACTICAL ACTIVITY 4.04
step 3: Input the number.
eng 1 Describe the stages this flowchart follows.
Step4: Add the number to the total
Process ~ add number total
Step S: When total is more than 100, output the waewe
total
Output ——
= cone |,
<0
‘OUTPUT Enera
total = total + number oH
Figure 4.37: Flowchart with control loop.
lowchar-Totalling number with control
nes 2 Convert the flowchart into pseudocode.
3 Analgorithm needs to ask the user to
input a number between 100 and 200.
Keep asking the user for the number until
Convert the flowchart into pseudocode. Draw a flowchart for the algorithm
Replace the selection condition with a wire loop. 4 Analgorithm stores a number. The user
hhas to guess what this number is. They
total = 0 i
keep guessing until they get it correct.
MAILE total < 100 The algorithm then outputs the number of
ourpur “Enter a number" guesses the user took.
mur nunber
total teed + munber Write a pseudocode algorithm for
this problem.
ENDWHILE
ourrur total
6 )
Scanned with CamScanner> CAMBRIDGE INTERNATIONAL AS & A LEVEL IT: COURSEBOOK
String Manipulation
Strings are col
Hections of ter ra d
Pumbers The ters, characters ani
are represented by tech marks, this
is bee; i NY spe s
Word -yat the Variable vaiue incites” from the
You may need
to manipula
one or m: ulate strings, for example get
Command [Dalai ISA
length(string)
Returns the | length("Hello"
In this example. the four diits of the ye.
extracted from the string and outpyy °°! (1,
san
rt
length of the | would gives Figure 4.38: Flowchart to extract yeer fom »
string pseudocode.
char(string, Returns the char("Hello®, 0) The a:
Hi ‘ }€ statements are the same seudocode,
ttt Ca pees give »H» coc
characterNum
in the string
mid(string, Returns mid("Hello",1,2)
peeoderoes anumchars | |woiltavetal
numChars) or | number of
| substring(string, | characters
| startingChar, from
| numChars) startingChar
in the string
————
upperstring) | Converts upper("Hello|
string to would give
capitals "HELLO*
lower(string) converts lower("Hellon)
string to would give
lowercase hellon
ee tien
able 4.3: String manipulators
written without the boxes.
A program is needed to input a word fro:
and then output alternate letters starting ws =
letter.
Draw a flowchart for the algorithm,
Start by identifying the steps requires.
Step i: As
the user to input a word.
Step 2: Input a word and store it ina var
Step 3: Count the number of lette
Step: Seta counter to start with the let
Position 0,
Step 8: Increase the counter by 2 each ti
the loop.
Step 6 Output the letter of the counter it :
, ic oreater ths?”
Step 7 Loop until the counter is greate™
equal to the number of letters
aah
Scanned with CamScannerdentify what type of symbols these steps need.
step 1: Ask the user to input a word.
Output
Step2: Input a word and store it in a variable,
Input and store in a variable
Step 3: Count the number of letters in the word.
Find length of the word
Step 4: Set a counter to start with letter 0.
Process set counter to be 0
‘Step $: Increase the counter by 2 each time through.
the loop.
Process, counter = counter +2
Step 6: Output the letter of the counter in the loop.
Get mid at position counter
Step 7: Loop until the counter is greater than the
number of letters.
Loop until counter > length
‘OUTPUT “Enea
wordLength = lengtvord)
‘ourPut
iwordhength count
counter = counar + 2
Figure 4.39: Flowchart with mid command
l TS
Le
4 Algs
ms and flowcharts
Pvoncocuuree
nvert the lowehart into pseudocod
oop with a FOR loop ({rom 0 to wordlength) but it
needs to add 2 each time.
ovTPuT “Enter a word"
INPUT word
wordLength = Length (word)
FOR counter = 0 TO wordbength
OUTPUT mid(wordLength, count:
ae
counter = counter + 1
NEXT counter
Question
19 Wha
number is the first character in a string?
eUeNW Aes
\ViTY 4.07
1 Describe the stages in the flowchart in
Figure 4.40.
2. Analgorithm is needed to ask the user
how many letters they want to enter. The
program should then ask the user to enter
that many letters, concatenate them and
output the result.
Draw a flowchart for the algorithm.
‘An algorithm takes the date of a month a
user was born, the name of the month, and
the year. It creates a date of birth in the form
DD/MMIYYYY and outputs this.
Create a pseudocode algorithm for
the problem.
n>
Scanned with CamScannerSubroutines
A subroutine i set of inst
They have an identier (2
other pacts ofthe
‘control passes
Tuctions that a
‘ame
rogram, Wh
back 10 where it
hat called it,
ye program t in
tothe pr -
control back (oto the program that call:
Im 3 Mew about fUNCTIONS. OF Use t
1 subroutine.
ca ret
not need 10)
b
chaptet
not the om
at itis
ly form of
dure: a type of subroutine that c
wocedure: 8
Porn a value to the main program
= of code the
tnetn a separate ite of cade
tifier and performs a task;
SGtvalsenherein the code and returns
Flowcharts
Each subroutine is a separate fowehart, anc
having a Start box, it has the name of the s.
forexample,
Figure 4.41: Subroutine identifi
ne
Natit sample, the subroutine is called OuiputTen
Note that the symbot
for a subroutine is similar toa
Pach PO but has © pair of parallel ‘vertical lines
Taide. The algoritnm stare at Start, the proses!
ring oe LQNEHO to £0 19 Outpa e output “He
cil the algorithm to go back to te
where it runs Stop,
OUTPUT eto:
GD
Figure 44
eae e lowchay
7g utruting
Scanned with CamScanner4 Algorithms and flowcharts
Pseudocode ay a
In pseudocode, a subroutine still has an identifier. I C — = “
th the command PROCEDURE and ends with,
starts |
ERDPROCEDURE
In this example, the procedure is called a . toto ttl
qutpursersage(). The brackets identify it asa sl alae we
Sproutine. The procedure outputs the words "e110 L—__
world" and then returns control, |
PROCEDURE outputMessage()
OUTPUT “Hello World" sw Pay,
catutsinerten /
|NDPROCEDURE
A procedure is called by using the name of the
procedure, for example,
INPUT x
cutputtieosage()
cuTPUT "Finished"
Procedures are declared at the top of the program, and (maaan)
the main program beneath all the function calls. : Sen SS
Parameters t—— \
You can send data to a subroutine; this data is called a
parameter. INPUT number
parameter: a piece of data that is sent toa
subroutine ‘oun | curruriest
/
cextevate(ourber) L /
Flowchart
In this example, the main flowchart (in Figure 4.44) calls
the subroutine (in Figure 4.43), calculate and sends it C=
the value in number, The function calculate renames
this as vaiue, It adds this to tota2 and outputs it
before returning control to the main program.
Is number No
es
Figure 4.44: Flowchart with condition loop calling calculate
subroutine.
\
: a)
Scanned with CamScanner>
Pseudocode
Parameters ar
“Tameters are identified within the by
ets,
In this example,
Procedure), inpu
then sends
the main prog:
iable number
Of itself,
Draw a flowchart for th
Start by identify
Step 1:
his algorithm.
# the steps required.
User inputs a number,
Step 2: Set the counter to 1
Step 3:
Loop until the counter is the number
entered,
Step 4: If the number is even, call subroutine
Step 5: Else if the number is odd, call subroutine
Create a subroutine taking number as parameter.
@ Multiply the parameter by itself,
b Output the result
Create a subroutine taking number as Parameter.
@ Calculate the parameter to the power of itself,
b Output the result.
Identify what type of symbols these steps need.
Step 1: User inputs a number
Input number store in variable
Step 2: Set counter to |
Process counter = |
Loop until counter is the number entered,
Loop until counter = munber
Step 4: If the number is even call subroutine
Uf counter is even call multiply()
Step 5: Else if the number is odd call subroutine
else call powerof()
Create a subroutine taking number as parameter,
multiply (number)
a Multiply the parameter by itself.
Process number * number
Step
nd
Procedure catculate, This is then
added to total before being output.
power Of(number)
CAMBRIDGE INTERNATIONAL AS & A LEVEL IT: COURSEBOOK
PROCEDURE calculate(value)
total = total + value
ourpuT total
ENDPROCEDURE
INPUT number
calculate(number)
b Output the result
Output result
Create a subroutine taking number as para
@ Calculate the parameter to the power o
Process number * number
b Output the result,
Output result
Draw the flowchart for the subroutines,
PowerOtnumber
1
resuit= number *nunbsr |
i]
Fesult= number * number
i
|
1
re 4.45: Subroutine flowcharts.
Flare 4-45: Subroutine flowcharts,
Draw the flowchart for the main Program.
tines
1g multiple sub(Ou
A
Scanned with CamScanner4 Algorithms and flowcharts
Convert the subroutines and main program to
pseudocode.
Write each subroutine first, then the main program,
PROCEDURE multiply (number
PROCEDURE ply (number) EE
result = number * number oF
CUTEUT reeult
ENDPROCEDURE,
PROCEDURE powerOf (number)
recult = nunber * number Inputcrice
OUTPUT result
counter = 2
WHILE counter < number
IF counter MOD 2 © 0 THEN _ wna
sultiply (number)
ELSE
powerOf (number)
ENDIF to
ILE
seco So nso
Questions
20: What is a subroutine? 5
21, Why are subroutines used in programs? Cx)
22. What is a parameter?
igure 4.48: Flowchart b,
[ir Kener NOUN ANA
Describe what the flowcharts a to d show.
san
Figure 4.49: Flowchart c
Figure 4.47: Flowchart a
7 >
Scanned with CamScannerNNO
Ss
PUT num
OUTPUT rosut
Step
Figure 4.50: Flowchan d.
2 Convert the flowcharts in part 1 into
pseudocode.
3 Create a program that asks the user whether
they want to make word uppercase or
lowercase. Create a procedure to turn a
word uppercase and output it, and a second
procedure to turn a word into lowercase and
output it. Call the appropriate procedure for
| which choice the user inputs.
Draw a flowchart for the algorithm.
| 4 Conver the flowchart {rom part 3 into
| pseudocode.
Nested construct
‘A nested construct is one construct (selection or iteration)
inside of another construct (selection or iteration), For
example, this could be a loop inside another loop, or a
selection statement inside loop, or a selection statement
inside another selection statement. You can even have
multiple nested loops, with several selection statements
je one loop. There is no end to the possibilities
K
CAMBRIDGE INTERNATIONAL AS & A LEVEL IT: COURSEBOO!
vata
construct: a control structure, such as ~
conditional statement
nested loops: one construct that is ins
another construct
In this example (see the flowchart and the
there is a nested loop; a WHILE loop inside
do
WHILE loop.
=
continue =
epertNPUT
\WHNLE continue = Faiee
OUTPUT “Loop again?=
continue = upper aneuT)
MOLE continue 14 *yE8* or contin
OUTPUT "Invalid option. Loop a9"
continue = upper(INPUT)
ENDWHILE
ENDURTLE,
ae
Scanned with CamScanner4. Algorithms and flowcharts
‘A program needs to input the results for 100 students.
Each student has 10 different results and the total
needs to be output for each student,
Create a flowchart for the algorithm.
Start by identifying the steps required.
Step 1: Loop through all 100 students.
Step 2: Loop through all 10 results for each student.
Step 3: Ask for the student's result.
Step4: Input the student’s result.
Step 5S: Add the result to their total.
Step 6: Output the total at the end of each student's
results.
Identify what type of symbols these steps need.
Step 1: Loop through all 100 students.
Count-controlled loop
Step 2: Loop through all 10 results for each student.
Count-controlled loop
Step 3: Ask for the student's result.
Output
Step 4: Input the student’s result.
Input and store the result
Step S: Add the result to their total.
Process total = total + result
Step 6: Output the total at the end of each student’s
results
uaentiomber = 1
‘sudentiamber=elagertimeer + 1
stdentiomber
> 100?
input
studectResat
Output
foe cata
Convert the flowchart into pseudocode.
Each loop is count controlled so replace with FoR loops.
FOR studentiumber = 1 to 101
total = 0
FOR result = 1 to 12
ourpur “Enter " & studentiunber & *'s result " & result
INPUT studentResult
total = total + studentResult
NEXT result
ourpur "Total is* & total
ENDWHILE
Scanned with CamScannerCAMBRIDGE INTERNS oo
ee
uestion
What isa nested statement?
‘an algorithm should ask the user i 1heY
want to perform a calculations and shou!
rng this until they S2¥ Ve
rnehould ask them how
10 add together
that quantity ©
+ and output
continue
Then the progr
many numbers they want t
The program should input
numbers, add them togete
the result
Draw a flowchart forthe algorithm
should take a word as input
from the user. Then take each letter inturn,
and output it the number of times ofits |
position in the alphabet. For example, '2
Pete output once, b” would be Output
twice, and so on.
2. Analgorithm
Create a pseudocode algorithm for
the problem.
Editing an algorithm/flowchart
You need to be able to read an algoritiim, oF flowchart,
ara be able to identify how to make changes (0 It
‘To do this, you need to work out what the algorithm
does first. Do this by using test data to run the
algorithm, follow each step and write down what
happens. Then look atthe difference between what the
algorithm did, and what you need to make it do
iat!
|
Figure 4.53: Maze
The following algorithm visits the yellow ©, th:
green before moving to finish. Start facing
FD2
RT90
FD4
RT90
FDS
LT90
FDI
RT90
FD2
L790
FD4
Edit the algorithm so it visits the yellow box and
the Finish without visiting the green box
‘The algorithm can stay the same up to the yellow
so repeat this:
FD2
RTVO
FD4
Contin te oct om thi Pit. Thee!
different ways you could go, for example
RTO
FD7
Lr9o
Scanned with CamScanner4 Algorithms and flowcharts
“This Nowchart takes in a user's first name and
svourite colour. It takes the first three letters of the
first name, and the first three letters of the colour to
create and output a username.
InPUT eau
th
aitrename 3)
T
‘remame = wsrname
‘majeaiout3)
Figure 4.54: Flovichart-Create a username.
Change the algorithm so that is gets the last three
letters of the colour instead of the first three.
The algorithm can stay the same up to where the
letters are taken from the colour. This box was
originally: username = username & mid(colous0,3)
| Instead it needs to get the last three, so it needs,
changing to:
Username = username & mid(colour,
length(colour)-4,3)
Questions
24 This flowchart takes 10 numbers as input, adds
them together and outputs the total
Figure 4.55: Flowchart-Total 10 numbers.
Change the flowchart so it inputs 20 numbers and
adds them together.
25. This algorithm asks the user to input $0 numbers 1
finds the smallest number and multiplies it by itself
before outputting it.
smallest = 9999
FOR counter = 0 to 50
INPUT nunber
Tf number < smallest THEN
smallest = number
ENDIF
NEXT counter
answer = smallest + amallest
OUTPUT answer
Change the algorithm so it finds the largest number
and multiplies this by itself before outputting it
Correcting an algorithm/
flowchart
You may need to find an error in an algorithm such as
a flowchart, To do this, you need to follow each step of
the algorithm, performing the actions it instructs to find
where it goes wrong.
7 >
~ Scanned with CamScannerCOURSEEOOK
> CAMBRIDGE INTERNATIONAL AS & A LEVEL
An algorithm should take three numbers as input, it should add together the two largest, and out
Find the error in the algorithm,
Figure 4.56: Flowchart with error
Scanned with CamScannerRun the algorithm with all possible different types
example data, for example,
(0, num2 = 5, num = 3 (numt
st), Output should be 15
‘Test 1: num
num? are the lan
‘Test 2: num! = 5, num2 = 3, nwm3 = 10 (numt and
rgest), Output should be 1S
(0, num3 = $ (num? and
«put should be 1S
mum are th
Test
sum’ are the largest), C
“Test 1
Is numl > num? and num! > num3?
Is mum2 > num3 Yes this is true, total = numi + num2
=10+5
OUTPUT IS
correct
Pec Acii ene MLNAcAaLC}
Find the error(s) in this algorithm.
counter 0
I
1 The algorithm should ask the user how many letters they want to enter, then let them enter that many
letters. All the letters should be concatenated and output.
4 Algorithms and flowcharts
est 2
Is numt >
Is mum2 > num
nd numl > num? No
nel num? > numt’? No
umd + num? = 103
m2
Ismumt > num
OUTPUT 13 - Thi
owt Cotal = num’ + num,
the yes and no from the ts
, they need swapping,
sarried
|. I shouted ha
mL > num2? Box are in the
wrong ordi
‘Test 3
Isnuml > num2
Is num? > num3
Is numl > num3? No t
OUTPUT IS
nel numt > num3? No
nel num2 > num? Yes
num + num2 = 5+ 10
correct
word «word
‘ner
=f seine
Lo
OUTPUT word
Figure 4.57: Flowchart with errors.
81
Scanned with CamScannereee
4 Identify two wa: 7
‘hut an algorithm can be expres
2 Numi the actions for these fowchart shapes
Scanned with CamScanner