You are on page 1of 29

Development Software

IB
(DSO17BT)

Basic Programming
Principles

Compiled by
HG Erasmus
CM Pretorius
Adapted by: MG Meintjes & TS Raphiri

All rights reserved. Apart from any fair dealing for the purpose of research
criticism or review as permitted under Copyright Act, no part of this
document may be reproduced or transmitted in any other form or by any
means, electronic or mechanical, including photocopy and recording, without
permission in writing from the publisher.

DSO17BT -1-
Chapter 2

Function Procedures and Sub Procedures


1.1 Introduction

We have seen with the last problems that we have been solving that the algorithms
started to become very long and complex and it became more and more difficult to
consider the problem as a whole. Lines of code that performed a certain task were
often repeated, for instance in different parts of a nested if. We use function
procedures and sub procedures to overcome these problems, making the coding
more effective by breaking the large complex algorithm into smaller manageable
modules. A module can be defined as a sub-part of an algorithm. The process of
dividing the algorithm into manageable parts is called modularization.

When repeating code that performs a certain task, we can place the lines of code in a
separate procedure, writing it once and then calling it whenever it is needed. Long and
complex algorithms can be broken down into smaller manageable tasks. In industry the
applications that are developed are normally huge, and we very often find many
programmers working on the same application, each one developing different
procedures.

Function procedures and sub procedures both perform a task, but a function
procedure will always return a result that has been calculated or determined within
the function.

1.2 Parameters

A parameter is data needed by the function procedure (also called a function) or a


sub procedure to be able to perform the tasks it has to do. It may also contain the
address of a result of the task at hand when dealing with sub procedures.

We have two types of parameters:


 Value parameters
 Reference parameters

1.2.1 Value Parameters

A value parameter contains a value that is sent to the function or sub procedure.
You can look at it as a copy of the value of the variable that is sent to the function or
sub procedure. The function or sub procedure may change the value of the copy of the
variable during execution, but as soon as control is returned to the calling module, the
variable will contain its original value.

Let us use the following analogy: Mrs Mabena is a teacher. Her three children help her
with the processing of the learners in her class’ marks for a test out of 30. She makes

DSO17BT -2-
three copies of the marks written on a piece of paper. Mary is responsible for
calculating the class average of the marks, writing the result on her copy, and then
giving this to Mrs Mabena. Tshepo’s job is to take his copy of the marks, and determine
the name of the student with the highest mark, then give the result on his copy to his
mother. Tumi’s responsibility is to determine each mark as a percentage and write this
onto her copy of the mark sheet. Mrs Mabena still has her original copy. Even though
changes were made to each copy, it did not affect Mrs Mabena’s copy.

When writing an algorithm, we will use the prefix val to indicate that it is a value
parameter.

1.2.2 Reference Parameters

A reference parameter contains the address (position in memory) of a variable.


Only sub procedures use reference parameters. The sub procedure finds the value of
the variable at this address. The sub procedure may change this value, and it will be
changed at this given address. The calling module will then automatically have access
to this updated value.

Let us use the same analogy as in value parameters, but let us assume the marks have
been entered on a spreadsheet on Mrs Mabena’s laptop, with a password. She gives
the password to this file to each of her children. Each one does his/her job, saving the
result on the file, resulting in Mrs Mabena’s excel file to be changed.

When writing an algorithm, we will use the prefix ref to indicate that it is a reference
parameter.

1.3 Function Procedures

A function procedure (we will call it only function from now on) is a module
dedicated to a single task. It consists of a number of statements that renders a single
result. It may receive zero or more value parameters and will always return a single
value.

1.3.1 The Function Call

A function is called (activated) from another part of the algorithm. When the function
has completed its execution, control is returned to the calling statement.

In the call, the parameter list is called the argument list, or actual arguments.

The calling statement may be any type of statement: an if-statement, and assignment
statement, a display statement – as can be seen in the following examples. The call
statement consists of the function name followed by the argument list in brackets. It is
not required that a function call must have arguments, but the brackets are
compulsory.

DSO17BT -3-
Example 1: Send two values to a function named DetermineProd that will calculate
the product of the two numbers sent as arguments:

Function call:
product = DetermineProd (num1, num2)

The result will be assigned to the variable product in the calling module.
DetermineProd is the name of the function, and num1 and num2 are the
arguments matching two value parameters.

Example 2: Consider the same function, but instead of saving the result in variable
product, display the product directly:

Function call:
display “The product of ”, num1, “ and ”, num2, “ is ”, DetermineProd(num1, num2)

Example 3: Consider the same function, test whether the result is greater than 100:

Function call:
if DetermineProd(num1, num2) > 100 then
display “The product is greater than 100”
endif

1.3.2 The Function Definition

The function definition starts with the function header that consists of the reserved
word function followed by the name of the function, followed by the parameter list in
brackets:

Format: function nameOfFunction(parameter list)

The last statement in the function is the return statement. This statement returns the
result of the function to the calling module, and also exits the function.

Format: return result

The name of the function is associated with the data type of the value that is returned
and therefore may return only a single value.

Example:
Consider the function call in Example 1 in 1.3.1:

product = DetermineProd (num1, num2)

The function definition for this call will be:

function DetermineProd (valNum1, valNum2)


return (valNum1*valNum2)

DSO17BT -4-
or

function DetermineProd (valNum1, valNum2)


prod = valNum1*valNum2
return prod

Notes:
1. The name of the function in the function header and the function call must be
the same.
2. The names used for the arguments and the parameters do not have to be the
same. In the design, to indicate that the parameter is a value parameter, the
prefix val is used, e.g. valNum1
3. The order in which the parameters in the parameter list appear in the function
header must be the same as the order in which the arguments in the argument
list in the function call appear.
4. The number of parameters in the parameter list in the function header must be
the same as the number of arguments in the argument list in the function call.
5. The name of the variable whose value is returned by the function does not have
to be the same as the variable that is going to receive the value that is returned.
6. The arguments in the function call are the name of the variables whose values
are passed to the function. The parameters in the function header will receive
these values when the function is called, and must indicate that they are value
parameters by adding the prefix val.

Call: prod = DetermineProd(num1, num2)

Function header: function DetermineProd(valNum1, valNum2)


prod = valNum1 * valNum2
return prod

1.4 Algorithm Examples

1.4.1 Example 1:

PaveIt needs a program to calculate the cost of paving. Read in the size of the area to
be paved in square meters, as well as the cost per square meter. Calculate the cost in
a function.

Planning:

Description Type Variable Name


Main module (DeterminePaveCost):
Input: size of area real areaSize
cost per square real costSquareMeter
meter
DSO17BT -5-
Output: cost of paving real pavingCost
Function (CalcCost):
Input: copy of size of area real valAreaSize
copy of cost per real valCostSquareMeter
square meter
Output: cost of paving real cost

Algorithm:

function CalcCost (valAreaSize, valCostSquareMeter)


cost = valAreaSize * valCostSquareMeter
return cost

DeterminePaveCost
~ This program calculates the cost of the paving, given the area and cost ~ per square
meter for the paving

display “Enter the area to be paved”


enter areaSize
display “Enter the cost per square meter”
enter costSquareMeter

pavingCost = CalcCost(areaSize, costSquareMeter)

display “The cost for the paving is ”, pavingCost


end

1.4.2 Example 2:

Write an algorithm for a lecturer to convert all his/her students’ marks to a percentage.
Display the percentage and a message indicating whether the student passed (50% or
more) or failed the test. Enter the total of the test, and then enter for each student
his/her student number and the mark obtained. Write a function to determine the
percentage, and a second function to indicate whether the student has passed (true or
false).

Planning:

Description Type Variable Name


Main module (ConvertTestMark):
Input: total of test real testTotal
student number integer studNum
test mark real testMark
Output: percentage real percentage
passed message string passedMess
Function (ConvertToPercentage):
Input: copy of total of test real valTestTotal

DSO17BT -6-
copy of test mark real valTestMark
Output: percentage real perc
Function (DeterminePassed):
Input: copy of percentage real valPerc
Output: did student pass? boolean studPassed

I P O
testTotal Prompt for & enter total of For each student:
For each student: test studNum
studNum For each student: percentage
testMark Prompt for & enter passedMess
student input values
Convert test mark to
a percentage
Determine whether
the student has
passed.
Display percentage
and passed
message.

Algorithm:

function ConvertToPercentage (valTestTotal, valTestMark)


perc = valTestMark / valTestTotal * 100
return perc

function DeterminePassed(valPerc)
if valPerc >= 50 then
studPassed = TRUE
else
studPassed = FALSE
endif
return studPassed

ConvertTestMark
~ This program determines several student’s test mark’s percentage and
~ displays whether the student passed or not

display “Enter the total of the test”


enter testTotal
display “Enter the student number (-1 to end)”
enter studNum
do while studNum <> -1
display “Enter student’s mark”
enter testMark

DSO17BT -7-
percentage = ConvertToPercentage(testTotal, testMark)

if DeterminePassed(percentage) then
passedMess = “ and has passed”
else
passedMess = “ and has failed”
endif
display studNum, “ has a percentage of ”, percentage, “
“% ”, passedMess
display “Enter the student number (-1 to end)”
enter studNum
loop

end

Exercises:

1. Predict the output of the following algorithms:

1.1 function DoCalculation(valNum1, valNum2)


return (valNum1 mod valNum2 + valNum2 \ 3)

MainModule
x = 11
y = 4
result = DoCalculation(x, y)
display “The result = ”, result
end

1.2 function DoCalc (valIn1, valIn2)


z = valIn1 + valIn2
return z

MainModule
x = 0
y = 1
do while x < 4
x = DoCalc(y, x)
y = y + 3
x = x + 2
display “y = ”, y, “x = ”, x
loop
end

2. Write the function definition for the following functions, then give an example of
a call to this function:

DSO17BT -8-
2.1 A function that receives three marks, and determines and returns the average of
these marks.
2.2 A function that receives four values, and determines and returns the smallest
value.
3. Write a complete algorithm with functions to solve each of the following
problems:

3.1 Enter the length and width of a rectangle then call a function to calculate the
perimeter of the rectangle and another function to calculate the area of the
rectangle. Display these calculated values.

3.2 The owner of an art gallery wants to know how many children visit the gallery
on a specific day. The operator enters the age of each visitor. A child is regarded
as of age 16 or younger. At 5 o’clock in the afternoon the operator enters an
age of -1 to indicate the gallery closes for the day. Determine whether the
visitor is a child or not within a function. Display the number of children that
visited the art gallery that day.

3.3 A company that offers a photo copying service charges the following prices:
First 500 copies cost 15 cents per copy
The next 500 copies cost 12 cents per copy
Any extra copies cost 9 cents per copy.
Your program should read in, for an unknown number of clients, the client
number, the number of copies that the client wants and a discount code. The
code determines how much discount the client will get, as follows:

Discount code Percentage Discount


A 12.5%
B 8.2%
C 6.7%
D 4%
Any Other No discount

Vat of 14% must then be added. The program must then calculate and print the
amount that the client owes the company, including the Vat. Use the following
three functions:
1. A function to determine the price for the copies before discount.
2. A function to calculate the discount given, and
3. A function to calculate the Vat payable.

DSO17BT -9-
1.5 FUNCTION PROCEDURES AND SUB PROCEDURES IN C++

1.5.1 C++ USER-DEFINED FUNCTIONS

Every C++ program contains at least one function, which is named main; however, a
C++ program may contain many functions. Functions may be defined before or after
the main function. However, the program execution always begins with the first
statement in the main function.
User-defined functions in C++ are classified into two categories:

 Value-returning functions—functions that have a return type. These functions


return a value of a specific data type using the return statement, in the
theory this is explained in terms of a function procedure.
 void functions—functions that do not return any value. These functions do not
use a return statement to return a value. In the theory this is explained in terms
of sub procedures.

1.5.2 VALUE-RETURNING FUNCTIONS

The syntax of a value-returning function is:

functionType functionName(parameter list) function header


{
//declaration and/or executable statements; function body
return expr/variable;
}

The function consists of two parts, namely the function header and the function
body.
 In this syntax, functionType is the type of the value that the function returns.
The functionType is also called the data type or the return type of the value-
returning function. A function can return a char, an int, a float, a double,
a bool, or a string.
 Statements enclosed between curly braces form the body of the function.

 The return statement must be the last executable statement within the curly
braces. In C++, return is a reserved word. When a return statement executes in
a function, the function immediately terminates and the control goes back to the
calling module.

1.5.2.1 Pass by value

By default, arguments in C++ are passed by value. When arguments are passed by
value, a copy of the argument is passed to the function. The second type of
parameter which is pass by reference will be discussed with the void functions at a
later stage in this chapter

DSO17BT - 10 -
The syntax of the parameter list is:

dataType identifier, dataType identifier, ...

dataType may be a char, an int, a float, a double, a bool, or a string.

1.5.3 FUNCTION CALL

Similarly to the theory, a value-returning function is used:

 In an assignment statement or expression


 In an output statement
 In a conditional expression

Function call in an assignment statement:


Let’s re-write Example 1 in in C++:
product = determineProd (num1, num2);

Function call in an output statement:


Let’s re-write Example 2 in in C++:
cout << “The product of ”<< num1<< “ and ”<< num2
<< “ is ”<< determineProd(num1, num2);

Function call in a conditional expression


Let’s re-write Example 3 in in C++:
if (determineProd(num1, num2) > 100)
cout << “The product is greater than 100\n”;

1.5.4 FUNCTION DEFINITION

Below is the function definition for the function called in the example 1 – 3:

double determineProd (double num1, double num2)


{
return (num1 * num2);
}
Or
double determineProd (double num1, double num2)
{
double prod;
prod = num1 * num2;
return prod;
}

DSO17BT - 11 -
When a function definition appears below the main function, you must enter a
function prototype above the main function or inside the main function above the
function call. A function prototype is a statement that specifies the function’s name, the
data type of its return value, and the data type of each of its parameters (if any). One
can also see the function prototype as “declaring” a function. Below is the example of
the function prototype of the function called in example 1 – 3:

double determineProd (double num1, double num2);


or
double determineProd (double, double);

Variable names are optional when declaring parameters in the function prototype.

Now let’s re-write the Algorithm Example 1 (1.4.1 on page 5 and 6) in C++:

#include <iostream>
#include <conio.h>

Using namespace std;

double calcCost (double areaSize, double costSquareMeter)


{
double cost = areaSize * costSquareMeter;
return cost;
}
int main()
{
//This program calculates the cost of paving, given the area
//and cost per square meter ~ for the paving

double areaSize, costSquareMeter, pavingCost;


cout << “Enter the area to be paved”;
cin >> areaSize;
cout << “Enter the cost per square meter”;
cin >> costSquareMeter;

pavingCost = calcCost(areaSize, costSquareMeter);

cout << “The cost for the paving is ” << pavingCost <<endl;
_getch();
return 0;
}

Let’s re-write the Algorithm Example 2 (1.4.2 on page 7) in C++:

#include <iostream>
#include <conio.h>

Using namespace std;

DSO17BT - 12 -
//function prototypes
double convertToPercentage (double testTotal, double testMark);
bool determinePassed(double perc);

int main()
{
/*This program determines several student’s
test mark’s percentage and
displays whether the student passed or not */

double testTotal, testMark, percentage;


string passedMess;
int studNum;

cout << “Enter the total of the test: ”;


cin >> testTotal;
cout << “Enter the student number (-1 to end): ”;
cin >> studNum;
while (studNum != -1)
{
cout << “Enter student’s mark :”;
cin >> testMark;

percentage = convertToPercentage(testTotal, testMark);

if (determinePassed(percentage))
passedMess = “ and has passed\n”;
else
passedMess = “ and has failed\n”;

cout << studNum << “ has a percentage of ”


<< setprecision(2) << percentage << “ % ”
<< passedMess <<endl;

cout << “Enter the student number (-1 to end): ”;


cin >> studNum;
}
}
double convertToPercentage (double testTotal, double testMark)
{
double perc = testMark / testTotal * 100;
return perc;
}

bool determinePassed(double perc)


{
bool studPassed;
if (perc >= 50 )
studPassed = true;
else
studPassed = false;
return studPassed;
}

DSO17BT - 13 -
1.6 Sub Procedures

A sub procedure is also a module, and is responsible for solving part of a problem. Sub
procedures are used when no value or more than one value needs to be “sent back” to
the calling module. It may receive value and reference parameters. It does not return a
value with a return statement. By making use of reference parameters, it changes data
outside the sub procedure, as it has access to the data through the address that is sent
to the sub procedure via the reference parameters.

1.6.1 The Sub Procedure Call

Syntax of the sub procedure call:

call SubProcedureName (argument list)

Consider the following sub procedure call:

call DetLargestSmallest (num1, num2, num3, num4, largest, smallest)


display “The largest value of ”, num1, “,” , num2, “,” , num3, “ and ” , num4,“ is ”, largest
display “and the smallest value is ”, smallest

 DetLargestSmallest is the name of the sub procedure.


 num1, num2, num3 and num4 are value parameters, and will not be
changed by the sub procedure, as they have to be displayed in the statement
that follows the call.
 largest and smallest are two arguments that are connected to two reference
parameters, i.e. their respective addresses will be sent to the sub procedure.
The values stored at these addresses may be changed.
 This sub procedure is used to calculate two results: the smallest and the largest
of the first four arguments passed by value.

1.6.2 The Sub Procedure

The sub procedure header statement has the following syntax:

sub NameOfSubProcedure (parameter list)

The sub procedure header of the call to DetLargestSmallest in 1.6.1 is as follows:

sub DetLargestSmallest (valNo1, valNo2, valNo3, valNo4, refLargest, refSmallest)

 DetLargestSmallest is the name of the sub procedure – same name as used


in the sub procedure call.
 valNo1, valNo2, valNo3 and valNo4 are value parameters that will receive
the value of the arguments associated with each one in the call (first four
arguments).

DSO17BT - 14 -
 refLargest and regSmallest are two reference parameters that will receive
the address of the two arguments associated with each of them (last two
arguments).

The Sub Procedure:

sub DetLargestSmallest (valNo1, valNo2, valNo3, valNo4, refLargest, refSmallest)


~ Determine the smallest and largest of the four values sent as value parameters
refLargest = valNo1
if valNo2 > refLargest then
refLargest = valNo2
endif
if valNo3 > refLargest then
refLargest = valNo3
endif
if valNo4 > refLargest then
refLargest = valNo4
endif

refSmallest = valNo1
if valNo2 < refSmallest then
refSmallest = valNo2
endif
if valNo3 < refSmallest then
refSmallest = valNo3
endif
if valNo4 < refSmallest then
refSmallest = valNo4
endif
end sub

 The sub procedure receives a copy of the value into each of the first four
parameters from the arguments associated with each of them: (the value of
num1 in the call will be assigned to valNo1 in the sub procedure header;
the value of num2 in the call will be assigned to valNo2 in the sub
procedure header, etc.).
 refLargest and refSmallest contains the addresses of the arguments
associated with each of them in the call: refLargest with largest and
refSmallest with smallest. This is where the sub procedure can directly
save the result of the calculations of the sub procedure (in this case
determining the largest and determining the smallest). What in actual fact
happens is that both the calling module (in our example in 1.6.1 largest and
smallest) and the sub procedure being executed (in our example here
refLargest and refSmallest), refer to the same position in memory, and
thereby the sub procedure is able to change the value of the variables in
the calling module.
 The sub procedure is always terminated with the line end sub.

DSO17BT - 15 -
Call: call DetLargestSmallest (num1, num2, num3, num4, largest, smallest)

Header: sub DetLargestSmallest(valNo1,valNo2,valNo3,valNo4,refLargest, refSmallest)

Note: Although this is not what happens in the computer, we can look at a reference
parameter as a two-way street, where the current value from the calling module is
“received” by the sub procedure. The sub procedure can then change the value and
“send it back” to the calling module. This happens in reality through the address in the
calling module of the variable being sent to the called module, and this way the sub
procedure has direct access to the variable in the calling module.

Both functions and sub procedures can be called from the main module, or any other
module (a function or a sub procedure).

1.7 SUB PROCEDURE EXAMPLES

1.7.1 Example 1:
Develop a solution to the following problem:

For a number of employees, enter the employee number, gross salary (salary before
deductions), the medical contribution that needs to be paid, as well as the income tax
percentage applicable to the employee. Except for the employee number, these values
must be prompted for and entered in a sub procedure. Then calculate the following
values in another sub procedure: the tax contribution that the employee has to make
based on the tax percentage (no tax is payable on the medical aid contribution,
therefore it must be deducted before the tax payable is calculated), as well as the net
pay (pay after deductions) that the employee is going to receive. Display these values
in a third sub procedure.

Let us first consider the IPO chart for the main module:

I P O
For each employee: For each employee: For each employee:
empNum Prompt & enter input empNum
grossSal fields netPay
medContr Calculate net pay & tax taxContr
taxPerc contribution
Display net pay & tax
contribution

DSO17BT - 16 -
And then the IPO chart for each of the three sub procedures:

PromptForAndEnterInput

I P O
Prompt for and enter values refGrossSalary
refMedContr
refTaxPerc
CalculatePayValues

I P O
valGrossSal Calculate pay after medical aid refTaxPayable
valMedContr contribution refNetPay
valTaxPerc Calculate the tax payable
Calculate the net pay

DisplayPayValues

I P O
valTaxPayable Display the tax payable and the
valNetPay net pay

Notes on the IPO charts of the sub procedure:


 All input values into the sub procedure, appearing in the Input column, have to be value
parameters, unless the same variable, possibly to be updated, also appears in the
Output column. Then it must be a reference parameter in both the input and output
column of the IPO chart for the sub procedure.
 All output values of the sub procedure appearing in the Output column, must be
reference parameters. This is because a sub procedure is used to either “send back” no
value, or more than one value to the calling module. If more than one value have to be
“sent back” to the calling module, the only way we can do it is with reference
parameters. (“sent back” is used in quotes because this is not what happens in reality –
refer to the note on pg. 16 under The Sub Procedure.)
 We can also see that we have sub procedures with no input from the calling module,
but output to the calling module (first sub procedure), as well as ones with input from
the calling module, but no output to the calling module (third sub procedure).

Algorithm:

DoPayCalculations:
display “Enter the employee number (9999 to end)”
enter empNum
do while empnum <> 9999
call PromptForAndEnterInput (grossSal, medContr, taxPerc)
call CalculatePayValues (grossSal, medContr, taxPerc, netPay, taxContr)
call DisplayPayValues (netPay, taxContr)
Display “Enter the employee number (9999 to end)”
Enter empNum
loop
end

DSO17BT - 17 -
sub PromptForAndEnterInput (refGrossSal, refMedContr, refTaxPerc)
display “Enter the employee’s gross salary”
enter refGrossSal
display “Enter the employee’s medical aid contribution”
enter refMedContr
display “Enter the employee’s tax percentage”
enter refTaxPerc
end sub

sub CalculatePayValues (valGrossSal, valMedContr, valTaxPerc, refNetPay, refTaxContr)


refNetPay = valGrossPay – valMedContr
refTaxContr = valTaxPerc / 100 * refNetPay
refNetPay = refNetPay – refTaxContr
end sub

sub DisplayPayValues (valNetPay, valTaxContr)


display “The net pay of the employee is R”, valNetPay
display “The tax contribution of the employee is R”, valTaxContr
end sub

1.7.2 Example 2:
Develop a solution to the following problem:

Mrs Kgasi wants to calculate the final predicate mark for her students. They each wrote
3 tests. The best mark contributes 45% towards the predicate, the second best test
35%, and the worst test 20%. For all her students, enter the student number and the
3 test marks as a percentage. Enter the 3 test marks in a sub procedure. Then sort the
test marks in descending sequence, so that the best test is stored in the first test’s
variable, the second best test in the second test’s variable, etc. Do this in a second sub
procedure. Then call a third sub procedure to convert all these marks to their correct
contributions, replacing the percentage values with the contributions. Calculate and
display the predicate mark along with the student number.

At the end display the average predicate mark, as well as the student number of the
student with the highest predicate mark. The accumulation of the necessary values to
determine the average predicate mark must be calculated using a fourth sub
procedure. The determining of the student number of the student with the highest
predicate mark must be calculated in a final sub procedure.

DSO17BT - 18 -
Let us first consider the IPO chart for the main module:

I P O
For each student: Initialise counters & For each student:
studNum accumulators studNum
tstMark1 For each student: predMark
tstMark2 Prompt & enter input avePredMark
tstMark3 fields studNumHighest
Sort the test marks
Calculate each test
mark’s contribution
Calculate the predicate
mark
Display stud number
and predicate mark
Accumulate total
predicate mark & count
number of students
Determine the student
number of the student
with the highest
predicate mark
Calculate the average predicate
mark
Display the average predicate
mark
Display the student number of
the student with the
highest predicate mark

And then the IPO chart for each of the five sub procedures for explanation
purposes:

EnterTestMarks

I P O
Prompt for and enter test marks refTstMark1
refTstMark2
refTstMark3

SortTestMarks

I P O
refTstMark1 Sort test marks refTstMark1
refTstMark2 refTstMark2
refTstMark3 refTstMark3

CalcTestMarkContr

I P O
refTstMark1 Calculate each test mark’s refTstMark1
refTstMark2 contribution refTstMark2
refTstMark3 refTstMark3

DSO17BT - 19 -
AccumulateTotalCntr

I P O
valPredMark Accumulate the total predicate refTotalPredMark
refTotalPredMark mark refNumStuds
refNumStuds Count the number of students

DetStudNumHighest

I P O
valStudNum Determine the student number refStudNumHighest
valPredMark of the student with the refHighestPred
refStudNumHighest highest predicate
refHighestPred

Algorithm:

CalcPredicateMarks
~ This program calculates the predicate mark for a number of students, and then calculate and
~ display the average predicate mark, as well as the student number of the student with the
~ highest predicate mark

totPredMark = 0
numStuds = 0
highestPred = 0
studNumHighest = 0

display “Enter student number (-999 to end)”


enter studNum
do while studNum <> -999
call EnterTestMarks (tstMark1, tstMark2, tstMark3)

call SortTestMarks (tstMark1, tstMark2, tstMark3)

call CalcTestMarkContr (tstMark1, tstMark2, tstMark3)

predMark = tstMark1 + tstMark2 + tstMark3

display studNum, “ has a predicate mark of ”, predMark, “%”

call AccumulateTotalCntr (predMark, totPredMark, numStuds)

call DetStudNumHighest (studNum, predMark, studNumHighest, highestPred)

display “Enter student number (-999 to end)”


enter studNum
loop

avePredMark = totPredMark / numStuds


display “The average predicate mark is ”, avePredMark

display “The student number of the student with the highest predicate mark is ”,
studNumHighest
end

DSO17BT - 20 -
sub EnterTestMarks (refTstMark1, refTstMark2, refTstMark3)
display “Enter the three test marks:”

display “ enter test mark 1”


enter refTstMark1
display “ enter test mark 2”
enter refTstMark2
display “ enter test mark 3”
enter refTstMark3
end sub

sub SortTestMarks (refTstMark1, refTstMark2, refTstMark3)


if refTstMark2 > refTstMark1 then
~ Swap the two values
temp = refTstMark1
refTstMark1 = refTstMark2
refTstMark2 = temp
endif

if refTstMark3 > refTstMark2 then


~ Swap the two values
temp = refTstMark2
refTstMark2 = refTstMark3
refTstMark3 = temp
endif

if refTstMark2 > refTstMark1 then


~ Swap the two values
temp = refTstMark1
refTstMark1 = refTstMark2
refTstMark2 = temp
endif
end sub

sub CalcTestMarkContr (refTstMark1, refTstMark2, refTstMark3)


refTstMark1 = refTstMark1 / 100 * 45
refTstMark2 = refTstMark2 / 100 * 35
refTstMark3 = refTstMark3 / 100 * 20
end sub

sub AccumulateTotalCntr (valPredMark, refTotPredMark, refNumStuds)


refTotPredMark = refTotPredMark + valPredMark
refNumStuds = refNumStuds + 1
end sub

sub DetStudNumHighest (valStudNum, valPredMark, refStudNumHighest, refHighestPred)


if valPredMark > refHighestPred then
refStudNumHighest = valStudNum
refHighestPred = valPredMark
endif
end sub

DSO17BT - 21 -
Exercises:
1.1 Study the following sub procedure call in an algorithm:

call CalculatePay(hours, rate, 25, grossPay, netPay)

The sub procedure will receive the hours that an employee worked as well as the rate
per hour. Currently all employees pay 25% tax as is indicated in the third argument.
The sub procedure must calculate the gross pay and the net pay for this employee
which must be accessible to the calling module. Employees get normal pay rate for the
first 40 hours. For the next 10 hours they get 1½ times the pay rate and for all hours
more than that, they get double the rate per hour.

Write the complete sub procedure for this problem.

1.2 Study the following sub procedure call in an algorithm:

call Rectangle(length, width, area, perimeter)

The variable length contains the length of a rectangle and the variable width
contains the width of the rectangle. The sub procedure must calculate the area and
perimeter for the rectangle which must be accessible by the calling module.

Write the complete sub procedure for this problem.

2 Predict the exact output for the following algorithm:

sub CalculateAnswers(valNum1, valNum2, refNum3)


valNum1 = valNum1 + 5
valNum2 = valNum2 / 5
refNum3 = valNum1 * valNum2
end sub

function MultipleOf5(valNum)
if valNum mod 5 = 0 then
Mult5 = True
else
Mult5 = False
endif
return Mult5

MainAlgorithm
display “Here are the answers:” ~ display on a new line
for x = 1 to 15
if x mod 2 = 0 then
display “Even : ”, x
else
if x mod 3 = 0 then
display “Multiple of 3 : ”, x
endif
endif
if MultipleOf5(x) = True then
call CalculateAnswers(0, x, y)

DSO17BT - 22 -
display “x = ”, x ~ display on a new line
display “y = ”, y ~ display on a new line
endif
next x
end

3 Design a solution to the following programming problem:

The Cell Phone Company, Cell4U, determines their cell phone costs as follows: A client
pays R2.05 for full minute calls and 2c for each extra second. They also pay 40c per
SMS, but a client gets 2 free SMS’s for every full 30 call minutes. A client also gets 1
SMS free for every 30 SMS’s sent.

All employees who work for the company get a free cell phone as a perk and their
account is also paid to a maximum of R800 per month. The company requires a
monthly report of the cell phone bills for all employees as well as the total amount that
they spend on cell phone perks for employees.

For all employees the following must be entered:


 Employee number
 Total duration in seconds of all calls during the month
 Number of SMS’s sent during the month

After it has successfully been entered, the following values must be calculated and
displayed for that employee:
 The employee number
 The total duration of all calls in minutes and seconds
 The number of SMS’s sent, along with the number of free SMS’s received
 The cost of all calls in rand and cent
 The cost for the SMS’s
 The total cost for the employee, and
 The amount paid by the company

At the end the total amount that has to be paid by the company must be displayed.

The program must provide for the following:

 The amount due for the calls and the amount due for the sms-messages must be
calculated in a sub procedure. This will necessarily imply that the sub procedure
must convert the seconds to minutes and seconds and that these values as well as
the number of free SMS’s also are made available to the main procedure.
 A second sub procedure must be called to calculate the total bill for the employee
and to accumulate the total that the company needs to pay out for cell phone perks.
This sub procedure must also use a Boolean parameter to indicate to the main
procedure whether the company will pay out the full amount for this employee or
only R800.
 All output must be displayed in the main module.

DSO17BT - 23 -
IPO Chart Main Module
I P O
For each employee: Initialize totals For each employee:
empNum For each employee: empNum
durInSecCalls Prompt for & enter durInMinSec
numSMSes input numSMSes
Calculate the numFreeSMSes
duration in min & costAllCallsRC
seconds costSMSes
Calculate num free totCostEmp
SMSes amntPaidComp
Calculate cost of all totAmntComp
calls
Calculate the cost for
SMSes
Determine the total
cost
Calculate the amount
to be paid by the
company
Accumulate the total
amount the company
has to pay for all
employees

IPO Chart For Module CalcCostCallsAndSMSes

I P O
valDurInSecCalls Calculate the duration in refDurInMinSec
valNumSMSes minutes and seconds refNumFreeSMSes
Calculate the number of free refCostAllCallsRC
SMSes refCostSMSes
Calculate the cost for all
calls
Calculate the cost for the
SMSes

IPO Chart For Module CalcTotalBill

I P O
valCostAllCallsRC Accumulate total bill for refTotCostEmp
valCostSMSes employee and indicate if full refAmntPaidComp
refTotAmntComp amt is paid or not. refMustPayTotAmnt
Accumulate total that refTotAmntComp
company must pay out for
perks

DSO17BT - 24 -
1.8 SUB PROCEDURES IN C++

1.8.1 VOID FUNCTIONS

C++ regards all independent modules as functions. In section 1.5 of this notes we
demonstrated how to use value-returning functions. In C++ we use void functions to
represent sub procedures discussed in the theory section. Similar to value-returning
functions, void functions execute instructions to perform a specific task. Void functions
do not return a value at the end of their execution. Similarly to value-returning, void
functions can be declared or defined either before or after the function main, but the
program execution will always start from the main function. However, a function
prototype must be placed before the main function whenever a value-returning or a
void function is defined after the main function.

The syntax used to create a void function in a C++ program:

void functionName([parameterList]) //function header


{
one or more statements body (always enclosed within {})
} //end of functionName function

So when you compare this syntax with the one for creating a value-returning function
you will notice two differences.
 First, a void function’s header begins with the keyword void rather than with a
data type. The void keyword indicates that the function does not return a value.
 Second, the function body in a void function does not contain a return statement,
which is required in the function body of a value-returning function. The return
statement is not necessary in a void function body because a void function does
not return a value.
Note: The return statement without any value can be used whenever we want to exit
early from our void function. Remember, any user-defined function will terminate after
the execution of the return statement.

A program might use a void function to prompt and receive input from the user,
especially if those input are required more than once in different section of the program.
Rather than duplicating the required code several times in the program, the code can
be entered once in a void function. In such case, reference parameters are required in
order to retrieve the input values from the calling module.

1.8.2 Pass by reference

Similarly to the theory, passing by reference is the second way of passing parameters
to the function. The address of the argument is copied into the parameter. The
changes made to the parameter affect the arguments. The address of the argument is
passed to the function and the function modifies the values of the arguments in the
calling function. In other words, you can pass the variable’s location in the computer’s
internal memory. To pass a variable by reference in C++, you include an ampersand

DSO17BT - 25 -
(&) before the name of the parameter in the function’s header and/or function
prototype. The ampersand, also known as address-of operator tells the computer to
pass the variable’s address rather than its value.

Note: both value and reference parameters can be used in a void function.

The syntax of the reference parameter list is:

dataType& identifier, dataType& identifier, ...

1.8.3 The void function call

To call a void function in a program write the name of the function and/or arguments.
Remember to include the semicolon at the end to terminate your calling statement.

Syntax of the sub procedure call:

functionName (argument list);

Consider the following void function call:

detLargestSmallest (num1, num2, num3, num4, largest, smallest);


cout << “The largest value of ”<< num1<< “,” << num2<< “,” <<num3
<< “ and ” << num4<<“ is ”<<largest<<endl;
cout<< “and the smallest value is ”<<smallest<<endl;

As noted in the theory section, value parameters can have variables or literal constants
as arguments, whereas reference parameters can only have variables as argument.

1.8.4 Examples

1.8.4.1 Example 1

Let’s re-write example 1 (1.7.1 on pages 16 and 17) in C++:

//function prototype
void promptForAndEnterInput (double&, double&, double&);
void calculatePayValues (double, double, double, double&, double&);
void displayPayValues (double netPay, double taxContr);

int main()
{
int empNum;
double grossSal, medContr, taxPerc, netPay, taxContr;
cout << “Enter the employee number (9999 to end): ”;
cin >> empNum;
while (empnum != 9999)
{
promptForAndEnterInput (grossSal, medContr, taxPerc);
calculatePayValues (grossSal, medContr, taxPerc, netPay, taxContr);

DSO17BT - 26 -
displayPayValues (netPay, taxContr);
cout << “Enter the employee number (9999 to end): ”;
cin >> empNum;
}
system(“pause”);
return 0;
}
void promptForAndEnterInput (double& grossSal, double& medContr, double& taxPerc)
{
cout << “Enter the employee’s gross salary: ”;
cin >> grossSal;
cout << “Enter the employee’s medical aid contribution: ”;
cin >> medContr;
cout << “Enter the employee’s tax percentage: ”;
cin >> taxPerc;
}

void calculatePayValues (double grossSal, double medContr, double taxPerc, double& netPay, double&
taxContr)
{
netPay = grossPay – medContr;
taxContr = taxPerc / 100 * netPay;
netPay = netPay – taxContr;
}
void displayPayValues (double netPay, double taxContr)
{
cout << “The net pay of the employee is R” << netPay <<endl;
cout << “The tax contribution of the employee is R” << taxContr<<endl;
}

1.8.4.2 Example 2

Let’s re-write example 2 (1.7.2 on pages 18 - 20) in C++:

void enterTestMarks (int& tstMark1, int& tstMark2, int& tstMark3);


void sortTestMarks (int& tstMark1, int& tstMark2, int& tstMark3);
void CalcTestMarkContr (int& tstMark1, int& tstMark2, int& tstMark3);
void accumulateTotalCntr (int predMark, int& totPredMark, int& numStuds);
void detStudNumHighest (int studNum, int predMark, int& studNumHighest, int& highestPred);

int main()
{
/*This program calculates the predicate mark for a number of students, and then calculate and
display the average predicate mark, as well as the student number of the student with the
highest predicate mark*/

int totPredMark = 0.0;


int numStuds = 0;
int highestPred = 0.0;
int studNumHighest = 0;

int studNum, tstMark1, tstMark2, tstMark3, predMark;


double avePredMark;
cout << “Enter student number (-999 to end): ”;
cin >> studNum;

DSO17BT - 27 -
while (studNum != -999)
{
enterTestMarks (tstMark1, tstMark2, tstMark3);
sortTestMarks (tstMark1, tstMark2, tstMark3);
calcTestMarkContr (tstMark1, tstMark2, tstMark3);
predMark = tstMark1 + tstMark2 + tstMark3;
cout << studNum <<“ has a predicate mark of ”<< predMark<<“%\n”;
accumulateTotalCntr (predMark, totPredMark, numStuds);
detStudNumHighest (studNum, predMark, studNumHighest, highestPred);
cout << “Enter student number (-999 to end): ”;
cin>> studNum;
}
avePredMark = totPredMark / numStuds;
cout << “The average predicate mark is ” << avePredMark <<endl;
cout << “The student number of the student with the highest predicate mark is ”
<< studNumHighest <<endl;
}

void enterTestMarks (int& tstMark1, int& tstMark2, int& tstMark3)


{
cout << “Enter the three test marks:\n”;
cout << “ enter test mark 1: ”;
cin >> tstMark1;
cout << “ enter test mark 2: ”;
cin >> tstMark2;
cout << “ enter test mark 3: ”;
cin >> tstMark3;
}

void sortTestMarks (int& tstMark1, int& tstMark2, int& tstMark3)


{
int temp;
if (tstMark2 > tstMark1)
{
//Swap the two values
temp = tstMark1;
tstMark1 = tstMark2;
tstMark2 = temp;
}

if (tstMark3 > tstMark2 )


{
//Swap the two values
temp = tstMark2;
tstMark2 = tstMark3;
tstMark3 = temp;
}

if (tstMark2 > tstMark1 )


{
//Swap the two values
temp = tstMark1;
tstMark1 = tstMark2;
tstMark2 = temp;
}
}

DSO17BT - 28 -
void CalcTestMarkContr (int& tstMark1, int& tstMark2, int& tstMark3)
{
tstMark1 = tstMark1 / 100 * 45;
tstMark2 = tstMark2 / 100 * 35;
tstMark3 = tstMark3 / 100 * 20;
}

void accumulateTotalCntr (int predMark, int& totPredMark, int& numStuds)


{
totPredMark = totPredMark + predMark;
numStuds = numStuds + 1;
}

void detStudNumHighest (int studNum, int predMark, int& studNumHighest, int& highestPred)
{
if (predMark > highestPred )
{
studNumHighest = studNum;
highestPred = predMark;
}
}

1.8.4 SUMMARY

In addition to these notes, study the following pages on Chapter 6 inside the
prescribed textbook.
 Page 225 – 276 (Chap. 6.1 – 6.4)
o Function and Parameter Declarations
o Returning a Single Value
o Returning Multiple Values
o Variable Scope
 And page 285 – 286
o Common Programming Errors
o Chapter Summary

DO THE FOLLOWING EXERCISES:


 EXERCISES 6.1 Page 242- 244
o Do all the exercises (1 – 14)
 EXERCISES 6.2 Page 253 – 257
o Do all the exercises (1 – 16)
 EXERCISES 6.3 Page 265 – 267
o Do all the exercises (1 – 8)
 EXERCISES 6.4 Page 272 – 276
o Do all the exercises (1 and 5)

DSO17BT - 29 -

You might also like