Beruflich Dokumente
Kultur Dokumente
Algorithm
An algorithm is a precise, step-by-step set of instructions for solving a task. An algorithm does not
solve a task; it gives you a series of steps that, if executed correctly, will result in a solution to a task.
R
Pseudocode: Pseudocode is a simple way of writing programming code in English. Pseudocode
is not actual programming language. It uses short phrases to write code for programs before
you actually create it in a specific language.
KU
Flowchart: A flowchart shows diagrammatically the steps required for a task (sub-system) and
the order that they are to be performed. These steps together with the order are called an
ALGORITHM. Flowcharts are an effective way to communicate the algorithm that shows how a
system or sub-system works.
A
OR
WORD/PHRASE DESCRIPTION
SET To set/store values/variables – initialization/declaration
READ/INPUT To input/get data from user/keyboard
PRINT/OUPUT To output/return data/value on screen
END To show the end of algorithm
IF … THEN … ELSE … ENDIF Selection – to check some condition
CASE … OF … OTHERWISE … Selection – to match multiple values/variables/conditions
A
ENDCASE
FOR….TO….NEXT Loop – (Unconditional) to repeat some task(s) a specific
number of times.
WHILE…DO…ENDWHILE Loop – (Conditional) to repeat some task(s) till a condition
remains TRUE
REPEAT…UNTIL Loop – (Conditional) to repeat some task(s) till a condition
remains FALSE
R
IF … THEN … ELSE … ENDIF
CASE … OF … OTHERWISE … ENDCASE
KU
IF … THEN … ELSE … ENDIF
It is used to check only one condition and act accordingly.
Syntax
IF <condition> THEN
<statement if condition is TRUE>
ELSE
A
<statement if condition is FALSE>
ENDIF
Example: Algorithm to check whether the input value is greater than100 and output the message
accordingly.
TH
SET number to 0
INPUT number
IF number > 100 THEN
OUTPUT “The entered number is greater than 100”
ELSE
OUTPUT “The entered number is smaller than 100”
ENDIF
ED
END
Result of Program:
R
KU
IF…THEN…ELSEIF…ELSE…ENDIF
This is used to check multiple conditions.
Each ELSEIF works like IF, but must be used within the main structure of IF…ENDIF.
There is no limit of ELSEIFs
If any of the ELSEIF’s condition is met, the rest of the ELSEIFs are not checked.
A
Syntax
IF <condition> THEN
<statement if condition is TRUE>
ELSEIF <condition> THEN
TH
<statement if condition is TRUE>
ELSEIF <condition> THEN
<statement if condition is TRUE>
ELSEIF <condition> THEN
<statement if condition is TRUE>
ELSEIF <condition> THEN
<statement if condition is TRUE>
ED
.
.
.
ELSE
<statement if condition is FALSE>
HM
ENDIF
Example: Algorithm to generate a marks sheet and check the grading scheme based on the
following criteria:
D 50 – 59.99
U < 50 (less than 50)
R
A 80 – 89.99
B 70 – 79.99
C 60 – 69.99
KU
D 50 – 59.99
U less than 50
A
INPUT eng, comp, isl, math, phy, chem
Tot = eng + comp + isl + math + phy + chem
Per = (Tot/375)* 100
R
KU
A
TH
ED
HM
Result of Program:
A
Syntax
CASE <identifier (variable) OF
<constant>,<constant>,<constant> : <statement>
<constant>,<constant>,<constant> : <statement>
R
<constant>,<constant>,<constant> : <statement>
<constant>,<constant>,<constant> : <statement>
OTHERWISE
KU
<constant> : <statement if identifier/variable is not matched>
ENDCASE
EXAMPLE (NOV 2003 – Q11): The following algorithm inputs air speeds (which must be in multiples of
100) and outputs a suitable message.
A
1. input a speed
2. whole = speed/100
3. case whole of
4. 0,1,2 : result = slow
5. 3, 4, 5, 6 : result = normal
TH
6. 7, 8, 9 : result = high
7. otherwise whole = -1
8. endcase
9. if whole = -1 then
10. output “abnormal reading”
11. else output result, “speed”
ED
(a) Dry run the above algorithm for the following Input data and complete the Output column in
INPUT OUTPUT
(b) State what would happen if line 2 had been missed out of the algorithm.
Variable whole would not be defined,
algorithm would fail/crash, etc.
A
R
KU
A
TH
Result of Program:
ED
HM
A
Example 2: The following example uses a Select Case construction to write a line corresponding to
the value of the variable number.
R
KU
A
TH
Result of Program
ED
Unconditional Loop: Unconditional loop repeats the tasks unconditionally the specified number of
times.
FOR … TO … NEXT
Syntax
FOR <identifier(variable> = <number> TO <number>
<statement>
<statement>
<statement>
R
NEXT
Example:
KU
Algorithm to output name 10 times. Algorithm to output numbers from 1- 10.
SET a to 0 SET a to 0
FOR a = 1 TO 10 FOR a = 1 TO 10
OUTPUT “Ahmed Thakur” OUTPUT a
NEXT NEXT
END END
A
Program TH
ED
Result
HM
A
Task: The following algorithm inputs 20 numbers and outputs how many numbers were positive
(> 0) and how many numbers were negative (< 0).
Algorithm (Corrected):
1 negative = 0
R
2 positive = 0
3 FOR count = 1 TO 20
4 input number
KU
5 if number < 0 then negative = negative + 1
6 if number > 0 then positive = positive + 1
8 NEXT count
9 print negative, positive
A
TH
ED
HM
A
WHILE … DO … ENDWHILE
It is a conditional loop.
Loop continues till the condition remains TRUE.
Condition is check first and the process comes next to it.
Syntax
WHILE <condition> DO
R
<statement>
<statement>
<statement>
KU
<identifier> = <identifier> + <number>
ENDWHILE
Example:
Algorithm to output name 10 times. Algorithm to output numbers from 1- 10.
A
SET a to 0 SET a to 0
WHILE a < 10 DO WHILE a < 10 DO
a = a + 1 a = a + 1
Output “Ahmed Thakur” OUTPUT a
ENDWHILE
TH ENDWHILE
END END
Program
ED
HM
Result
A
Program code that inputs 30 positive numbers and then output the largest number input.
Algorithm (Corrected):
1 Large = 0
2 Counter = 0
R
3 WHILE Counter < 30
4 DO
5 INPUT Num
KU
6 IF Num > Large THEN Large = Num
7 Counter = Counter + 1
8 ENDWHILE
9 PRINT Large
Exercise:
A
June 2015, Paper 22 – Q2
June 2005 – Q13 (b)
November 2002 – Q13
November 2006 – Q9
TH
ED
HM
A
REPEAT… UNTIL
It is a conditional loop.
Loop continues till the condition remains FALSE.
The process comes first, condition is checked next.
Syntax
REPEAT
R
<statement>
<statement>
<statement>
KU
<identifier> = <identifier> + <number>
UNTIL <condition>
Example:
Algorithm to output name 10 times. Algorithm to output numbers from 1- 10.
SET a to 0 SET a to 0
A
REPAT REPAT
a = a + 1 a = a + 1
Output “Ahmed Thakur” Output a
UNTIL a = 10 UNTIL a = 10
END
TH END
Program
ED
HM
Result
A
Algorithm
1 count = 1
2 repeat
3 input day, month, year
R
4 count = count + 1
5 until count = 1000
KU
(i) Describe why the loop only inputs 999 dates instead of 1000.
value of count starts at 1 so only 999 iterations
value of count reaches 1000, but before 1000th input
(ii) What needs to be changed or added to the above code to make sure 1000 dates are input?
line 1 should read count = 0
A
line 5 should read count = 1001 (or count >1000)
change to appropriate loop structure
Corrected Algorithm
1 count = 0
2 repeat
TH
3 input day, month, year
4 count = count + 1
5 until count = 1000
Exercise:
June 2011, Paper 12 – Q7
June 2015, Paper 21 – Q2
ED
Understand and use pseudocode, using the following commands and statements:
INPUT and OUTPUT (e.g. READ and PRINT)
HM
INPUT/READ
This command is used in pseudocode to accept/collect/get data value from user/keyboard entry.
Algorithm: To take two numbers from user and output the sum.
SET num1, num2, tot to 0
A
INPUT num1
INPUT num2
tot = num1 + num2
OUTPUT tot
END
OUTPUT/PRINT
This command is used in pseudocode to output/display any value or string on screen.
Algorithm: To change the magnitude (sign) of a user entered number and output it.
SET num,chng_mag to 0
INPUT num
Chng_mag = num x -1
OUTPUT chng_mag
END
R
Further techniques used in Algorithm:
Counting
Totaling
KU
Highest(Greatest) / Lowest(Smallest)
COUNTING
Counting in 1s is quite simple; use of the statement count = count + 1 will enable counting to
be done (e.g. in controlling a repeat loop). The statement literally means: the (new) count =
the (old) count + 1
A
It is possible to count in any increments just by altering the numerical value in the statement (e.g.
count = count – 1 counts backwards)
Exercise:
TH
June 2014, Paper 32 – Q1 (i)
June 2013, Paper 12 – Q17
June 2012, Paper 12 – Q15
November 2011, Paper 13 – Q16
June 2011, Paper 12 – Q17
November 2010, Paper 13 – Q17 (b)
November 2010, Paper 12 – Q9
June 2009 – Q18
ED
TOTALING
HM
Example: Algorithm to count total number of positive and negative entries in 100 inputs.
Algorithm:
SET num, pos, neg to 0
FOR a = 1 TO 100
A
INPUT num
IF num >= 0 THEN
pos = pos + 1
ELSE
neg = neg + 1
ENDIF
OUPUT pos, neg
END
HIGHEST / LOWEST
This technique is used to get the highest or lowest value of many entered values.
The variable for highest value must be initialized with 0 (expected smallest value)
The variable for lowest value must be initialized with 1000 (expected highest value)
R
The weather conditions in a town are being monitored over a year (365 days). The values recorded
per day are weather type and temperature (e.g. CLOUDY, 25).
KU
Write an algorithm, using pseudocode or flowchart only, which:
inputs the weather type and temperature for each day
outputs the number of days that were CLOUDY, RAINING, SUNNY or FOGGY
outputs the highest recorded temperature for the year
outputs the lowest recorded temperature for the year
Solution:
SET weathertype, to “ ”
A
SET temp, avg, hightest, cloud, rain, sun, fog to 0
SET lowest to 1000
sunnyday = sunnyday + 1
ELSEIF weathertype = “FOGGY” THEN
foggyday = foggyday + 1
ENDIF
HM
END
Exercise:
November 2011, Paper 13 – Q16
Specimen Paper 1, 2011 – Q19
PSEUDOCODES PROBLEMS
R
PROBLEMS
Questions 1 to 3 contain sections of pseudocode which contain errors. Locate the errors and suggest
the correct coding. Questions 4 to 10 are problems which require an algorithm to be written in
KU
pseudocode – there is “no right answer” here; as long as the pseudocode works then the solution is
acceptable.
(1) The following section of pseudocode inputs 1000 numbers and then outputs how many were
negative, how many were positive and how many were zero.
A
1 negative = 1: positive = 1
2 for x = 0 to 1000
3 input number
4 if number < 0 then negative = negative + 1
TH
5 if number > 0 then positive = positive + 1
6 endif
7 endif
8 next
9 print negative, positive
(2) The following section of pseudocode inputs rainfall (in cm) for 500 days and outputs the average
rainfall and the highest rainfall input.
ED
(3) The following section of pseudocode inputs a number, n, multiplies together 1 x 2 x 3 x ……. x n,
calculates input number/sum and outputs result of the calculation.
A
(4) Regis lives in Brazil and often travels to USA, Europe and Japan. He wants to be able to convert
Brazilian Reais into US dollars, European euros and Japanese yen. The conversion formula is:
For example, if Regis is going to USA and wants to take 1000 Reais (and the exchange rate is
0.48) then he would input USA, 1000 and 0.48 and the output would be: 480 US dollars.
R
Write an algorithm, using pseudocode, which inputs the country he is visiting, the exchange rate
and the amount in Brazilian Reais he is taking. The output will be value in foreign currency and
KU
the name of the currency.
(5) As part of an experiment, a school measured the heights (in metres) of all its 500 students.
Write an algorithm, using pseudocode, which inputs the heights of all 500 students and outputs
the height of the tallest person and the shortest person in the school.
A
(6) A geography class decide to measure daily temperatures and hours of sunshine per day over a
12 month period (365 days)
Write an algorithm, using pseudocode, which inputs the temperatures and hours of sunshine for
TH
all 365 days, and finally outputs the average (mean) temperature for the year and the average
(mean) number of hours per day over the year.
(7) A small shop sells 280 different items. Each item is identified by a 3 – digit code. All items that start
with a zero (0) are cards, all items that start with a one (1) are sweets, all items that start with a
two (2) are stationery and all items that start with a three (3) are toys.
Write an algorithm, using pseudocode, which inputs the 3 – digit code for all 280 items and
ED
(8) A company are carrying out a survey by observing traffic at a road junction. Each time a car,
bus, lorry or other vehicle passed by the road junction it was noted down.
(9) Speed cameras read the time a vehicle passes a point (A) on the road and then reads the time
it passes a second point (B) on the same road (points A and B are 100 metres apart). The speed
of the vehicle is calculated using:
A
The maximum allowed speed is 100 kilometres per hour. 500 vehicles were monitored using these
cameras over a 1 hour period.
inputs the start time and end time for the 500 vehicles that were monitored
calculate the speed for each vehicle using the formula above
outputs the speed for each vehicle and also a message if the speed exceeded 100 km/hour
output the highest speed of all the 500 vehicles monitored
R
The train travels in both directions (i.e. from 1 to 10 and then from 10 to 1). The fare between
each station is $2.
KU
A passenger inputs the number of the station at the start of his journey and the number of the
destination station and the fare is calculated (e.g if a passenger gets on a station 3 and his
destination is station 9 his fare will be $12). The calculation must take into account the direction
of the train (e.g. a passenger getting on at station 7 and getting off at station 1 will also pay $12
and not a negative value!!).
A
A discount of 10% is given if 3 or more passengers are travelling together.
1. Three errors:
ED
2. Three errors:
3. Three errors:
2 input conv_rate
3 input no_reais
4 currency_value = no_reais * conv_rate
5 if country = USA then print “$”, currency_value
6 if country = Europe then print “€”, currency_value
7 if country = Japan then print “¥”, currency_value
5.
R
1 tallest = 0
2 shortest = 500
3 for count = 1 to 500 do
KU
4 input height
5 if height > tallest then tallest = height
6 if height < smallest then smallest = height
7 next
8 print tallest, shortest
A
6.
1 sum_temp = 0: sum_hours = 0
2 for count = 1 to 365 do
3 input temp, hours
4 sum_temp = sum_temp + temp
5 sum_hours = sum_hours + hours
TH
6 next
7 mean_temp = sum_temp/365
8 mean_hours = sum_hours/365
9 print mean_temp, mean_hours
7.
1 cards = 0: stationery = 0: toys = 0
ED
8 next
9 print cards, stationery, toys
8.
1 cars = 0: buses = 0: lorry = 0: others = 0
2 for count = 1 to 10000 do
3 input vehicle
4 if vehicle = car then cars = cars + 1
5 if vehicle = bus then buses = buses + 1
6 if vehicle = lorry then lorry = lorry + 1
A
9.
1 highest = 0
2 for count = 1 to 500 do
3 input start_time, end_time
4 speed = 100/(end_time – start_time) {NOTE: m/second}
5 speed = speed * 3.6 {NOTE: conversion to km/hour}
10.
R
1 input start
2 input end
3 if end > start then no_stations = end – start
KU
4 else no_stations = start – end
5 cost = no_stations * 2
6 input no_passengers
7 if no_passengers > 2 then cost = 0.9 * cost
8 final_cost = cost * no_passengers
9 print final_cost
A
10 print tickets
[NOTE: it is possible to use other loop structures other than for …. to; the algorithms would work equally
as well with repeat …. until or while …. endwhile. The for …. to loops work particularly well when an
exact count is known (e.g. exactly 100 temperatures). If we had to input temperatures until they
TH
became negative it would be best to use a while or repeat loop, for example].
ED
HM
A
Understand and use standard flowchart symbols to represent the above statements, commands
and structures
Flowchart
A graphic map of the path of control or data through the operations in a program or an information-
handling system. Symbols such as squares, diamonds, and ovals represent various operations. These
R
symbols are connected by lines and arrows to indicate the flow of data or control from one point to
another.
KU
OR
A
Oval Terminal Interrupt TH Start/Stop of Flowchart
For Selection
Rhombus Decision Box
IF condition
HM
Introduction to Flowcharts
This section covers the use of flow diagrams (charts) in the production of algorithms. Systems
flowcharts are different and these are covered in a different section (Systems analysis).
The early part of section 3.1 (i.e. top down design, structure diagrams, menus, libraries of procedures
and subroutines) is covered adequately by standard text books.
R
This section primarily covers four areas:
1. Common flow chart symbols
2. Writing flowcharts to solve problems
KU
3. Dry running of flowcharts to determine its function and outputs
4. Exercises to test the above concepts
A
TH
ED
HM
A
Example 1
A town contains 5000 houses. Each house owner must pay tax based on the value of the house.
Houses over $200 000 pay 2% of their value in tax, houses over $100 000 pay 1.5% of their value in tax
and houses over $50 000 pay 1% of their value in tax. All others pay no tax. Write an algorithm to
solve this problem in the form of a flowchart.
R
KU
A
TH
ED
HM
A
Example 2
The following formula is used to calculate n: n = (x * x)/(1 – x). The value x = 0 is used to stop the
algorithm. The calculation is repeated using values of x until the value x = 0 is input. There is also a
need to check for error conditions. The values of n and x should be output. Write an algorithm to
show this repeated calculation in the form of a flowchart.
R
KU
A
TH
ED
HM
A
Example 3
Write an algorithm in the form of a flowchart which takes temperatures input over a 100 day period
(once per day) and outputs the number of days when the temperature was below 20 °C and the
number of days when the temperature was 20 °C and above.
R
KU
A
TH
ED
HM
A
Example 4
Write an algorithm in the form of a flowchart which:
inputs the top speeds (in km/hr) of 5000 cars
outputs the fastest speed and the slowest speed
outputs the average (mean) speed of all the 5000 cars
R
KU
A
TH
ED
HM
A
Example 5
A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code. All books
have a code starting with 1, all maps have a code starting with 2 and all magazines have a code
starting with 3. The code 9999 is used to end the algorithm.
Write an algorithm in the form of a flowchart which inputs the codes for all items in stock and outputs
the number of books, number of maps and the number of magazines in stock. Include any validation
checks needed.
R
KU
A
TH
ED
HM
A
R
When dry running a flowchart it is advisable to draw up a trace table showing how variables change
their values at each stage in the algorithm. The advantages of doing this are:
KU
if you make a mistake, it is easier to back track to where the error occurred rather than starting
from the beginning again
there is less chance of an error being made
encourages a more logical approach
The following three examples show all stages in the dry running for the given set of input data:
A
TH
ED
HM
A
Example 1
This algorithm inputs 3 numbers, each number goes through successive division by 10 until its value is
less than 1. An output is produced which contains the number input and a value generated by the
flowchart processing.
R
KU
A
TH
ED
HM
X N T Output T, N
85 1 85
8.5 2
0.85 85, 2
3190 1 3190
319 2
31.9 3
3.19 4
A
0.319 3190, 4
Example 2
This algorithm inputs 5 values and outputs how many input numbers were negative and how many
were positive.
R
KU
A
TH
ED
HM
A
Example 3
This algorithm inputs the number of hours of sunshine recorded each day for a week (7 days). The
output is the highest value for hours of sunshine and the average (mean) value for the numbers of
hours of sunshine per day.
Data to be used: hours = 9.0, 7.8, 1.2, 4.5, 10.0, 6.4, 3.1
R
KU
A
TH
ED
HM
A
FLOWCHARTS PROBLEMS
Questions 1 to 7 are problems which require an algorithm to be written in the form of a flowchart.
Questions 8 to 10 require a trace table to be written and find the expected output for the given set
of data. The answers to these questions can be found in Section 6.
R
(1) Regis lives in Brazil and often travels to USA, Europe and Japan. He wants to be able to convert
Brazilian Reais into US dollars, European euros and Japanese yen. The conversion formula is:
currency value = number of Reais X conversion rate
KU
For example, if Regis is going to USA and wants to take 1000 Reais (and the exchange rate is 0.48)
then he would input USA, 1000 and 0.48 and the output would be: 480 US dollars.
Write an algorithm, using a flowchart, which inputs the country he is visiting, the exchange rate and
the amount in Brazilian Reais he is taking. The output will be value in foreign currency and the name
of the currency.
A
(2) As part of an experiment, a school measured the heights (in metres) of all its 500 students.
Write an algorithm, using a flowchart, which inputs the heights of all 500 students and outputs the
height of the tallest person and the shortest person in the school.
TH
(3) A geography class decide to measure daily temperatures and hours of sunshine per day over a
12 month period (365 days)
Write an algorithm, using a flowchart, which inputs the temperatures and hours of sunshine for all 365
days, and finally outputs the average (mean) temperature for the year and the average (mean)
number of hours per day over the year.
ED
(4) A small shop sells 280 different items. Each item is identified by a 3 – digit code. All items that start
with a zero (0) are cards, all items that start with a one (1) are sweets, all items that start with a
two (2) are stationery and all items that start with a three (3) are toys.
Write an algorithm, using a flowchart, which inputs the 3 – digit code for all 280 items and outputs
the number of cards, sweets, stationery and toys.
HM
(5) A company are carrying out a survey by observing traffic at a road junction. Each time a car,
bus or lorry passed by the road junction it was noted down.
(6) Speed cameras read the time a vehicle passes a point (A) on the road and then reads the time
it passes a second point (B) on the same road (points A and B are 100 metres apart). The speed
of the vehicle is calculated using:
The maximum allowed speed is 100 kilometres per hour. 500 vehicles were monitored using these
cameras over a 1 hour period.
R
output the highest speed of all the 500 vehicles monitored
KU
1 ------ 2 ------ 3 ------ 4 ------ 5 ------ 6 ------ 7 ------ 8 ------ 9 ------ 10
The train travels in both directions (i.e. from 1 to 10 and then from 10 to 1). The fare between
each station is $2.
A
A passenger inputs the number of the station at the start of his journey and the number of the
destination station and the fare is calculated (e.g if a passenger gets on a station 3 and his
destination is station 9 his fare will be $12). The calculation must take into account the direction
of the train (e.g. a passenger getting on at station 7 and getting off at station 1 will also pay $12
and not a negative value!!).
TH
A discount of 10% is given if 3 or more passengers are travelling together.
(8) Draw the trace table and determine the output from the following flowchart using the following
data:
R
KU
A
TH
ED
HM
A
(9) Draw the trace table and determine the output from the following flowchart using the following
data (NOTE: input of the word “end” stops the program and outputs results of the survey):
vehicle = car, car, lorry, bus, van, van, car, car, bus, car, end
R
KU
A
TH
ED
HM
A
(10) Draw the trace table and determine the output from the following flowchart using the following
data:
R
KU
A
TH
ED
HM
A
1.
R
KU
A
TH
ED
HM
A
2.
R
KU
A
TH
ED
HM
A
3.
R
KU
A
TH
ED
HM
A
4.
R
KU
A
TH
ED
HM
A
5.
R
KU
A
TH
ED
HM
A
6.
R
KU
A
TH
ED
HM
A
7.
R
KU
A
TH
ED
HM
A
8. (NOTE: there is an error in the question in Section 3.1 – output box should read: OUTPUT X,T)
R
KU
A
9. (NOTE: there is an error in the question in Section 3.1 – the “others = others + 1” statement
should by-pass all the other counting procedures)
TH
ED
HM
10.
A