Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
28 views
Chapter 14
Uploaded by
Adnan Saleem
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
Download now
Download
Save Chapter 14 For Later
Download
Save
Save Chapter 14 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
28 views
Chapter 14
Uploaded by
Adnan Saleem
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
Download now
Download
Save Chapter 14 For Later
Carousel Previous
Carousel Next
Save
Save Chapter 14 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 16
Search
Fullscreen
Chapter 14 Structured Programming By the end of this chapter you should be able to: Use a procedure and explain where in the construction of an algorithm itis appropriate to use a procedure show understanding of passing parameters by reference and by value Use a function and explain where in the construction of an algorithm itis appropriate to use a function se the terminology associated with procedures and functions: procedure/function header, procedure/ function interface, parameter, argument, return value show understanding that a function is used in an expression ‘write programs containing several components and showing good use of resources.Tee Ceasar Cu 14.01 Terminology Different programming languages use different terminology for their subroutines, as listed in Table 14.01 Pseudocode PROCEDURE FUNCTION Python wid function fruitful funation vs. Subroutine Function Pascal procedure function Table 14.01 Programming language terminology for subroutines 14.02 Procedures In Chapter 12 (Section 12.02], we used procedures as a means of giving a group of statements ‘2 name. When we want to program a procedure we need to define it before the main program. We call itin the main program when we want the statements in the procedure body tobe executed. Inpseudocode, a procedure definition is written as: PROCEDURE
() // this is the procedure header estatementisl> i these statements are the procedure body ENDPROCEDURE This procedure is called using the pseudacode statement: CALL
() Python Get
‘VB.NET Sub
() estatement(e)> fend sub Pascal procedure
; lends When programming a procedure, note where the definition is written and how the procedure is called from the main program. Code examples Hereis an example pseudocode procedure definition PROCEDURE Inputoddwunber() REPEAT INPUT "Enter an odd number: " Number UNTIL Number MOD 2 = 2 -ENDPROCEDURE This procedures called using the cau statement: CALL Inputoddsumber()er aa eur! Python DO recesuresamolesy c/vsen/syival lyf Rec roma -fay One“ es i Se eneoemerer ot a eg Number = int (input ("! cer an odd number: + * main program starts here * ‘InputOddumber () ani Figure 14.01 The Python editor with a procedure The Python editor colour-codes the different parts ofa statement. This helps when you are typing your own code. The indentation shéws which statements are part of the loop. The built-in function input returns a string, which must be converted to an integer before it can be used as a number, VB.NET [orca ecerencern alata Fe eit ver ot Bap Oo Ta Seee ret ied osha "Etar a ot ae brent) ortaaumber( Soest) —————| Figure 14.02 The Visual Basic Express editor with a procedure The Visual Basic Express editor colour-codes different parts of the stateme soitis easy to see if syntax errors are made. The editor also auto-indents and capitalises keywords Variables need to be declared before they are used, The editor will follow the capitalisation of the variable declaration when you type an identifier without following your original capitalisation The editoris predictive: pop-up lists will show when first partofa stement, jou type th When you execute the Main program, console. Readbine() keeps the run-time window open.sete ard Figure 14.03 The Pascal editor with a procedure The Pascal editor automatically emboldens keywords The procedure body is enclosed within begin and end statements. There is no semicolon after the keywords begin or repeat. Variables need to be declared before they are used When you execute the main program, Readnn keeps the run-time window ‘open. The main program finishes with ena, (note the full stoo). TASK14.01 \Wirte program code to implement the pseudocode from Worked Example 12.02 in Chapter 12. 14.03 Functions In Chapter 13 (Section 13.08), we used built-in functions. These are useful subroutines written by other programmers and made available in module libraries. The most-used ones are Usually in the system library, 50 are available without having to explicitly import them, You can write your own functions. Any function you have written can be used in another program if you build up your own module library. function is used as partof an expression. When program execution gets to the statement. that includes a function call as part ofthe expression, the function is executed. The value returned from this function cal is then used in the expression. When writing your own function, ensure you always return a value as part of the staternents that make up the function (the function body). You can have more than one RETURN statement ifthere are different paths through the function body.Cambrid ECE UT ENC Ceca sca act in pseudocode, a function definition is written as: FUNCTION
() RETURNS
// function header
// function body RETURN
ENDPROCEDURE Syntax definitions Python Je ~
-estatement(e)>
=
‘Return
End Function Pascal function
; evalues: ena; When programming a function, the definition is written in the same place asa procedure. The the main program, or in a procedure. inction is called from within an expression Code example \We can write the example procedure from Section 14.02 as a function. In pseudocode, this is FUNCTION Inputoddiumber() RETURNS INTEGER REPEAT INPUT "Enter an odd number: " Number UNTIL Wunber MOD 2 = 1 RETURN Wunber | EQS lolx) Fle Edt Format Run Options Windows Help def InputOddNamber ( Number = 0 voile Mumber & 2 | amber = int (inpac (" an odd number: ")) = Number |# teseeeees main program starts here | NewNumber = InpucOddWumber () fneioao Figure 14.04 The Python editor with a function and local variable | ‘The variable tanber in Figute 14.04 is not accessible in the main program, Python's variables are focal unless declared to be globalChapter 14: Structured Programming ) eT i) se ar Nae ere . enter «roster sb min Figure 14.05 The VB.NET editor with (a) global variables and (b) a local variable as.a global variable atthe start ofthe module. This |s a local variable within the function. is not good programming practice. The variable number in Figure 1405(a) is declared _| in Figure 14,05(b), the variable wunber is declared Pascal Neal Figure 14.06 The Pascal editor with (a) global variable and (b) local variable asa global variable, outside the function. Thisis | asa local variable within the function. not goad programming practice. The variable Number in Figure 14.06(a)s declared _|in Figure 14.06(), the variable munber is declared global variable is available in any part of the program code. Itis good programming Practice to declare a variable that is only used within a subroutine as a local variable. In Python, every variables local, unless itis overridden with a global declaration, In VB.NET and Pascal, you need to write the declaration statement for a local variable within the subroutine.TEN cau ca tas TASK14.02 \Write program code to implement the pseudocode from Worked Example 12.03 in Chapter 12. The global and local variables are listed in Table 12.11. 14.04 Passing parameters to subroutines When a subro tine requires one or more values from the main program, we supply these as arguments to the subroutine at call time. This is how we use builtin functions. We don't need to know the identifiers used within the function when we call a built-in function, When we define a subroutine that requires values to be passed to the subroutine body, we Use a parameter lst in the subroutine header. When the subroutine i called, we supply the arguments in brackets. The arguments supplied are assigned to the corresponding parameter of the subroutine (note the order ofthe parameters in the parameter lst must be the sameaas the order in the list of arguments). This is known as the subroutine interface. 14.05 Passing parameters to functions The function header's written in pseudocode as: FUNCTION
(cparaneterList>) RETURNS
where
(
) The parameter list needs more information for a procedure definition. In pseudocode, a parameter n the list is represented in one of the following formats: BYREF
:
BYVAL
:
Passing parameters by value The pseudocode for the pyramid example in Chapter 12 (Section 12,04) includes a procedure definition that uses two parameters passed by value. We can now make that explicit PROCEDURE Outputsynbols(BYVAL NumberofSymbols + INTEGER, BYVAL Symbol : CHAR) DECLARE Count : INTEGER FOR Count + 1 70 Numberosymbole OUTPUT symbol // without moving to next line ENDFOR OUTPUT NewLine ENDPROCEDURE In Python (Figure 14.10), all parameters behave like local variables and their effec though they are passed by value, Proceduretxample.py - :/Users/Syiia/ tty Brogeail =lDixI) Fle Edt Fomat fun Optons Windows Hep [set oucpucsymbols Mimber0fSymbois, Symbol) 2 Count in range (unberorsymbole) : srint (Symbol, end") | oucpucsymbois (5, *=") Figure 14.10 Parameters passed to a Python subroutineCes Mace ac uu In VB.NET (Figure 14.11), parameters default to passing by value. The keyword ByVal 1s automatically inserted by the editor. Seeman te (Dg ds eo sh anutsntlsoyn nabetenls, ty sel) for Cunt 2 Te nbertsetelt Stn ettetoat ea tenet) 0 pain’) Sretsmotes, =) etactentticg, ‘ Figure 14.11 Parameters passed by value to a VB.NET procedure In Pascal (Figure 14.12), there is no keyword for passing by value. This i the default method. Figure 14.12 Parameters passed by value to a Pascal procedure Passing parameters by reference The pseudocode for the pyramid example generated in Chapter 12 Section 12.04) includes a procedure definition that uses two parameters passed by reference. We can now make that explicit: PROCEDURE AdjustValuesForNextRow(BYREF Spaces : INTEGER, BYREF Symbols : INTEGER) spaces « Spaces - 1 symbols « symbols + 2 ENDPROCEDURECambridge International AS The pseudocode statement to call the procedure is: CAUL AdjustValueeForNextRow(MumberOfSpaces, NumberOsSymbols) Python does not have a facility to pass parameters by reference. Instead the subroutine behaves as a function and returns multiple values (see Figure 14.13). Note the order of the ceive these values. the main part ofthe program, ables as they Prone. ers sye [Hy Prgraning/ CE Aoh/ CN lee alo EE Foret a Coens Wiest al © AdjustValueaForNextRaw (Spact | spaces ~ Spaces 2 symbole = Symbols + 2 eerurs Spaces, Symbols | teeeseeeronain program starts here cient Mamberorspaces = snt(sapst()) NonberOfSymbole = ine (input()) ; NumberCrSymbcle ~ AdjuetValueaforNextRaw thmberofSpaces, MusberOfSymbels) (numberofSpaces) Figure 14.13 Multiple values returned from a Python subroutine This way of treating a multiple of values as a unitis called a tuple. This concept is beyond the find out more by reading the Python help files. 5 scope of his book. You In VB.NET (Figure 16.14), the ByRe€ keyword is placed in front ofeach parameter to be passed by reference. ++ sacar Se, tt Ee) supine 2 Serene corciceatne) on = Figure 14.14 Parameters passed by reference to a VB.NET procedureChapter 14: Structured Programming In Pascal (Figure 14.15), The keyword vars placed in front ofthe declaration of parameters to be passed by reference. Drogran Pregect2 var Munzez0eSpaces, lunbeco#symbols : integers procedure AayuetvelserFortenciow var Sp ‘begin ‘spaces 1 spaces - Symbole = Symbols + 25 Symeie + snvegeny: \// seensesesmmain progres starts here st+sssesseees Reacin tumnezofspeces)* Readin Wanbesofsyabeis) AajustVatuesFortensiow RunmeroeSpaces, RnberoeSmbele) + essed itexberotspaces) , ee a " TASK.14.04 1 Write program code to implement the structure chart from Figure 12.02 in Chapter 12 {forthe average of two numbers. 2. Write program cade to implement the structure chart from Figure 12.03 in Chapter 12 {forthe number guessing game 3 Amend your program code from Task 14.02 to implement theinterface shown in the structure chat from Figure 12.5 in Chapter 12. ‘The programs in this section are full solutions to the pyramid-drawing program developed in Chapter 12 (Section 12.04) ‘The parameters of the subroutines have different identifiers from the variables in the main program. Thisis done deliberately, so that itis quite clear that the parameters and local variables within @ subroutine are separate from those in the calling program or module Ifa parameter is passed by reference to a procedure, the parameter identifier within the procedure references the same memory location as the variable identifier passed to the procedure as argument. ; ; , ; 14.07 Putting it all together :Cambridge International AS and A level Computer Science The pyramid-drawing program in Python VB.NET and Pascal Python] pack =" | # constant ef InputMaxdiunberOfSynbola() Number = 0 while Number ¥ 2 print ("How many symbole make the base?") Nunber = int(input("Input an odd number: ")) return Number to give @ space @ mane def setvalues(): Symbol = input(tWhat symbol do you want to use? *) MaxSymbols = InputNaxumberOrsynbcls() Spaces = (axSynbols + 1) // 2 symbols = 1 Symbol, MaxSymbols, Spaces, Synbols def Outpuchars(Number, symbol): Count in range (Number): print (symbol, ent def Adjust. spaces | symbols det main’) Thissynbol, MaxVunberOfSynbols, MumberOfSpaces, MunberOfSynbols = while NunberOfsymbols <= MaxNunberofsymbots: OutputChare(tlunberOfspaces, SPACE) Outputchars(NunberOfsymbole, Thissymbol) print() # move to new line NumberOfSpaces, MumberOfsynbols = AdjustValuesForlextRow jMumberOfspaces, maint) Nunberofsymbols) VB.NET) niodule Const space ‘constant to give a space a name Dim NumberOfspaces, NunberOfsymbole As Integer | Dim MaxNunberofsymbols As Integer Dim Thiesymbol As cha: Sub InputMaxNunberOfsymbole(ByRef Number As Integer) Do bole make the base?") fe an odd numb Number = ReadLine() Loop Until (umber Mod 2 = 1) Bnd sub Sub SetValues(ByRef symbol, ByRef MaxSymbols, ByRef Spaces, ByRef Symbols) IWrite(*what symbol do you want to use? symbol = ReadLine() InputMaxMunberOfSymbols(MaxSynbols) Spaces = Maxsymbols + 1) \ 2 Symbols = 1 Bnd subies Ces a ae Sub Outputchars(yVal Number, ByVal symbol) Dim Count As Integer For Count = 1 To Number serite(symbol) Next End sub Sub AdjustValuesForNextRow(ByRef Spaces, ByRet Symbols) Spaces = spaces ~ Symbols = Symbols + 2 End sub sub main() SetValues(Thissymbol, MaxNumberofSymbols, NunberOtspaces, Nunberofsynbols) Do Outputchars(Numberofspaces, space) OutputChars(NumberOfsymbols, Thissymbol) e.WriteLine() ‘move to new line AdjustValuesForNextRow(Nunberofspaces, NunberOfsynbols) Loop Until NumberOfSynbols > MaxNunberofsynbols -ReadLine() End sub End Module Pascal [program Project2; {sappryee consour} Sysutils; const space = ' '; // constant to give a space a name var NunberOfspaces, NumberOfsymbols : integer var MaxNumberOfsymbols + integer: var SymboleThissymbol : char; [procedure InputliaxNumberofsynbole(var Number : integer); begin repeat WriteLn(‘Kow many symbols make the base?!); Write(‘Input an odd number: "); Readin (Number): until Number MoD 2 end [procedure SetValues(var Symbol : char; var MaxSynbols, Spaces, Symbols : integer); begin Write(‘What symbol do you want to use? ‘J ReadLn(Symbol); InputNaxNumberOfSymbols(Maxsymbols); Spaces i= (MaxSymbols + 1) DIV 2; Symbols := 1 fend[procedure OutputChars(Nunber : Integer; Symbol + hari; fvar Count : integer begin for Count := 1 to Number do Write (Symbol); ena Procedure AdjustValuesForNextRow(var Spaces, Symbols : integer); begin Spaces := Spaces - 1; Symbols := Symbols + 2; end: Uf seeeteeees main program starts here sereeesenees begin SetValues(Thissynbol, MaxNunber0fSynbols, NumberOfSpaces, NunberOfSynbols); repeat, Outputchars(Nunberotspaces, space); OutputChars(NunberOfsynbols, Thissymbol); Writein; // move to new line Adjust ValuesForNextRow(NumberofSpaces, NunberofSymbols); until Wunberofsymbols > MaxNunberofsymbole; Readin; // to keep the window open end. Discussion Point: replaced by a single proce he two proce itho Declaration of subroutines (tunctions and procedures is done before the main program body. Calling procedure is a program statement. Calling 2 function s done within an expression, for example an assignment. VB.NET and Pascal functions return exactly one value Parameters can be passed toa subroutine. This is known as the interface. VB.NET and Pascal pass parameters by value, as a default, but can return one or more values via parametersifthey are declared as reference parameters. InPython, parameters can only pass valuesinto a subroutine. The only way to update a value ofa variblein the calling Program is to return one or more values from a function \When a subroutine is defined, parameters are the ‘placeholders’ for values passed into a subroutine. ‘Arguments are the values passed to the subroutine when itis called.er ep Casati Lacuna Exam-style Questions 1. Write program code fora procedure outputtimestable that Lakes one integer parameter,n, and outputs the times table forn For example the procedure call outputtimestable(s) should produce: FA 15 20 25 30 35 40 a5 50 (6) Pererreers 2. Write program code fora function tepivieible() that takes two integer parameters, and y. The function isto return the value True or False to indicate whether xis exactly divisible by y- For example, tepivisibie(24, 6) should fetun Trueand Sepivieinie(24, 7) should return False. io) 3. Apoultry farm packs eggs into egg boxes. Each box takes six eggs. Boxes must not contain fewer than six eggs. ‘Write program code fora procedure BggatntoBoxes that takes an integer parameter, NumbexofEgga, The procedure isto calculate how many egg bores can befiled withthe given number of eggs and how many eggs willbe leftover, The procedureis to return two values as parameters, tunberofBoxes and EggsLeftover. 31
You might also like
CPT 168 HW#9 Answer Key
PDF
50% (4)
CPT 168 HW#9 Answer Key
14 pages
Computer Science Coursebook-219-234
PDF
No ratings yet
Computer Science Coursebook-219-234
16 pages
8.1.6 Procedures and functions, Library Routines, Local and Global Variables
PDF
No ratings yet
8.1.6 Procedures and functions, Library Routines, Local and Global Variables
22 pages
Interest of Procedural Programming: Solution: Idea
PDF
No ratings yet
Interest of Procedural Programming: Solution: Idea
7 pages
LBEPS Session 18
PDF
No ratings yet
LBEPS Session 18
27 pages
HND PRG W4 Algorithms With Pseudocode
PDF
No ratings yet
HND PRG W4 Algorithms With Pseudocode
19 pages
console application
PDF
No ratings yet
console application
11 pages
CH 04 - PL
PDF
No ratings yet
CH 04 - PL
28 pages
Types of Subprograms
PDF
No ratings yet
Types of Subprograms
255 pages
ADS_II Course Chapter_2 Modularity (Func Proc)
PDF
No ratings yet
ADS_II Course Chapter_2 Modularity (Func Proc)
47 pages
UNIT 4
PDF
No ratings yet
UNIT 4
20 pages
Sub Programming - Intro and Procedures
PDF
No ratings yet
Sub Programming - Intro and Procedures
4 pages
Notes For Structured Programming, Procedure and Function: Components
PDF
No ratings yet
Notes For Structured Programming, Procedure and Function: Components
5 pages
Chapter 7 Functions
PDF
No ratings yet
Chapter 7 Functions
37 pages
Functions
PDF
100% (1)
Functions
18 pages
String Handling Procedures & Functions File Handling Library Routines Local & Global Variables Maintaining Programs
PDF
No ratings yet
String Handling Procedures & Functions File Handling Library Routines Local & Global Variables Maintaining Programs
22 pages
Functions and Procedures
PDF
No ratings yet
Functions and Procedures
11 pages
Functions
PDF
No ratings yet
Functions
59 pages
PPL Unit 3
PDF
No ratings yet
PPL Unit 3
24 pages
CS Notes
PDF
No ratings yet
CS Notes
6 pages
Problem_Solving_class
PDF
No ratings yet
Problem_Solving_class
24 pages
Chapter 06
PDF
No ratings yet
Chapter 06
49 pages
Ppl-Unit-3 R16
PDF
No ratings yet
Ppl-Unit-3 R16
24 pages
5. Functions and Arrays
PDF
No ratings yet
5. Functions and Arrays
11 pages
Computer Science Coursebook-235-252
PDF
No ratings yet
Computer Science Coursebook-235-252
18 pages
Chapter 5
PDF
No ratings yet
Chapter 5
34 pages
Lec 7 - Functions
PDF
No ratings yet
Lec 7 - Functions
56 pages
Week 5_slides
PDF
No ratings yet
Week 5_slides
44 pages
Problem Solving
PDF
No ratings yet
Problem Solving
12 pages
Paper 2 part 7
PDF
No ratings yet
Paper 2 part 7
7 pages
Real Pascal Programming Notes
PDF
No ratings yet
Real Pascal Programming Notes
38 pages
BUE Lec5-Functions I
PDF
No ratings yet
BUE Lec5-Functions I
56 pages
Programming (3)
PDF
No ratings yet
Programming (3)
36 pages
ECE151 - Lecture 6
PDF
No ratings yet
ECE151 - Lecture 6
78 pages
PPL Unit 3 R2021
PDF
No ratings yet
PPL Unit 3 R2021
31 pages
ch9 2
PDF
No ratings yet
ch9 2
62 pages
Functions and Arrays
PDF
No ratings yet
Functions and Arrays
11 pages
Qbasic
PDF
0% (1)
Qbasic
11 pages
Functions
PDF
No ratings yet
Functions
4 pages
1. Python - Arrays, Procedures & Functions (Inc Linear & Bubble) - Student (2)
PDF
No ratings yet
1. Python - Arrays, Procedures & Functions (Inc Linear & Bubble) - Student (2)
237 pages
Revision Notes - 38 Functions and Procedures (1)
PDF
No ratings yet
Revision Notes - 38 Functions and Procedures (1)
14 pages
VHDL PDF
PDF
No ratings yet
VHDL PDF
250 pages
Lecture7 Function Part1
PDF
No ratings yet
Lecture7 Function Part1
44 pages
PPT ch06
PDF
No ratings yet
PPT ch06
50 pages
Chapter 3 - Principles of Programming Languages
PDF
100% (1)
Chapter 3 - Principles of Programming Languages
17 pages
PPL-Unit 3 Part 1
PDF
No ratings yet
PPL-Unit 3 Part 1
20 pages
PROCEDURES QUESTIONS
PDF
No ratings yet
PROCEDURES QUESTIONS
11 pages
2ch8 - Procedures Functions Arrays & File Handling
PDF
No ratings yet
2ch8 - Procedures Functions Arrays & File Handling
35 pages
Answer Keys Computing T2 Grade 8 Theory Questions
PDF
No ratings yet
Answer Keys Computing T2 Grade 8 Theory Questions
17 pages
Theory p2
PDF
No ratings yet
Theory p2
24 pages
SSC Gr10 ICT Q4 Module 4 WK 5 - v.01-CC-released-15June2021
PDF
No ratings yet
SSC Gr10 ICT Q4 Module 4 WK 5 - v.01-CC-released-15June2021
13 pages
Cs Practical Full
PDF
No ratings yet
Cs Practical Full
38 pages
CS-602 PPL Unit-3
PDF
No ratings yet
CS-602 PPL Unit-3
17 pages
9 - Subroutines - 1
PDF
No ratings yet
9 - Subroutines - 1
26 pages
Online Class -X.pptx First [Autosaved]
PDF
No ratings yet
Online Class -X.pptx First [Autosaved]
33 pages
Quantum Cryptography
PDF
No ratings yet
Quantum Cryptography
6 pages
Supervised, Unsupervised & Reinforcement Learning
PDF
No ratings yet
Supervised, Unsupervised & Reinforcement Learning
11 pages
Dijkstra's Algorithm
PDF
No ratings yet
Dijkstra's Algorithm
4 pages
As Computer Science Topical Paper 1 Final 20181
PDF
No ratings yet
As Computer Science Topical Paper 1 Final 20181
467 pages
Chapter 12
PDF
No ratings yet
Chapter 12
21 pages
Chapter 11
PDF
No ratings yet
Chapter 11
30 pages
Javascript Tutorial: Examples in Each Chapter
PDF
No ratings yet
Javascript Tutorial: Examples in Each Chapter
285 pages
2 4 Algorithm Design Methods Key
PDF
No ratings yet
2 4 Algorithm Design Methods Key
11 pages
Book1 (AutoRecovered)
PDF
No ratings yet
Book1 (AutoRecovered)
1 page
"Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"
PDF
No ratings yet
"Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"
2 pages
9608 w20 PM 22 Pseudocode
PDF
No ratings yet
9608 w20 PM 22 Pseudocode
3 pages