0% found this document useful (0 votes)
3 views22 pages

Pseudocode

Computer science Grade 11 Chaptre Pseudocode

Uploaded by

yjn6tdctcd
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)
3 views22 pages

Pseudocode

Computer science Grade 11 Chaptre Pseudocode

Uploaded by

yjn6tdctcd
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

Computer science O Level - unit 7- Pseudocode prepared by Mr H.

Dewkarun

PSEUDOCODE

An algorithm is a set of sequenced instructions to represent a program.

pseudocode and flowcharts are two ways to represent an algorithm.

Pseudocode

Pseudocode is a series of English statements to explain an algorithm.

It has no strict syntax rules of a programming language.

It is used subsequently to write program codes for a computer program .

There are 3 types of structure which are used in a computer program.

1. Sequence – a program executes statements in order line by line.


2. Selection – conditional statements(if) are used to execute selected statement.
3. Repetition – a loop is used to execute the same statement many times.

Variable
It is an identifier which stores values/data in memory. Ex Name, price etc

Constants
Constants are declared by stating the identifier and the literal value in the following format:
CONSTANT <identifier> ← <value>

Example – CONSTANT declarations


CONSTANT HourlyRate ← 6.50
CONSTANT DefaultText ← "N/A"

Basic data types


The following keywords are used to designate basic data types:
• INTEGER a whole number
• REAL a number capable of containing a fractional part
• CHAR a single character
• STRING a sequence of zero or more characters
• BOOLEAN the logical values TRUE and FALSE

Copyright By Mr [Link] 1
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

Variable declarations
Declarations are made as follows:
DECLARE <identifier> : <data type>

Example – variable declarations


DECLARE Counter : INTEGER

DECLARE TotalToPay : REAL

DECLARE GameOver : BOOLEAN

Assignment
Values are assigned to a variable using the ← operator.
Ex. Cost ← 10, Cost is given the value of 10

Mathematical operators

Operator Action
+ add
– subtract
* multiply
/ divide
^ raise to the power
() group

The integer division operators MOD and DIV can also be used.
DIV(<identifier1>, <identifier2>)
Returns the quotient of identifier1 divided by identifier2 with the fractional part discarded.
MOD(<identifier1>, <identifier2>)
Returns the remainder of identifier1 divided by identifier2
The identifiers are of data type integer.

Examples – MOD and DIV

DIV(10, 3) returns 3
MOD(10, 3) returns 1

Copyright By Mr [Link] 2
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

Examples of pseudocode assignments:


Price ← Cost * 20
Tax ← Price * 0.12
SellingPrice ← Price + Tax
Gender ←"M"
Chosen ← False
Work out:
find the values of the variables below:

Amount ← 100
TotalPrice ← Amount * 3.5
Discount ← 0.2
FinalPrice ← TotalPrice – TotalPrice * Discount
Name ←"Nikkil"
Message ←"Hello" + Name

Logical operators
Operator Comparison
> greater than
< less than
= equal
>= greater than or equal
<= less than or equal
<> not equal
() group

Boolean operators
The only Boolean operators used are AND, OR and NOT. The operands and results of these
operations are always of data type BOOLEAN.
Input and output statements
INPUT, READ - used for the entry of data
It is followed by a variable.
example:
INPUT Name
Read StudentMark
Copyright By Mr [Link] 3
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

OUTPUT, PRINT - display of information


It is followed by a string or a variable or a list of values
separated by commas,
example:
PRINT Name ---a variable
PRINT "Your name is", Name --- a string
OUTPUT Name1, Name2, Name3---- a list of values

Standard actions
Increasing a total by addition:

Total ← Total + Value

Sum ← sum + Value

Ex Add all the numbers 10, 15, 20, 25, 30

Total ←0

Total ← Total + Value

10 ← 0 + 10

…… ← 10 + 15

…….. ← .….+ 20

…….. ← …….+ 25

……. ← …….+ 30

count of the number of times an action is performed:

increment by 1

Count ← Count + 1

Counter ← Counter + 1

i←i+1

Copyright By Mr [Link] 4
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

Decrement by 1

Count ← Count - 1

Counter ← Counter - 1

i←i-1

Initialization
OverallHighest ← 0

OverallLowest ← 100

OverallTotal ← 0

Counter ← 1

String operations
LENGTH(<identifier>)
Returns the integer value representing the length of string. The identifier should be of data type string.

LCASE(<identifier>)
Returns the string/character with all characters in lower case. The identifier should be of data type string or
char.

UCASE(<identifier>)
Returns the string/character with all characters in upper case. The identifier should be of data type string or
char.

SUBSTRING(<identifier>, <start>, <length>)


Returns a string of length length starting at position start. The identifier should be of data type string, length
and start should be positive and data type integer.
Example – string operations
LENGTH("Happy Days") will return 10

LCASE(ꞌWꞌ) will return ꞌwꞌ

UCASE("Happy") will return "HAPPY"

SUBSTRING("Happy Days", 1, 5) will return "Happy"

Copyright By Mr [Link] 5
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

Other library routines


ROUND(<identifier>, <places>)
Returns the value of the identifier rounded to places number of decimal places.
The identifier should be of data type real, places should be data type integer.

RANDOM()
Returns a random number between 0 and 1 inclusive.

Example – ROUND and RANDOM


Value ← ROUND (RANDOM() * 6, 0) // returns a whole number between 0 and 6

SEQUENCE OF INSTRUCTIONS IN A PSEUDOCODE


1. Initialisation
2. Input
3. Process – condition + iteration
4. Output

Conditional statements
Conditional statements are used to decide which action should be taken.
Two types of conditional statement:

1. IF … THEN … ELSE … ENDIF, condition can be true or false

2. CASE … OF … OTHERWISE … ENDCASE, choice between several different values

IF … THEN … ELSE … ENDIF

IF {CONDITION = TRUE} THEN


ACTION TRUE
ELSE
ACTION FALSE
ENDIF

Copyright By Mr [Link] 6
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

EX.1 EX. 2

IF Age < 18 THEN IF MARK < 40 THEN


PRINT "Child" OUTPUT “FAIL”
ELSE ELSE
PRINT "Adult" OUTPUT “PASS”
ENDIF ENDIF

EX.1 EX.2
IF (MARKS >= 90) AND (MARKS < 101 ) THEN IF (BOY < 18) OR (GIRL < 18 ) THEN
OUTPUT “DISTINCTION” OUTPUT “MINOR”
ELSE ELSE
OUTPUT “CREDIT” OUTPUT “ADULT”
ENDIF ENDIF
Ex .3
IF ((HEIGHT > 1) OR (WEIGHT > 20) OR (AGE > 5)) AND (AGE < 70) THEN
PRINT "YOU CAN RIDE"
ELSE
PRINT "TOO SMALL, TOO YOUNG OR TOO OLD"
ENDIF

Copyright By Mr [Link] 7
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

IF … THEN …ELSEIF … ELSE … ENDIF (nested IF)


This makes use of two IF statements or more.

IF {CONDITION 1 = TRUE} THEN


ACTION 1
ELSE IF {CONDITION 2 = TRUE} THEN
ACTION 2
ELSE
ACTION FALSE
ENDIF
ENDIF
Ex:1 IF PERCENTAGEMARK < 0 OR PERCENTAGEMARK >100 THEN
PRINT “INVALID MARK”
ELSE
IF PERCENTAGEMARK > 49 THEN
PRINT “PASS”
ELSE
PRINT “FAIL”
ENDIF
ENDIF
EX: 2
IF NUM < 0 THEN
OUTPUT “NUMBER IS NEGATIVE”
ELSE
IF NUM > 0 THEN
OUTPUT “NUMBER IS POSITIVE”
ELSE
OUTPUT ‘’ NUMBER EQUALS TO ZERO”
ENDIF
ENDIF

Copyright By Mr [Link] 8
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

WORK OUT:
1. Complete the pseudocode that asks the user to input 3 item code and assign a value to the
cost of the item according to the table.
ITEM_CODE COST (RS)
1 10
2 20
3 30

INPUT ITEM_CODE
IF ITEM_CODE = 1 THEN
COST ← …..
………
IF …………………….. THEN
COST ← 20
ELSE
……. ITEM_CODE =……. THEN
………. ← 30
ELSE
…………. “INVALID ITEM_CODE”
ENDIF
ENDIF
ENDIF

2. Complete the pseudocode below that asks a user to input his age and checks whether he has
entered a correct age. It then output the respective category according to the table.
AGE CATEGORY
1 - 12 CHILD
13 - 17 TEENAGER
18 - 120 ADULT

Copyright By Mr [Link] 9
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

INPUT AGE
IF (AGE >= 1) AND (AGE < 13) THEN
OUTPUT “CHILD”
ELSE IF (AGE > ….) AND (AGE ….. 18) THEN
OUTPUT “……………………..”
……… IF (AGE …. ….) AND (AGE ….. ……) THEN
PRINT “ ADULT”
ELSE
……………. “INVALID AGE”
ENDIF
ENDIF
ENDIF
3. Write an algorithm that ask a user to input a mark and then output its grade according to the
table.
MARK GRADE
80 - 100 A
70 - 79 B
60 - 69 C
50 – 59 D
40 – 49 E
0 - 39 U

Copyright By Mr [Link] 10
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

CASE … OF … OTHERWISE … ENDCASE


It is an alternative to multiple IF statements.
Selection is based on one variable with multiple values.
Logical operators cannot be used. ( AND, OR, NOT)
CASE (VARIABLE) OF CASE (VARIABLE)
(VALUE1) : STAEMENT1 CASE (VALUE1)
(VALUE2) : STATEMENT2 STATEMENT1
……. CASE (VALUE2)
…….. STATEMENT2
OTHERWISE …….
STATEMENT (NONE OF THE ABOVE) ……..
END CASE OTHERWISE
STATEMENT (NONE OF THE ABOVE)

END CASE
EX 1: EX 1:
CASE Grade OF CASE GRADE
"A" : PRINT "Excellent" CASE “A”
"B" : PRINT "Good" OUTPUT “EXCELLENT”
"C" : PRINT "Average" CASE “B”
OTHERWISE PRINT "Improvement is needed" OUTPUT “GOOD”
ENDCASE CASE “C”
EX 2: OUTPUT “AVERAGE”
CASE Choice OF OTHERWISE PRINT "Improvement is needed"

1 : Answer ← Num1 + Num2 ENDCASE

2 : Answer ← Num1 - Num2

3 : Answer ← Num1 * Num2

4 : Answer ← Num1 / Num2

OTHERWISE PRINT "Please enter a valid choice"


ENDCASE

Copyright By Mr [Link] 11
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

Comparison of Case and NestedIF pseudocode for a calculator algorithm.


Input number 1 Input number 1
Input number 2 Input number 2
Input operator Input operator

If operator = “Add” then Case Operator


Output number 1 + number 2 Case “Add”
Else Output number 1 + number 2
If operator = “subtract” then Case “subtract”
Output number 1 - number 2 Output number 1 - number 2
Else Case “multiply ”
If operator = “multiply” then Output number 1 * number 2
Output number 1 * number 2 Case “divide”
Else Output number 1 / number 2
If operator = “divide” then Otherwise
Output number 1 / number 2 Output “Incorrect operator”
Else End Case
Output “Incorrect operator”
Endif
Endif
Endif
Endif

Ex 3: Case using comparison operators


Case Percent
Case >= 80
Output “Grade A”
Case >= 70
Output “Grade B”
Case >= 60
Output “Grade C”
Case >= 50
Output “Grade D”
Otherwise
Output “Grade U”
End Case

Copyright By Mr [Link] 12
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

Work out: A company manufactures three different types of item, with costs based on the
following:

Write a pseudocode which inputs the item type and output the item cost for each item. Use Case.

Work out: write a pseudocode which input a number 1 to 7 for each day and output each day of
the week. If a wrong number is entered, it will output “please enter a number between 1 and 7”.
Use case

Copyright By Mr [Link] 13
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

Loop structures
Iteration is to repeat actions in an algorithm.

Loop structures are used to perform the iteration.

There are three different types of loop structure:

1. FOR … TO … NEXT a fixed number of repetitions

2. REPEAT … UNTIL at least one repetition, number not known

3. WHILE … DO …ENDWHILE may not repeat, number not known

FOR … TO … NEXT
Repeat statements for a number of times.

Statements

FOR shows which loop we are using.

COUNTER is a variable which will take values for repetition

1 is the starting value of the variable

10 is the ending value of the variable

Statements . This statement will repeat.

NEXT - The variable is increased by one.

Ex 1. Print numbers from 1 to 12

FOR NUM ← 1 TO 12

OUTPUT NUM

NEXT

Copyright By Mr [Link] 14
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

EX 2: Write a pseudocode to check the age for 50 people. If their age is below 18, output
“child”. Otherwise output “Adult”.

FOR x ← 1 TO 50

IF Age < 18 THEN

PRINT "Child"

ELSE

PRINT "Adult"

ENDIF

NEXT
EX 3: Write a pseudocode to check 20 numbers and output whether the number is positive
or negative or zero.

FOR NUMBER ← 1 TO 20

INPUT NUM

IF NUM < 0 THEN


OUTPUT “NUMBER IS NEGATIVE”
ELSE
IF NUM > 0 THEN
OUTPUT “NUMBER IS POSITIVE”
ELSE
OUTPUT ‘’ NUMBER EQUALS TO ZERO”
ENDIF
ENDIF
NEXT

Copyright By Mr [Link] 15
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

Ex4: FOR NUMBER ← 1 TO 20 step 1 - increase by one 1,2,3,4 ….20

FOR NUMBER ← 1 TO 20 step 2 - increase by two 3,5,7,……20

FOR NUMBER ← 10 TO 1 step -1 - decrease by one 10,9,8,7…..1

Work out: complete the pseudocode which prints the word “LOOP” 10 times.

…………… COUNTER ← ……….. TO ………..

OUTPUT “LOOP”
……………

Maximum, minimum
MaximumMark ← 0

MinimumMark ← 100

FOR Counter ← 1 TO 30

Input StudentMark
IF StudentMark > MaximumMark THEN

MaximumMark ← StudentMark

ENDIF
IF StudentMark < MinimumMark THEN

MinimumMark ← StudentMark

ENDIF
NEXT Counter

Average
Total ← 0

FOR Counter ← 1 TO ClassSize (30)

Input StudentMark

Total ← Total + StudentMark

NEXT Counter

Average ← Total / ClassSize


Copyright By Mr [Link] 16
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

WHILE … DO … ENDWHILE
The number of repetitions/iterations is not known.
Actions are only repeated WHILE a given condition is true.
WHILE (CONDITION) DO
(STATEMENT TO BE REPEATED)
END WHILE

EX1: Print all numbers from 1 to 10

NUMBER ← 1

WHILE (NUMBER <=10) DO


Output NUMBER

NUMBER ← NUMBER + 1

END WHILE
EX 2: Write a pseudocode which input 5,10,4,-1,9 and displays the number input. The program
will stop when -1 is input.
INPUT NUM
WHILE (NUM <> -1) DO
OUTPUT NUM
INPUT NUM
END WHILE
EX 3: write a pseudocode to check a mark which must be between 0 and 100. if the correct mark
is less than 40, output “fail”. else output “pass”.
INPUT MARK

WHILE (MARK >=0) AND (MARK <=100) DO

IF MARK < 40 THEN

OUTPUT “FAIL”

ELSE

OUTPUT “PASS”

Copyright By Mr [Link] 17
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

ENDIF
END WHILE

WORK OUT: Change the for loop to a while loop.

FOR x ← 1 TO 50
Count ← ……………..

Input Age while ………………………………….. Do

IF Age < 18 THEN Input Age


IF Age < 18 THEN
PRINT "Child"
PRINT "Child"
ELSE ELSE
PRINT "Adult"
PRINT "Adult"
ENDIF
ENDIF
Count ← ………………………………
NEXT
End while

Copyright By Mr [Link] 18
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

REPEAT … UNTIL
The number of repetitions/iterations is not known
Actions are repeated UNTIL a given condition becomes true
Actions in this loop are always completed at least once.
The condition is checked after the action.
REPEAT
(STATEMENTS)
UNTIL (CONDITION)
Ex 1:
Total 0

Ex2:
REPEAT
PRINT "*"
COUNTER ← COUNTER + 1
UNTIL COUNTER > 10
Ex 3:
REPEAT
INPUT CODE
IF CODE > 999 AND CODE < 2000 THEN BOOKS = BOOKS + 1
ELSE IF CODE > 1999 AND CODE < 3000 THEN MAPS = MAPS + 1
ELSE IF CODE > 2999 AND CODE < 4000 THEN MAGS = MAGS + 1
ELSE PRINT “ERROR IN INPUT”
Copyright By Mr [Link] 19
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

ENDIF:ENDIF:ENDIF
UNTIL CODE = 9999

Work out :write a pseudocode that will input numbers and output the sum of
positive numbers.
Repeat
Input num
Sum← Sum + num

Until num …………


Output sum

End

Work out: 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 the
problem using pseudocode. Use while, repeat and for loop

Work out: 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 using pseudocode.
NOTE: It is much easier in this example to input x first and then loop round doing the calculation until
eventually x = 0. Because of this, it would be necessary to input x twice (i.e. inside the loop and outside
the loop). If input x occurred only once it would lead to a more complicated algorithm.
(Also note in the algorithm that <> is used to represent ≠ ).
A while loop is used here, but a repeat loop would work just as well.

Work out: 3
Write an algorithm using pseudocode which takes temperatures input over a 100 day period (once per
day) and output the number of days when the temperature was below 20C and the number of days when
the temperature was 20C or above.
(NOTE: since the number of inputs is known, a for … to loop can be used. However, a while loop or a
repeat loop would work just as well).

Work out: 4
Write an algorithm using pseudocode which:
• inputs the top speeds of 5000 cars
Copyright By Mr [Link] 20
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

• outputs the fastest speed and the slowest speed


• outputs the average speed of all the 5000 cars
(NOTE: Again since the actual number of data items to be input is known any one of the three loop
structures could be used. It is necessary to set values for the fastest (usually set at zero) and the slowest
(usually set at an unusually high value) so that each input can be compared.
(5) The following section of pseudocode inputs 1000 numbers and then outputs how many were negative,
how many were positive and how many were zero.
Locate the 3 errors and suggest a corrected piece of code.
1 negative = 1: positive = 1
2 for x = 0 to 1000
3 input number
4 if number < 0 then negative = negative + 1
5 if number > 0 then positive = positive + 1
6 endif
7 endif
8 next
9 print negative, positive

(6) The following section of pseudocode inputs rainfall (in cm) for 500 days and outputs the average
rainfall and the highest rainfall input.
Locate the 3 errors and suggest a corrected piece of code.
1 highest = 1000
2 days = 1
3 while days > 0
4 input rainfall
5 if rainfall > highest then highest = rainfall
6 endif
7 total = total + rainfall
8 days = days + 1
9 average = total/500
10 endwhile
11 print average, highest

(7) 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.
Locate the 3 errors and suggest a corrected piece of code.
1 input n
2 for mult = 1 to n
3 sum = 0
4 sum = sum * mult
5 result = n/sum
6 next
7 print result

(8) As part of an experiment, a school measured the heights (in metres) of all its 500 students.
Copyright By Mr [Link] 21
Computer science O Level - unit 7- Pseudocode prepared by Mr [Link]

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.

(9) 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 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.

(10) 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 outputs the
number of cards, sweets, stationery and toys.

End

Copyright By Mr [Link] 22

You might also like