Compiled by Adelle von Below Quality assured by ... · C++ Programming for the Absolute Beginner,...
Transcript of Compiled by Adelle von Below Quality assured by ... · C++ Programming for the Absolute Beginner,...
Compiled by Adelle von Below
Quality assured by Oluwapelumi Giwa
Edited by Barbara Woods
Version 1.0
January 2014 CTI EDUCATION GROUP
TABLE OF CONTENTS INTRODUCTION
1.1 COURSE DESCRIPTION
1.3 LEARNING OUTCOMES AND ASSESSMENT CRITERIA
1.4 LECTURES
1.5 CLASS EXERCISES AND ACTIVITIES
1.6 HOW TO USE THE STUDY GUIDE
1.7 PRESCRIBED TEXTBOOK
1.8 RESOURCES
1.9 ICONS USED IN THE STUDY GUIDE
UNIT 2 - MAPPING TO EBOOK
2.1 PURPOSE OF INSTRUCTION GUIDE
LO1USE, DEVELOP AND DESIGN STRUCTURED PROGRAMMING METHODS
LO2USE MODULARISATION FROM THE CHOSEN PROGRAMMING LANGUAGE.
LO3PRODUCE APPROPRIATE DOCUMENTATION FOR A GIVEN PROGRAM APPLICATION.
LO4CREATE AND APPLY APPROPRIATE TEST SCHEDULES
UNIT 3 - PROGRAMMING CONCEPTS
INTRODUCTION
3.1 GENERAL CONCEPTS
3.2 DATA TYPES
3.3 ANALYSING AND SOLVING PROBLEM
3.4 PROGRAM FLOWCHARTS
3.5 EXERCISES
UNIT 4 - PROGRAM CONTROL STRUCTURES
INTRODUCTION
4.1 IF STATEMENTS
4.2 SELECT CASE STATEMENTS
4.3 FOR LOOPS
4.4 DO LOOP
4.5 DO UNTIL LOOP
4.6 EXERCISES
UNIT 5 - PROGRAMMING STANDARDS
INTRODUCTION
5.1 NAMING A VARIABLE
5.2 WRITING ALGORITHMS
5.3 USING FUNCTION PROCEDURES
5.4 SUB-PROCEDURES
5.5 VARIABLE SCOPE
5.6 WORKING EXAMPLE
5.7 EXERCISES
UNIT 6 - DOCUMENTATION AND ERROR PREVENTION
INTRODUCTION
6.1 RELEVANT PROGRAM DOCUMENTATION
6.2 ERROR DETECTION
6.3 PROGRAM TESTING
6.4 EXERCISES
GLOSSARY:
BIBLIOGRAPHY
Introduction
1.1 Course description
The student will gain the basic knowledge of general principles and the
concepts of programming.
Students will develop programs and, although the content could be delivered from a range of languages, compilers or platforms, the unit should aim to
deliver skills and knowledge that will easily transfer to other areas of the qualification life cycle.
Students will adopt good practice while designing programs using industry
techniques. The student will also use variables, constants and literals. The
student will understand the concepts of data storage within a computer program and identify or select appropriate iterative and selection structures
when writing simple programs. In addition to the above, the student will learn the facilities and rules of the language, e.g., operators, I/0 commands and how
to make use of comments and code layout.
The student will use or create both predefined and user-defined functions and procedure; and map structured design onto a program using functions or
procedures; pass data by value and reference; create software applications, e.g., a word processor or graphics, analysis, design and implementation of
documentation; professional standards. Students will test the data and schedules, e.g., black box, white box, dry testing and data collection.
1.3 Learning outcomes and assessment criteria
This module is designed to cover four learning outcomes. After completing this course, you should be able to:
1. Use, develop and design structured programming methods
2. Use modularisation from the chosen programming language 3. Produce appropriate documentation for a given program application
4. Create and apply appropriate test schedules.
It is important that you pay careful attention to the learning outcomes and
assessment criteria, as listed in the table on the next page, because all of your assessments are designed to demonstrate that you have mastered these.
Learning outcomes Assessment criteria for pass To achieve each outcome, a student must
demonstrate the ability to: LO1
Use, develop and design
structured programming methods
AC1.1 Identify and select appropriate pre-defined data
types
AC1.2 Use simple input or output and appropriate
operators with the above
AC1.3 Identify and use appropriate selection structures
and loop structures for the given task
AC1.4 Produce programs to desired standards LO2
Use modularisation from the
chosen programming language
AC2.1 Construct a program from a design and use
appropriate functions/procedures
AC2.2 Demonstrate the effect of scope and life-time of
variables
AC2.3 Pass data effectively between modules. LO3
Produce appropriate
documentation for a given
program application
AC3.1 Produce user documentation for a completed
programming application including the user
interface design
AC3.2 Develop documentation for a pre-described
program application LO4
Create and apply appropriate test
schedules
AC4.1 Demonstrate discrimination between semantic and
syntax errors
AC4.2 Produce test documentation
AC4.3 Successfully construct and use test data and
schedules to detect logic errors
AC4.4 Use appropriate techniques for detecting errors
1.4 Lectures Each week has four compulsory lecture hours for all students. It is
recommended that the lecture hours be divided into two sessions of two hours each, but this may vary depending on the campus.
Each week has a lecture schedule which indicates the approximate time that
should be allocated to each activity. The week’s work schedule has also been divided into two lessons.
1.5 Class exercises and activities
Students will be required to complete a number of exercises and activities in class. These activities and exercises may also contribute to obtaining pass,
merit or distinction criteria; it is, therefore, important that students are present in class so that they do not forfeit the opportunity to be exposed to
such exercises and activities.
Activity sheets that are handed in should be kept by the lecturer so that they can be used as proof of criteria that were met, if necessary.
1.6 How to use the study guide
The purpose of the study guide is to facilitate your learning and help you to
master the content of the prescribed textbook and other material. It helps you to structure your learning and manage your time, provides outcomes and
activities to help you to master those outcomes, and directs you to the appropriate sections in the prescribed textbook. It is important that you start
with the study guide.
The study guide has been carefully designed to optimise your study time and maximise your learning, so that your learning experience is as meaningful and
successful as possible. To deepen your learning and enhance your chances of success, it is important that you read the study guide attentively and follow all
the instructions carefully. Pay special attention to the course outcomes at the beginning of the study guide and at the beginning of each unit.
It is essential that you complete the exercises and other learning activities in
the study guide, because your course assessment (examinations, tests and
assignments) will be based on the assumption that you have completed these activities.
This study guide accompanies a prescribed textbook and, therefore, it should
be read in conjunction with the prescribed text: it should not be deemed as a replacement for the prescribed text.
A clear understanding of the theories and models outlined in the text is not
only necessary in terms of understanding modern business; it also provides a fundamental building block for the study of corporate strategy – a subject that
is included at more advanced levels of the business curriculum.
1.7 Prescribed textbook
The prescribed textbook for this course is:
Pretorius, C. M. & Erasmus, H.G., Basic Programming
Principles. 2nd edition. Pearson Education. ISBN: 9781775786030.
1.8 Resources
The list below contains details for supplementary reading.
1.8.1 Books Henkmans, D. (2003). C++ Programming for the Absolute Beginner, Premier
Press, ISBN: 931841438
Perry, G. (2001) Sams Teach Yourself Beginning Programming in 24 Hours ISBN: 0672323079 Covers BASIC programming, but useful for beginners.
Veeraraghavan, S. (2002) Sams Teach Yourself Shell Programming in 24 Hours
ISBN: 672323583
1.8.2 Web sites www.freetutes.com/systemanalysis/
NOTE Web pages provide access to a further range of Internet
information sources. Students must use this resource with care, justifying the use of
information gathered.
1.9 Icons used in the study guide
The following icons are used in the course of the study guide:
This icon represents the start of a unit.
This icon points to the objectives/outcomes for each section,
which describe what you should know and what the student should be able to do after completion of a particular section.
This icon indicates learning activities/exercises that have to be completed, whether individually or in groups, in order to
assess (evaluate) the student’s understanding of the content of a particular section.
This icon indicates required reading – from the prescribed
textbook – that is essential for the completion of a particular section.
This icon points to self-assessment checks that test the student’s understanding and/or evaluate his/her progress.
This icon indicates references to supplementary reading that will support the student’s understanding of concepts.
Unit 2 - Mapping to eBook
2.1 Purpose of instruction guide
The eBooks given to the students are to be used in a certain way. The
instruction guide directs and also shows the students where to find and link each topic of every week in their eBook. This brings about the essence of
mapping to eBook.
LO1 Use, develop and design structured programming methods Content covered for learning outcome
Storage: The student will use variables, constants and literals. Understand the
concepts of data storage within a computer program. For a third generation language, the use of pre-defined data types, integers, floating point, character,
boolean, strings, one-dimensional and two-dimensional arrays of simple types, and simple files. The student will understand the use of these types, and the
available operators within the supplied language.
Control structures: The student will identify and select appropriate iterative
and selection structures when writing simple programs.
Programming language syntax: The student will learn the facilities and rules of the language, e.g., operators, I/0 commands, etc.
Program design: The student will develop a solution to a problem, e.g., create
structure charts, write pseudo code, etc. The student will also produce tested programs to meet given specifications.
Programming standards and practice: The student will make use of comments
and code layout, e.g., consistent indentation and descriptive identifiers.
Assessment criteria 1.1 Identify and select appropriate pre-defined data types.
Assessment criteria 1.2 Use simple input or output and appropriate operators with the above.
Assessment criteria 1.3 Identify and use appropriate selection structures and loop structures for the
given task. Assessment criteria 1.4
Produce programs to desired standards.
Chapter 1 – General concepts and arithmetic
Chapter 2 – Understanding a problem and using a computer to solve it
Chapter 3 – Write algorithms in sequential steps
Chapter 4 – The selection control structure: Part 1
Chapter 5 – The selection control structure: Part 2
Chapter 6 – Iteration using a fixed count loop
Chapter 7 – Iteration using the DO loop
Chapter 8 – Arrays
LO2 Use modularisation from the chosen programming language. Content covered for learning outcome
Use of functions or procedures: The student will use or create both predefined
and user-defined functions and procedures, and map structured design onto a program using functions or procedures.
Scope of variables: The student will use global, local, static and external
variables.
Parameters: The student will use the knowledge of passing data by value and
reference e.g. using return values.
Assessment criteria 2.1 Construct a program from a design and use appropriate functions/
procedures. Assessment criteria 2.2
Demonstrate the effect of scope and life-time of variables.
Chapter 9 – Function procedures and sub-procedures
LO3 Produce appropriate documentation for a given program
application. Content covered for learning outcome
Presentation of documentation: The student will create software applications,
e.g., a word processor or graphics, analysis, design and implementation of
documentation, professional standards and the needs of the industry.
User documentation: The student will draw up user documentation for specified programming applications, and the purpose and operation of the
program will be developed.
Program documentation: The student will draw up documentation that covers technical aspects of a given programming application, including algorithms
implemented, data table, syntax, e.g., selection and iteration structures used and user interface methods adapted.
Assessment criteria 3.1 Produce user documentation for a completed programming application
including the user interface design. Assessment criteria 3.2
Develop documentation for a pre-described program application.
Chapter 2 – Understanding a problem and using a computer to solve it
LO4 Create and apply appropriate test schedules Content covered for learning outcome
Error types: The student will apply test schedules on semantic, run-time and
syntaxes.
Test documentation: The student will create a test plan and relate evidence of
testing (may include reading sample inputs from a file or writing test results to a file).
Test data and schedules: The student will test the data and schedules, e.g.,
black box, white box, dry testing and data collection.
Error detection techniques: The student will apply compiler and link error messages, debugging tools and structured walk-through.
Assessment criteria 4.1
Demonstrate discrimination between semantic and syntax errors. Assessment criteria 4.2
Produce test documentation. Assessment criteria 4.3
Successfully construct and use test data and schedules to detect logic errors.
Assessment criteria 4.4 Use appropriate techniques for detecting errors.
Chapter 3 – Write algorithms in sequential steps
Chapter 4 – The selection control structure: Part 1
Appendix B – Error handling and debugging techniques
Unit 3 - Programming Concepts
Introduction
The student will be introduced to basic programming concepts that will lead to an understanding of a problem and how to use computer technology to
implement a solution to the problem.
3.1 General concepts
Before we can start writing a program to solve a problem, we first need to understand some programming concepts.
Attributes as data
To clearly understand what an attribute is, you need to understand what an
entity is. Each object or thing that you can describe is considered an entity. For instance, when studying, the students can be described. They have a
name, an identity, width, height, eye colour, etc. Now the student will be my entity, and all the describing factors will be my attributes - in other words,
attributes describe an object or entity features.
When completing a form at the library, information about yourself and your current residence are requested. This information is then captured onto the
system to allow you to obtain membership in the library. The information describes you. (You will be the entity and the information will be the
attributes).
In order to write computer programs, such as this library system, the programmer must provide space for the attributes to be stored. This should
not only be stored, but should be retrievable at any given time. To store the
attributes, it should first be identified and then allocated a data type.
Consider the following. John is 20 years old and drives a red City Golf. It is not possible to sum his name with his age. Different attributes need to
have different data types in order to make sense. When writing a program, each attribute in use should be allocated a specific space in which it should be
stored. These attributes will now become variables.
Think of a variable as a bucket that can only hold one item at a time. If I call my bucket “test mark”, I will only be able to store one mark in that bucket.
For example, the first test mark received is 65%. At this time, 65 will be stored in my bucket. The next test mark of 80% will now overwrite the
previous mark. The number in the bucket now is 80.
3.2 Data types Each declared variable should be allocated a data type. Data types will
determine the possible values that can be considered as valid input.
Numeric variables
This type of variable can be used on numbers where calculations should take
place.
Data Type Definition Example
Integer Contains positive or negative whole numbers (signed or unsigned)
32, -12, 0
Real Contains positive or negative
fractions or decimals, regardless of decimal places. Floating point
numbers
16.35, 0.2, -987.334
Non-Numeric variables All other variables should fall into one of the below categories:
Data Type Definition Example
Character A single letter, number or special
character.
“M”, “7”, “#”, “!”
String Consist of two or more characters combined
“Rupert”, “Error message”, “ABC” or
“123”
Boolean Can only contain true or false. This
relates back to “Yes” and “No”
Statement: The book
relates to the subject Answer: No, 0
Boolean Value: False
When a numeric value is declared as a character, it cannot be regarded as a
numeric value, and thus no calculation can be done on it.
Numbers such as telephone numbers should not be defined as number, rather as string as no calculation will be done on the number. The initial “0” in front
of the telephone number will be discarded as a numeric 01 means exactly the same as 1.
Refer to pages 4 – 7 (Pretorius & Erasmus, 2012). Variables
Exercise (Pretorius & Erasmus, 2012)
Description Variable name Variable Type Possible value
Colour of dress
Age in years
Salary in R/C
Class code (K,L or M)
Constant
A constant is a fixed value that cannot change throughout the entire program.
This variable can be of any data type.
Examples of constants:
The V.A.T. percentage for South Africa is 14% There are always 24 hours in a day
The value of pi is always 3.14159
The number of days in a year cannot be represented as a constant nor can the number of weeks in a month. (Explain why.)
Arrays
An array consists of a number of related variables. At any given time, the
array can hold numerous values but identical data types. For example, an array cannot store your name and your age at the same time, because they
are of different data types – name is of string data type and age is an integer.
Think of it as a row of “buckets”. When you need a value from one of the buckets, you will refer to the number in the row, for example, row number 6.
Arrays work with index numbers and typically start at zero (0).
Properties of arrays (Pretorius & Erasmus, 2012): It has a single name
A single variable in an array is called an element All the elements in an array are the same data type
The position of an element in an array is called an index.
Working example: If we would like to add the names of the months into an array, we would
declare a variable of type string, for example monthName. To reference January, we would refer to monthName[0]. December would thus be referred
to as monthName[11].
Refer to pages 155 – 168 (Pretorius & Erasmus, 2012). Arrays
Exercise
What is a one-dimensional array?
Draw and fill out a 3 X 1 and 3 X 3 dimensional array.
3.3 Analysing and solving problem
Before we can attempt to solve a problem, we need to understand the problem. According to (Pretorius & Erasmus, 2012), there are three steps that
can be followed in order to ensure that you understand the problem:
1. Read the problem carefully 2. Understand what the problem entails
3. Only then write down the steps to solve the problem.
The steps written down to solve the problem are called an algorithm. According to (Pretorius & Erasmus, 2012), “an algorithm must be written in
such a way that it is ambiguous and precise. The computer cannot think for itself – you need to tell the computer exactly what to do”. An algorithm is
divided into three phases:
1. What data you have available 2. How the problem is going to be solved
3. What the required results will be.
Input is processed to produce meaningful output.
People write programs to perform certain tasks. A program task could be to perform calculations or to make decisions based on the value of one or more
variables. A program could also be used to compare values and perform a certain action based on the outcome. For these actions, programmers make
use of the following operators:
Arithmetic Logical.
Input Process Output
Arithmetic Operators
These operators are used to make calculations. It tells the computer how the
data should be processed.
Operator Description Example Answer
^ Exponentiation 2^3 8
- Negation (Not) -True False
* Multiplication 3* 4 12
/ Division 6 / 3 2
\ Integer Division 36\5 7
Mod Modulus arithmetic 37 mod
5
2
+ Addition 4 + 10 14
- Subtraction 13 – 7 6
Refer to page 10 - 15 (Pretorius & Erasmus, 2012). Arithmetic expressions
and equations.
Exercise (Pretorius & Erasmus, 2012):
Calculate the value of x in each of the following statements: X = g -5 + 14 mod h ^ 2, where g = 12 and h = 1
X = 35 mod y – (z * w + y / 3) + y * w, where w = 5, y = 24, z = 3
Logical operators
The use of logical operators results in only one of two values, TRUE or FALSE.
Operator Description Example Answer
AND Requires both variables/conditions to be
TRUE for the result to be TRUE True
AND False
False
OR Requires either variable/condition to be TRUE for the result to be TRUE
True OR False
True
NOT Returns TRUE if the variable/condition is
FALSE and vice versa NOT True False
Logic operators are also called logical gates. Logical gates can be combined in various ways to create some of the important components of computers, such
as the memory registers.
Logic gates are explained as follows: Switching circuits that perform certain simple operations on binary
signals Have one or two inputs
Have one output Inputs and output is one bit in size with a value of either 0 (false) or 1
(true)
Basic building blocks of computers and all other digital devices Can be combined to perform useful and more complex functions.
Refer to pages 54 - 57 (Pretorius & Erasmus, 2012). Logical Operations
Exercise (Pretorius & Erasmus, 2012): Evaluate the following expressions:
D OR K AND NOT S; where D = TRUE, K = FALSE, S = TRUE M > 7 AND D < S ^ 2; where M = 7, D = 8, S = 4 NOT F OR E AND D + C = A; where A = 5, C = 12, D = -4, E = TRUE and F = FALSE
Relational operators
Comparison operators compare two numeric or two character values. A numeric value cannot be compared with a character value.
Operator Description Example
= Equal to A = 10
> Greater than number > 50
< Smaller than total < 21
<> Not equal to age <> 0
>= Greater and equal to Weight <>35
<= Smaller and equal to SubjectCount <=6 Refer to pages 52 - 53 (Pretorius & Erasmus, 2012). Relational Operations
Exercise (Pretorius & Erasmus, 2012): Evaluate the following expressions:
A + T <> (A + B) * 4; where A = 4, B = 17 and T = 20
“true” = 30
3.4 Program flowcharts After a problem has been analysed, the program to be used in solving the
problem must be designed. The result of this design process is a program flowchart. The program flowchart illustrates the logic of the program and gives
details on manipulating the data. It is less costly to determine, arrange and rearrange complex logic on a flowchart than to correct logic errors in an
implemented program.
A program flowchart is vital, if the program is to be maintained easily and efficiently or if modifications are necessary. The program flowchart is used to
show the steps in the computer programs and the logic required for each process. Program flowcharts are constructed with a set of standardised
symbols that make it easier for persons other than the original programmer to
read and maintain the program.
Refer to pages 58, 66, 72 – 73, 81, 83, 112 – 116, 145 – 146 (Pretorius & Erasmus,
2012).
For example, print the total age of 10 students.
Source: (Labuschagne, 2012)
Example 2:
Calculate pay for each employee in a company. Print these details on a
monthly report.
Each employee record in the employee file holds the employee number, name, hours worked and the rate of pay. The output for each employee includes the
employee number, name, hours worked, rate of pay and the gross pay. Processing continues until an employee number of 0000 is read.
Source: (Labuschagne, 2012)
3.5 Exercises Complete the following exercises from the prescribed textbook:
Question 1 and 2 (page 16) Question 1 – 4 (page 57)
UNIT 4 - Program Control
Structures
Introduction Depending on the result of a decision or condition made in the program,
control may be directed to another part of the program. This is done with the use of a control structure. The following control structures will be discussed:
1. IF statements 2. SELECT CASE statement
3. FOR Loop
4. DO Loop.
4.1 IF statements
“If-statements” are also called if-then statements. The computer executes a statement (the if-statement) and based on the result, performs a resulting
action (then or else). If the condition is true, the “then” part will be executed. If the condition is false, the “else” part will be executed.
The basic layout of an if-statement is as follows:
IF condition THEN action when condition is true
ELSE action when condition is false.
For example, test if the student passed a specific module by using the module result as input:
If result >= 50
Then message = “Student passed” Else message = “Student failed”.
The above example will output a message “Student passed” for any value that
is greater or equal to 50, and a message of “Student failed” for any input value less than 50.
If-statements can also have more than one condition. This is called a
compound if-statement.
For example, to qualify for your learners license, you need to be a South African Citizen and be older than 16.
If nationality = “RSA” AND age >=16 Then qualify = true
Else qualify = false.
The above example uses an AND logical operator that states that both
conditions needs to be true in order for the system to execute the then part.
Refer to pages 66 – 76 (Pretorius & Erasmus, 2012).
Exercise (Pretorius & Erasmus, 2012)
Study the following code: C = A * B + 3 mod 7
If A > C then
Display “A has higher value than C”
B = A – C
Else
Display “A is equal to or less than C”
B = C – A
Endif
Display “the value of B is now “, B
Display “The value of C is now “, C
What will be displayed if the code is executed and the following values
apply? A = 5 and B = 7
What will be displayed if the code is executed and the following values
apply? A = 12 and B = -9
4.2 SELECT CASE statements
The select...case statement is used in menu-like situations. It allows code to
be written where a number of if-statements would otherwise follow one another. It is a neater, more concise and better programming technique to use
a select...case statement rather than successive if-statements.
The basic layout of a Select Case statement: SELECT case Number
Case 1 List statements here
Case 2 List statements here
Case 3
List statements here ELSE
List statements here END-SELECT
For example, commission is paid out based on the amount of sales made.
Different categories will earn different commission rates. Total sales of less than 25 000 will earn 2.5% commission; sales of less than 50 000 will earn 3%
commission; and sales of less than 100 000 will earn 5% commission. Sales of more than 100 000 will earn 7.5 % commission.
SELECT case Sales
Case < 25 000 Commission = 2.5
Case 25 000 to 49 999
Commission = 3 Case 50 000 to 100 000
Commission = 5 Else Commission = 7.5
END-SELECT
Refer to pages 98 – 107 (Pretorius & Erasmus, 2012). The Select Case Structure
Exercise
Write a select case statement to calculate the new value of the price variable depending on the grade, based on the table below.
Grade Processing of price
A Double the price
B Add VAT of 14%
C Deduct a discount of 8.75%
Other Add R5 if the price is higher than R50 Subtract R4 if the price is equal to R50 or lower
4.3 FOR loops
The-for statement is used in programming when a block of code is to be executed a specific number of times.
The basic layout of a FOR-loop is:
FOR counter = begin-value TO end-value Perform actions listed here
NEXT counter
For example, calculate the average temperature for a given week.
FOR counter = 1 TO 7 Input “day temperature”
Add “day temperature” to total NEXT counter
Calculate average total / 7
The above example will perform the two actions (input temperature and add to total) seven times. The average will be calculated outside of the loop.
Refer to pages 110 – 128 (Pretorius & Erasmus, 2012). Iteration using a fixed
count loop.
Exercise Write a code to calculate and display the sum of the first five odd
numbers.
4.4 DO loop
A DO loop is used when the number of times of execution is unknown. The condition will be tested each and every time.
There are two types of DO loops.
DO WHILE DO UNTIL.
Do-While statement
The Do-While statement is executed only while a specific condition is true. As
soon as the condition tests false, the loop exits. The condition is checked before the loop is entered. A lecturer will first check if there are students in a
class before starting the lecture.
The basic layout of a Do-While statement is:
DO WHILE condition is true List all the statements here
LOOP
For example, to print a list of student names for a course, we will first have to check if any students are registered for the course.
Read student name, surname
DO WHILE student name not empty Print Student Name, Surname
LOOP
Refer to pages 133 – 146 (Pretorius & Erasmus, 2012). Iteration using a DO-
loop.
4.5 Do UNTIL loop
The do...until statement is very similar to the do-while control statement in
that both are conditional loops. However, unlike the do-while statement, the do...until statement does not test the condition before entering the loop. It
tests the condition at the end of the loop. This means that a do...until loop will always execute at least once, whereas a do-while loop may never execute.
The basic layout of a Do-Until loop DO
List all the statements here LOOP UNTIL condition is true
For example, calculate the wages for all employees. It is assumed that the
company will at least have one employee.
Input hours worked
DO Input pay rate
Calculate wage as hours worked * Pay rate Print wage
Input hours worked LOOP UNTIL hours worked = 0
Refer to pages 133 – 152 (Pretorius & Erasmus, 2012). Iteration using a DO
loop.
4.6 Exercises Complete the following exercises from the prescribed textbook
Exercise 1 – 4 (page 65) Exercise 1 – 3 (pages 70 – 71)
Exercise 1 – 3 (pages 103 – 107) Exercise 1 – 9 (pages 126 – 128)
Unit 5 - Programming Standards
Introduction Standards have been around for hundreds if not thousands of years. We follow
standards to provide a solid foundation for our work. Writing a program should be no different. Certain standards need to be followed to ensure that the
quality of our work is acceptable.
5.1 Naming a variable As discussed in Unit 3, a variable is used by the computer to store a specific piece of information. In order to access that information, we need to use the
variable name. Imagine the confusion if you are working on a system where the variable names make no sense. Number 1 is the name of the variable that
stores the item quantity; number 2 is the name of the variable that stores the
invoice number; number 3 is the name of the variable that stores the product ID. By the time all the variables are named, you will have no idea which
number relates to which piece of information.
Following the rules as set out in (Pretorius & Erasmus, 2012), ensures that your program is understandable and that it follows some form of standard.
The name must be unique
The name must be descriptive The name may not contain spaces. When joining two or more words to
form a variable name, use uppercase for the first letter of each word, example itemPrice or invoiceDate
The name can contain numbers and letters, but not numbers alone. Example file13
A variable must start with a small letter
A variable name may not contain special characters such as !,@,#,$, etc. A variable name should be as short as possible (while still being
descriptive).
Refer to page 4 (Pretorius & Erasmus, 2012). Naming a variable
5.2 Writing algorithms
The following rules should be followed when writing algorithms:
The name must describe the function or purpose of the algorithm That last statement is always the terminator (end statement)
Predetermined words should be used Comments should be used explaining the statement. Comments are
indicated with the use of a tilde sign (~)
Calculations can be done using equations.
5.3 Using function procedures
A function procedure (or function) consists of a number of statements used to execute a single task. A function always returns a value and can receive
numerous or no variables (called parameters).
A program that needs to calculate a total based on a specific formula can be created as a function. For example, the student DP is calculated as 15% per
assignment and 10% per test. The DP counts 50% of the year mark. In order to create the function, we need to determine the parameters.
CalculateDP (Asg1, Asg2, Test1, Test2)
DP = (Asg 1 + Asg2) * 0.15 + (Test1 + Test2) * 0.1 Return DP
The above function needs to be called as part of a calculation or by a variable that will store the value of the answer. To call the function by a variable, we
can use the following statement in our main program:
studentMark = Function CalculateDP (assignment1, assignment2, testMark1, testMark2)
This can also be done as part of a calculation as indicated below:
Result = Function CalculateDP (assignment1, assignment2,
testMark1, testMark2) + Exam * 0.5
Refer to pages 184 - 187 (Pretorius & Erasmus, 2012). Naming a variable
When a function receives parameters, the order of the parameters is very
important.
Important notes for using functions
The function and the main program are two separate entities
The main program and function communicates using parameters If the function does not receive the parameters in the same order, the
result will be calculated incorrectly There may be more than one return statement in a function, but only
one of the return statements can be executed, and execution of this return statement must be just before the end statement.
Refer to pages 187 – 190 (Pretorius & Erasmus, 2012). Calling a function and
using a function
5.4 Sub-procedures
A sub-procedure (also called a procedure) can also be used to solve a specific part of a problem and has the following properties:
Can receive parameters It does not return a value
It can change the value of reference parameters.
A reference parameter should be used when you need to change the value of an actual parameter variable in the procedure. When you declare a reference
parameter, the function call will pass the memory address of where the actual parameter, instead of copying the parameter value into the formal parameter.
Procedures are called by their name.
The basic syntax of calling a procedure is as follows:
Call ProcedureName (argument list)
For example, the following transactions can be captured for a tenant per month: DisplayRental, AssignNewRental, or AccumulateInterestl. The
following procedures should be created:
Sub DisplayRental(Tenant, rentMonth, rentAmount) Display Tenant, “rental for the month of “, rentMonth, “ is R
“,rentAmount End-Sub
Sub AssignNewRental (interestRate, refAmount, refMonthInt)
refMonthInt= refAmount * interestRate / 100 refAmount = refAmount + refInterest
End-Sub
Sub AccumulateInterest(MonthInt, refInterest)
refInterest = refInterest + MonthInt End-Sub
The main program should call these procedures by name:
Call DisplayRental( TenantName, rentPerMonth, amount)
Call AssignNewRental( percInterest, amount, monthInterest) Call AccumulateInterest( monthInterest, Interest)
Refer to pages 192 – 199 (Pretorius & Erasmus, 2012). Sub-procedures
It is possible to send no parameters to procedures or functions. For example,
to display menu options, one can make use of procedures, or when a value must be entered and validated until it is correct. When a correct value is
entered, it must be returned to the calling module.
Exercise Define a reference parameter and how it works
Differentiate between a function procedure and a sub-procedure with examples.
5.5 Variable scope There are four different types of variable scopes:
Local Global
External Static.
Local variables
A local variable can only be used inside the procedure or function where it was first declared.
Global variables
A global variable can be used in the main program and inside procedures or functions.
External variables
An external variable is used externally. External variables are declared outside
any procedure or function.
Static variables
A static variable is a variable that has been declared inside the main program
and re-declared inside a procedure or function. The scope of a static variable is
the procedure where the variable is declared, excluding any other procedures that may contain a variable with the same name.
5.6 Working example
Prompt the user to input the temperature for today and the temperature for
yesterday, in degrees Fahrenheit. The program must convert degrees Fahrenheit to degrees Celsius, then determine and print which of the two days
was the colder.
Assume the temperatures were different for the two days. The code must include a main program, and two functions – one to convert degrees
Fahrenheit to degrees Celsius and one to determine the colder temperature (in
degrees Celsius).
To convert degrees Fahrenheit to degrees Celsius, subtract 32 from °F and take 5/9 of the remainder. For example, converting 212°F to degrees Celsius:
(212 - 32) * 5 / 9 = 180 * 5 / 9 = 100
That is, 212°F converts to 100°C.
First, declare the two functions.
FahrToCelc (temp) newTemp = 5/9 * (temp – 32)
Return newTemp
LowTemp (temp1, temp2)
If temp1 < temp 2 Then Lowest = tem 1
Else Lowest = temp2 Return Lowest
The next step will be to call the function from the main program. Remember
that a function is called by a calculation or by a variable. The main program will contain the following statements:
MainModule Input temp1F, temp2F – get values from users
Temp1C = Function FahrToCelc(temp1F) Temp2C = Function FahrToCelc(temp2F)
LowestTemp = Function LowTemp(Temp1C, Temp2C) Print LowestTemp
End.
5.7 Exercises Complete the following exercises from the prescribed textbook:
Exercise 1 – 5 (pages 190 – 193) Exercise 1 – 4 (pages 201 – 204)
Unit 6 - Documentation and Error Prevention
Introduction
When a new system or program is created, documentation is used to indicate what the program is about; when it was created; by whom it was created; how
the program functions; error messages that may occur during the interactivity phase of the program, etc. Documentation is used to document everything that
is part of the program.
6.1 Relevant program documentation
Different types of projects call for different types of documentation.
Documentation can be displayed in any form. This can be represented in the form of text, video, audio, etc. The majority of documentation consists of text
files such as Word or HTML documents.
All programs should be documented adequately so that: People who have to maintain the code know what was intended by every
single line of code (program design documentation and source code documentation)
People who have to use the program know how to run it, what to expect, and what output will be displayed or printed (user documentation).
Code comments
When mentioning documentation, code comments are probably the most common understanding amongst programmers. For any serious program that
you develop, it is almost guaranteed that either you or another programmer will have to return to the code one day to correct a problem or add a new
feature.
It is thus important that your code is easy to read. It should also contain comments that clearly explain what is intended by structures and blocks in the
code. If a programmer who has to maintain the code has to try to understand what it was that you intended, it wastes time and also opens the possibility
that the intention may be misunderstood, which may lead to further problems.
A well-documented program will be easier to follow, modify, debug and maintain than a program that does not contain sufficient documentation.
Comments stating what steps are intended should be included for each
program flow or control statement (e.g. for, if, while, etc.). Any block of code should have a short explanation of its purpose.
Code should also include a prologue. A prologue can be found at the top of the file and contains the following information:
Name of the file Name of the author
Date created Operating system
Description of the code.
For example:
~ File name: ConvertingTemps.exe ~Author: John Smith
~Created: January 2014 ~ Operating System: Windows 7
~ConvertingTemp is an application that allows users to instantly convert any temperature from Celsius to Fahrenheit, and Fahrenheit to Celsius.
Other functions of this application are to compare different temperatures and display of two temperatures.
User interface design
The first part that should be documented about your interface is the structure and navigation. This will indicate how different menus or pages link together
and how to navigate back and forth in the program.
Source: http://infodesign.com.au/wp-content/uploads/uidocumentation.pdf
User guide
The old saying of “when all else fails, read the manual” is commonly used
these days. So why do people only use documentation as a last resort? User
guides are often hard to follow and some tend to bury the information that users need amongst other related but irrelevant information.
The purpose of a user guide is to indicate to the user how to use and interact
with a specific program. The guide should focus on the needs of the user, support the task at hand and be available when needed.
Screenshots should be included ONLY to support written documentation.
NOTE: A user guide is not a collection of screenshots!
6.2 Error detection
Error detection is the ability to detect any errors that may occur during the
writing, compiling and running of a program. Error handling or correction is the
ability to correct and fix the errors.
Logical errors
Even if a program is carefully planned and written, you can never assume that the algorithm used is error-free. Logical errors, also known as semantic
errors, are the most difficult to find and to correct. Some programmers tend to forget that the computer does not have an overall idea of the program it is
executing. Therefore, computers cannot correct logical errors.
Logical errors can be checked by performing desk checking. Desk checking is used to manually validate a program by using trace tables. The important data
of the program (input, output, variables, values, etc.) is written down on paper and the programmer steps through the design, making changes where needed
on the paper.
When performing desk checking, a set of test data should be identified and
their results calculated beforehand. The result received when desk checking is performed should be the same as the test data result. Test data should
include valid-, invalid-, highest valid- and lowest valid- values.
Refer to pages 36 – 45, 237 - 240 (Pretorius & Erasmus, 2012). Testing the logic of an algorithm.
Syntax errors
Syntax errors occur while the program is being written. Syntax errors are also
known as grammatical errors. An example is the developer spelling a function
or procedure name incorrectly. This type of error is easy to correct.
Refer to page 236 – 240 (Pretorius & Erasmus, 2012). Error handling and debugging techniques.
Data errors
Data errors are usually found in the input data. Data errors are also called
runtime errors. When writing any program, it is necessary to make sure that
the quality of the runtime error-handling is good. This will prevent the program from crashing. The users do not have any resources or files to help them when
a runtime error occurs. The user cannot debug or fix a runtime error. Only the developer knows the code and knows how to debug and fix runtime errors. An
example of a runtime exception is a user inputting a string value instead of an integer value.
Refer to pages 236 – 240 (Pretorius & Erasmus, 2012). Error handling and
debugging techniques
6.3 Program testing
Program testing, as the name suggests, involves testing the program. Once the program is completed, it is tested for any errors or problems it might have.
Normally in big organisations, teams consist of developers who develop the program and testers who test the program once it is developed.
Before any testing can occur, a test plan should be created. A test plan is a document which displays the test cases planned for a program or module, their
purpose, inputs, expected outputs and criteria for success. There is no set layout for a test plan. For the purpose of this course, we will use the layout as
indicated below.
A test plan should have: The name of the program that will be tested
The names of the people who are preparing the testing A testing strategy indicating each test that will be performed, its
participants and the method that will be used for the testing Requirements for testing the data (hardware and software)
Test data that will be used The features that will be tested.
Refer to pages 46 – 51 (Pretorius & Erasmus, 2012). Calculating the outcome of an algorithm
There are numerous types of program testing that should be performed before
the program can be labelled as acceptable. These include:
Walkthroughs
Walkthroughs are similar to desk checking and are known as a group activity. The program is tested manually by keeping track of the program’s data using
paper or a blackboard. Walkthroughs are mostly used for discussion of the way the programmer chooses to implement or design the program’s
requirements.
Unit testing
Unit testing is where the complete program is broken down into smaller parts
for the testers to verify. Once the first part of the program is completed, it is
tested. When using this method, the testers will not have a stack of testing to complete at once after the program is completed. Unit testing is known as
testing a module or procedure by itself.
Data coverage
Data coverage is also known as black-box testing. Data coverage is where a set of valid inputs is extremely small and is verified by a sub-program by
testing it against every possible input value. Using this method will ensure that the program meets the desired requirements and values that may be used.
Code coverage
Code coverage is also known as white-box testing. Code coverage is similar to
data coverage, but instead of testing the input values, the execution of statements or groups of statements are tested. This method will verify the
number of times the statements are executed and if each statement is executed correctly.
6.4 Exercises
Complete the following exercises from the prescribed textbook
Exercise 2 – 3 (pages 48 – 49)
Exercise 1 – 2 (page 240)
Glossary:
Algorithm A set of instructions written in a specific sequence to solve a problem
Array Variables of the same data type grouped under a single name
Boolean A variable that can take only one value, True or False
Character A single number, letter or special character
Constant A fixed value that cannot change throughout the entire
program. This can be of any data type
Data A collection of facts, such as values, measurements or readings
Data errors These errors are referred to as unchecked exceptions and occur while the program is executing
Data
validation
A test to check that input data can be used by the program
in its current format
For loop Used to repeat a section of code a number of times whit a
control variable that has a differing value each time through the loop
Function call A statement that activates or calls a function from another
part of the algorithm
Function
procedure
Instructions that perform a specific task that is often
repeated are coded separately so that they can be reused whenever required
If statement An instruction that controls program flow by allowing a
section of code to execute only when a specified condition is true
Input The data entered into a system for processing into output
Integer A variable type that contains a whole number that has no fractional or decimal part
Logical errors
An error resulting from faulty reasoning; a bug in a program that causes it to terminate abnormally or to
produce incorrect output
Operator A symbol used in an expression or equation, which tells the computer how to process the data
Parameters Data in the form of variables or values that is sent to a function or procedure so that it can perform the task it has
to do
Real number A variable that contains a positive or negative number with a decimal part
String A variable consisting of two or more alphanumeric characters
Sub-
procedure
A separate procedure that consists of lines of code to solve
a specific part of a larger problem
Syntax error An error in the grammar of a statement
Test Plan A test plan is a document which displays the test cases
planned for a program or module, their purpose, inputs, expected outputs, and criteria for success
Walkthrough The program is tested manually by keeping track of the program’s data using paper or a blackboard
Bibliography Gaddis, T. (2013). Starting out with Programming Logic & Design. United states: Pearson Education.
Labuschagne, C. (2012). Fundamentals of Computer Science. South Africa: CTI
Education Group and London School of Business and Management.
Pretorius, C. M. & Erasmus, H. G. (2012). Basic Programming Principles. South
Africa: Pearson Education - Juanita Pratt.
RichardJohnsonbaugh. (2009). Discrete Mathematics. United States of America: Pearson Education.
Bedfordview Campus 1st Floor, 14 Skeen Boulevard Bedfordview, 2008
P.O. Box 1389, Bedfordview, 2008 Tel: +27 (0)11 450 1963/4, Fax: +27 (0)86 686 4950
Email: [email protected]
Bloemfontein Campus Tourist Centre, 60 Park Avenue, Willows, Bloemfontein, 9301
P.O. Box 1015, Bloemfontein, 9300 Tel: +27 (0)51 430 2701, Fax: +27 (0)51 430 2708
Email: [email protected]
Cape Town Campus The Brookside Building, 11 Imam Haron Street (old Lansdowne Road), Claremont, 7708 P.O.Box 2325, Clareinch, 7740 Tel: +27 (0)21 674 6567, Fax: +27 (0)21 674 6599
Email: [email protected]
Durban Campus 59 Adelaide Tambo Drive (old Kensington Drive) Durban North, 4067 P.O. Box 20251, Durban North, 4016 Tel: +27 (0)31 564 0570/5, Fax: +27 (0)31 564 8978
Email: [email protected]
Durbanville Campus Kaapzicht, 9 Rogers Street, Tyger Valley, 7530 P.O. Box 284, Private Bag X7 Tyger Valley, 7536 Tel: +27 (0)21 914 8000, Fax: +27 (0)21 914 8004
Email: [email protected]
East London Campus 12 Stewart Drive, Berea, East London, 5241 PostNet Suite 373 Private Bag X9063, East London, 5200 Tel: +27 (0)43 721 2564, Fax: +27 (0)43 721 2597
Email: [email protected]
Nelspruit Campus 50 Murray Street Nelspruit, 1200
P.O. Box 9497, Sonpark, Nelspruit, 1206 Tel: +27 (0)13 755 3918, Fax: +27 (0)13 755 3918 Email: [email protected]
Port Elizabeth Campus Building 4, Ascot Office Park Cnr Ascot & Conyngham Roads, Greenacres, 6065
P.O. Box 40049, Walmer, 6065 Tel: +27 (0)41 374 7978, Fax: +27 (0)41 374 3190 Email: [email protected]
Potchefstroom Campus
16 Esselen Street Cnr Esselen Street & Steve Biko Avenue Die Bult, Potchefstroom, 2531 P.O. Box 19900, Noordbrug, 2522 Tel: +27 (0)18 297 7760, Fax: +27 (0)18 297 7783 Email: [email protected]
Pretoria Campus
Menlyn Corporate Park, Building A 175 Corobay Avenue (Cnr Garsfontein), Pretoria, 0181 PostNet Suite A147, Private Bag X18 Lynnwood Ridge, 0040 Tel: +27 (0)12 348 3060, Fax: +27 (0)12 348 3063 Email: [email protected]
Randburg Campus
6 Hunter Avenue, Cnr Bram Fischer Drive Ferndale, Randburg, 2194
P.O. Box 920, Randburg, 2125 Tel: +27 (0)11 789 3178, Fax: +27 (0)11 789 4606 Email: [email protected]
Vanderbijlpark Campus
Building 2, Cnr Rutherford & Frikkie Meyer Blvds Vanderbijlpark, 1911
P.O. Box 6371, Vanderbijlpark, 1900 Tel: +27 (0)16 931 1180, Fax: +27 (0)16 933 1055 Email: [email protected]
Group Head Office Fourways Manor Office Park, Building 1 Cnr Roos & Macbeth Streets, Fourways, 2191
P.O. Box 1398, Randburg, 2125 Tel: +27 (0)11 467 8422, Fax: +27 (0)11 467 6528 Website: www.cti.ac.za