0% found this document useful (0 votes)
20 views12 pages

Pseudo Code

This document provides an overview of pseudocode and flowcharts, detailing their use in representing algorithms clearly and concisely. It covers various programming constructs such as assignment, conditional statements, loop structures, and input/output statements, along with examples and standard flowchart symbols. The chapter emphasizes the importance of consistent formatting in pseudocode to enhance understanding and includes activities for practical application.

Uploaded by

kemisoabigail1
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)
20 views12 pages

Pseudo Code

This document provides an overview of pseudocode and flowcharts, detailing their use in representing algorithms clearly and concisely. It covers various programming constructs such as assignment, conditional statements, loop structures, and input/output statements, along with examples and standard flowchart symbols. The chapter emphasizes the importance of consistent formatting in pseudocode to enhance understanding and includes activities for practical application.

Uploaded by

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

@ Pseudocode and flowcharts

lnthischapteryouwilllearnabout:
e thepseudocodelorassignment,using<-
• thepseudocodelOfconditionalstatements
IF ·- TIIEN - ELSE ·- ENDIF
CASE ·- OF - OTHERWISE ·- ENDCASE
e thepseudocodelorloopstructures
FOR._TQ_NEXT

WHILE ·- DO ·- ENDWHILE
e thepseudocodelOfinputandoutputstatement:5
INPUT and OU'JPUI
{e.g. READ and PRINT)
e thepseudocodelorstandardactions
totalling(e.g. Sum .. SUlll + Number)
counting(e.g.Count .. count+l}
• the standard llov,diart symbols for the above statements, commands and structures .)

10.1 Introduction
Using pscudocodc is a clear and concise way to represent an algorithm. Data
items to be processed by the algorithm arc given meaningful names in the same
way that variables and constants are in a high -level programming language.
Pseudocode is not bound by the strict syntax rules of a programming language.
It does what its name sa)'Si it pretends to be programming code!
To ensure that pseudocode is easily understandable by others it is useful to be
consistent in the way that it is written. The pseudocode in this book is written in
the following way to help you understand the algorithms more easily:
• Courier New font is used throughout
• all keywords (words used to describe a specific action (e .g. INPUT) are written
in capital letters
• all names given to data items and sub -routines start with a capital letter
• where conditional and loop statements arc used, repeated or selected statements
are indented by two spaces.

10.2 Assignment
Values arc assigned to an itcm/\'ariable using the - operator. The 'lariable on the left
of the - is assigned the w.lue of the expression on the right. 111c expression on the
right can be a single \'alue or se\'cral \'alucs combined with mathematical operators.
Table10 1 Mathematicajope,ators
Operator

rrultiply

raisetothepowe,
() ()'()Up
10.3 Conditional statements

Examples of pseudocode assignments:


Cost has the value 10
Price <- Cost * 2 Price has the value 20
Tax <- Price * 0 .12 Tax has the value 2.4
SellingPrice <-Price+ Tax SellingPricehasthevalue22.4
Gender <- "M" Gender has the value M
Chosen <- False Chosen has the value False

Activity 10.1
W'hat values will the following variables have alter the aslignmeot:5 have been completed?

10.3 Conditional statements


\Vhen different actions are performed by an algorithm according to the \'alues of
the variables, conditional statements can be used to decide which action should
be taken.
There are two types of conditional statement as shown below with an example
of eac h.
• A condition that can be tru e or false: IF ·- THEN -· ELSE ... ENDIF, for
example

• A choice between several different values: CASE ·- OF -· OTHERWISE .


ENDCASE, for example

_,. "'""" o,
"A" PRINT "Excellent"

: PRINT "Average"
OT HERWISE PRINT "Improvement is needed"
ENDCASE

10.3.1 IF ... THEN ... ELSE ... ENDIF


For an IF condition the THEN path is followed if the condition is true and the
ELSE path is followed if the condition is false. There may or may not be an ELSE
path. The end of the statement is shown by ENDIF.
10 PSEUDOCODE AND FLOWCHARTS

A condition can be set up in different ways:


• Using a Boolean variable that can have the value TRUE or FALSE (see
Section 11.4 for details of Boolean variables). For example

THEN PRINT "Your search was successful"


ELSE PRINT "Your search was unsuccessful"

• Using comparison operators, as shown in Table 10.2. Comparisons arc made


from left to right, for example A > 8 means is A greater than B. Comparisons
can be simple or more complicated. For example

Table102Conva,isonq,e<al<ITT
Operator Comparison
l areate,lhan

1..-eate,thano,eaual
lesslhaoorequaj
notequaj
() I CJ"oup

1l1e algorithm below checks if a percentage mark is valid and a pass or a fail. 1l1is
makes use of two IF statements. The second IF statement is part of the ELSE
path of the first IF statement. This is called a nested IF.

IliPUTPercentageMa rk

IFP<,rcentagellark<OORPercentageMark>lOO

IFPe rce nt a g e Ma rk>4i


;.1:h~== ;;: ;'."'t
greate,lhanah\ll>dred
be

Thisisanesll'dIFstatementshown
de,.-tybylhellSeofaserondlevei
ofiodentation .The percMtagemark
isontytestedifjtisintheror,ectraoge

Figure10.1

Activity 10.2
Change the algorithm to check fora mark between O and 20 and a pass markol 10. Decide
what normal. bo\lndary and erroneous data you will need to l\llly test yom algorithm
10.4 Loop structures

10.3.2 CASE ... O F .. . OTH ERWISE ... ENDCASE


For a CASE condition the value of the variable decides the path to be taken.
Several values arc usually specified. OTHERWISE is the path taken for all other
values. The end of the statement is shown by ENDCASE.
The algoritlun below specifics what happens if the value of Choice is l , 2, 3
or 4.

CASE Choice OF
1 : Answer .. Numl + Num2
2 : Answer .. Numl - Num2
3 : Answer .. Numl * Num2
4 : Answer .. Numl I Num2
OTHERWISE PRINT "Please enter a valid choice"

Activity 10.3
Use a CASE statement to di~laythe day of the week ii the variable DAY has the value 1 to 7
and an error otherwise

10.4 Loop structures


\\'h en some actions performed as part of an algoritlrn1 need repeating, this is
called ' iteration'. Loop structures arc used to perform the iteration.
There arc three different types ofloop structure:

Operator Comparison

A ,epetitioo. where the numbe, of repeats is


notknown.ttlatiscompletedatleastonce
A ,epetitioo. where the numbe, of repeat, is WIIILE - · 00 ·- ENDWHILE
not known. ttlatmayneverbecompleted

All types ofloops can perform the same task, for example printing 10 stars.

FOR Counter .. 1 TO 10 · i
!
Counter .. Counter + 1
UNTIL Counter > 10
I
Counter .. o !
WHILE Counter c: 10 DO I
!
:
The FOR ... NEXT loop is the most efficient for this type of task.
10 PSEUDOCODE AND FLOWCHARTS

10.4.1 FOR ... TO ... NEXT


A variable is set up with a start value and an end value and then incremented in
steps of one until the end value is reached and the iteration finishes. The variable
can be used within th e loop so long as its value is not changed. This type of loop
is very useful forreadingvaluesintolists.

Figure10.2

10.4.2 REPEAT ... UNTIL


l11is loop structure is used when the numbe r of repetitions/iterations is not
known and the actions arc repeated UNTIL a gi\·cn c.ondition becomes true.
111c actions in this loop are always completed at least once.

Totalo- 0 ~

Mark..-0 ~

PRIN'T ' Rnter valuefor mark , - ltofiniah •

InputMa rk ~

UNTIL!lark - - 1 ~

Figure10.3

10.4.3 WHILE ... DO ... ENDWHILE


This loop structure is used when th e number of repetitions/iterations is not
known and the actions arc only repeated WHILE a given condition is true. If
the WHILE condition is untrue when the loop is first entered then the actions
in the loop arc never performed.

To t a l o - 0 ~
PRIIIT ' Rnt e r val u efor ...,rk , - ltofinioh•

Input Mark

Figure10.4
10.5 Input and output statements

Activity 10.4
a Writepseudocodetoinput10pos.itivenumbersandfindthetotalandtheaverage
b Writepseudorndetoinputpositivenumbers, - 1tolini~.andlindthetotalandtheaverage
c Explainwhyyouchos.etheloop1tructuresloreachta1k

10.5 Input and output statements


INPUT and OUTPUT are used for the entry of data and display of information.
Sometimes READ can be used instead of INPUT; this is usually used for reading
from files, which is not covered in this textbook. Frequently PRINT is used
instead ofOUTPUT.
INPUT is used for data entry. It is usually followed by a variable where the data
input is stored, for example :

OUPUT/PRINT is used to display information ei ther on a screen or printed on


paper. It is usually followed by a single value that is a string or a variable or a list
of values separated by commas, for example :

10.6 Standard actions


The ability to repeat actions is very important in the design of algorithms. When
an algorithm is mrned into a program the same set of actions may be repeated
many thousands of times, for example, keeping a running total of the value of
goods sold in a supermarket.

:J
i_R_u _n _n _i _n_~ !.o,•l __ : __ Run_n.1.n.~T_o _,.-_1 __ , .. Y•.l_u_e_ ·· ·· · · · ·· ·· ·· · · · ·· ·· · · · ·· ·· ·: .:..: : :: : ..

Keeping a count of the number of times an action is performed is another


standard action, for example:

Counting is also used to count down until a certain value is reached, for example
the number of items in stock in a supermarket:

!Nl:l~e;:i_nStock _.. Nu~errn.St_o_ck _ - .. 1 - -····----·-·-·-- ·-·-·---· · ····--···-·__]

10.7 Examples of algorithms in pseudocode


Exa mple 1
Tickets are sold for a concert at $20 each. If 10 rickets are bought then the
discount is 10%; if20 rickets are bought the discount is 20%. No more than
25 rickets can be bought in a single transaction.
10 PSEUDOCODE AND FLOWCHARTS

a Use pseudocode to write an algoritlun to calculate the cost of buying a given


number of tickets.
b Explain how you would test your algorithm.

b Would use test data with values of


0 , 26 Expected result rejected
I , 25 Expected results 20,400
9, 10 Expected results 180, 180
19 , 20 Expected results 342, 320

Activity 10.5
ForthetestdatagiveninEXilmple1,identifythetypeoltest
datausedandsuggesl'iOmemoretestdata

Examp le 2
A school with 600 srudents wants to produce some information from the results of the
four standard tests in Maths, Science, English and IT. Each test isoutof lOO marks.
The information output should be the highest, lowest and average mark for each
test and the highest, lowest and average mark o;erall. All the marks need to be input.
a Use pseudocode to wri te an algorithm to complete this task.
b Explain how you would test your algoritlun.
10.7 Examples of algorithms in pseudocode

SubjectLowest .. 100
SubjectTotal .. o
CASE Test OF
1 : SubjectName .. "Maths"
: SubjectName .. "Science"
: SubjectName .. "English"
4 : SubjectName .. "IT"
OTHERWISE

FOR StudentNumber .. 1 TO 600


REPEAT
PRINT "Enter Student", StudentNumber,""s mark for",

UNTIL Mark c: 101 AND Mark > ~1


IF Mark c: OverallLowest THEN OverallLowest .. Mark
IF Mark c: SubjectLowest THEN SubjectLowest ... Mark
IF Mark > OverallHighest THEN OverallHighest .. Mark
IF Mark > SubjectHighest THEN SubjectHighest .. Mark
OverallTotal .. OverallTotal + Mark
SubjectTotal ... SubjectTotal + Mark
NEXT
SubjectAverage .. SubjectTotal/600
PRINT SubjectName
PRINT "Average is", SubjectAverage
PRINT "Highest Mark is", SubjectHighest
PRINT "Lowest Mark is " , SubjectLowest

; ov,,callAv,m,10 .. OverallTotal/2400
Average is", OverallAverage
•overall Highest Mark is", OverallHighest

b For the algorithm to be tested by dry running, it would be a good idea to


reduce the number of students to 5 and the number of subjects to 2.

Activity 10.6
11Identify the changes you would need to make to the algorithm for Example 2 to reduce the
numberofstudentsto5andthenumberofsubjectsto2
b ldeotilythetestdataneededtotestEXilmple2withthereducednumberolstudeotsand
subjects.
c Withthe..etofdatayouhavechosen,setupandcompleteatracetablesothatyoucan
compare your expected results with the actual results when you dry run the algorithm
10 PSEUDOCODE AND FLOWCHARTS

10.8 Standard flowchart symbols


Flowcharts are drawn using standard symOOls.

10.8.1 Begin/End
Terminator symbols are used at the beginning and end of each flowchart.

Figure10.5lermonatofsymbols

10.8.2 Process
Process symbols are used to show when values are assigned to an item/variable
like an assignment in pseudocode.

Figu re 10.6 Proces,,)fflbol

10.8.3 Input/Output
Input/Output symbols are used show input of data and output ofinformarion.

Figure10.7 1nput!Outputsymbol

10.8.4 Decision
Decision symbols are used to decide which ac tion is to be taken next. These can
be used for selection and repetition/iteration.

Figure10.8 0ecisionsymbol

10.8.5 Flow lines


Flow lines are used to show the direction of flow which is usually, but not always,
top to bottom and left to right.

Figu re 10.9Rowline
10.8 Standard flowchart symbols

Exa m ple 1 (co ntinued)


Tickets arc sold for a concert at $20 each, iflO tickets are bought then the
discount is I 0%, if 20 rickets are bought the discount is 20%. No more than
25 tickets can be bought in a single transaction.
c Draw a flowchart for the algorithm to calculate the cost ofbuying a given
number of rickets.

Output • Yourticket o
cost •, co ot

Figur• 10.10Flowd>artforExampje1

Activity 10.7
Draw a flowchart for the algorithm given in
Example 2.
Choosethemethodyouthinkistheclearest
way to show this algorithm and explain why
it is the dearest
10 PSEUDOCODE AND FLOWCHARTS

End-of-chapter questions 5 The temperature in an apartmen t must be kept


betwee n 18°C and 20"C. l fthe temperature reaches
l Show two ways of selecting diffen:nt actions using
22°C then t he fun i.s switched on; if the temperature
pscudocode. reaches 16°C then the he.:iter is switched on,
2 You have been asked to write the pscudocodc to
otherwise: the fun and the heaters arc switched off.
choose the correct routine from the menu shown
The following library routines an: available:
below.
• GctTempcrature
a Decide which type of conditional statement you
• FanOn
a.re going to use:.
• FanOff
b Explain your choice.
• H catcrOn
c Write the psc:udocode. • H caterOff
d Select your test dau and e.~plain why you chose
Write an algorithm, using pscudocodc or a
each value. flowchart, to keep the temperature at th e right level.
6 Daniel lives in Ital y and travels to Me,dco, India
and New Zealand. The time differences arc:
1 Set upnewAccOU'I\
2Mahchangestoan&.istjr.gAccount Country

4V;ewMy Orclers

6Alter..nE!<islingOrde,

Figu .. t0.11
11ms, ifit is 10: 15 in Italy it will be 14:45 in India.
a \\'rite an algorithm, using pscudocode or
3 Show th ree w.:iys a loop to :M:ld up fa·e numbers and oth erwise:, wh ich:
print out the tota l can be sc:t up using pscudocode. • inputs the name of d1e country
E."tplain which lo:i,p is the mos t efficient to use:. • inputs the time in I roly in hours (H ) and
4 A sweet shop sc:lls 500 different sorts of sweets. mi.nutes ( M )
Each sort of sweet is identified by a unique four- • calculates the time in the country input using
digit code. All swt<'ts that start with a one ( I ) a.re the data from the t.1blc
chocolates, all sweets that start with a two (2) an: • outputs the country and the time in hou rs
toffees, all sweets that surt with a three (3 ) an: and minutes. [41
jellies and all other sweets an: miscellaneous and b D escribe:, with examples, two sc:ts of test data
can start with any other digit except zero. you would use: to test your algorithm. [2 1
a Write an algorithm, using a flowchart, which Cambridge !GCSE Computer 5t,.die1 7010/0420
inputs the four-digit cock for all 500 items and Paper JI Q/7 June 2011
outputs th e number of chocobtes, toffees and
jell ies. 7 A school is doing a check on the heights and weights
b Explain how you would test you r flowchart. of all its students. The school has I OOO snidcnts.
c Decide the test data to use and complete a trace Write an algorithm , using pscudocodc o r a
tab le showing a dry run of yo ur flowchart. flowchart,which
• inputs the height and weight of all I OOO students
• outputs the a,·cragc (mean ) height and weight
• includes any necessary error traps for the input
ofhcight and weight. [51
Cnmbridge !GCSE Co,Hp11ter Studie1 7010/0420
Paper 11 Q l 7 November20 10
End-of-chapter questions

8 A small cafC: sells five types of item: 9 5000 numbers are being input which should ha\·e
• bun 0.50 dollars either one digit ( e.g. 5 ), two digits ( e.g. 36), three
• coffee 1.20 dollars digits (e.g . 149 ) or four digits (e .g. 8567).
• cake 1. 50 dollars \Vrite an algorithm, using pseudocode or a
• sandwich 2.10 dollars flowchart only, which
• dessert 4.00 dollars • inputs5000 numbers
Write an algorithm, using pseudocode or a • outputs how many numbers had one digit,
program flowchart only, which two digits, three digits and four digits
• inputs every item sold during the day • outputs the percentage of numbers which were
• uses an item called 'end' to finish the day's input outside the range. [6]
• adds up the daily amount taken for each type of C111nbridge IGCSE Computer Studies 7010/0420
item P11per 13 QlS November2013
• outputs the total takings (for all items added
together) at the end of the day
• outputs the type of item that had the highest
takings at the end of the day. [ 6]
C11mlnidge !GCSE Computer Studies 7010/0420
P11per 13 Ql6 November 2012

You might also like