Procedural Programming C_ITPP111

Compiled by Tom Zimba

Quality assured by Marwick Makwindi

Version 1.0

NQF Level 5

Credit value: 12

 January 2016 CTI EDUCATION GROUP

© CTI Education Group

TABLE OF CONTENTS

INTRODUCTION ...... 5 Module aim ...... 5 Module description ...... 5 Learning outcomes and assessment criteria ...... 5 Summary of learning outcomes and assessment criteria ...... 6 Module content ...... 6 Lectures...... 8 Review questions and Let’s do it exercises ...... 8 Information resources ...... 8 Prescribed textbook ...... 8 Recommended information sources ...... 9 Textbooks/e-Books ...... 9 Online documents ...... 9 Using this Study Guide ...... 9 Purpose ...... 10 Structure ...... 10 Individual units ...... 10 Glossary ...... 11 The use of icons ...... 11 Alignment to prescribed textbook ...... 12 Study Guide/prescribed textbook alignment ...... 12 Concluding remarks ...... 13 UNIT 1 – PRINCIPLES OF PROCEDURAL PROGRAMMING ...... 14 Learning objectives ...... 14 Prescribed reading ...... 14 Introduction ...... 14 1.1 Characteristics of programming ...... 14 1.1.1 Low-level ...... 15 1.1.2 High-level ...... 15 1.2 Interpreters and compilers ...... 16 1.3 Generations of programming languages ...... 17 1.4 Paradigms In programming ...... 18 1.4.1 Procedural languages ...... 18 1.4.2 Object-oriented languages ...... 18 1.4.3 Event-driven languages ...... 19 1.5 Data Types ...... 19 1.6 Variables...... 19 1.7 Good Programming practice ...... 20 1.7.1 Use of Comments ...... 20 1.7.2 Indentation ...... 20 1.7.3 Variable naming ...... 20 1.7.4 Use of modules ...... 20 1.8 Exercise 1 ...... 21 Concluding remarks ...... 21 UNIT 2 – DESIGN PROCEDURAL PROGRAMMING SOLUTIONS ...... 22 Learning objectives ...... 22 Prescribed reading ...... 22 2.1 Introduction ...... 23 2.2 Requirements specification ...... 23 2.3 Program design tools ...... 24 2.3.1 Flow Chart ...... 24 2.3.2 Pseudo code ...... 25 2.4 Technical Documentation ...... 25 2.5 Exercise 2 ...... 26 Concluding remarks ...... 26 UNIT 3 – IMPLEMENT PROCEDURAL PROGRAMMING SOLUTIONS ...... 27

© CTI Education Group

Learning objectives ...... 27 Prescribed reading ...... 27 Introduction ...... 28 3.1 Modular design ...... 28 3.1.1 Benefits of using modules ...... 28 3.1.2 Calling a module ...... 29 3.2 Modules in procedural programming ...... 30 3.2.1 Function ...... 30 3.2.2 Procedures ...... 31 3.3 Exercise 3 ...... 31 3.4 Types of variables ...... 31 3.4.1 Local ...... 31 3.4.2 Global ...... 32 3.5 Passing arguments to modules ...... 33 3.5.1 Argument and parameter compatibility ...... 35 3.5.2 Passing multiple arguments ...... 35 3.6 Types of passing arguments ...... 36 3.6.1 Passing arguments by value ...... 36 3.6.2 Passing arguments by reference ...... 36 3.7 Exercise 4 ...... 36 3.8 Decision structures ...... 37 3.8.1 If–Then ...... 37 3.8.2 Boolean expressions and relational operators ...... 37 3.8.3 If-Then-Else ...... 38 3.8.4 The If-Then-Else If statement...... 39 3.8.5 The case structure ...... 40 3.9 Logical operators ...... 40 3.10 Boolean variables ...... 41 3.11 Exercise 5 ...... 42 3.12 Repetition structures ...... 42 3.12.1 The While loop ...... 42 3.12.2 The Do-While loop ...... 43 3.12.3 The Do-Until loop ...... 45 3.13 Deciding which loop to use ...... 46 3.12.1 The For loop ...... 46 3.14 Exercise 6 ...... 49 3.15 Data structures ...... 49 3.15.1 Arrays ...... 49 3.15.2 Array elements and subscripts ...... 50 3.15.3 Assigning values to array elements ...... 51 3.15.4 Using a loop to step through an array ...... 51 3.15.5 Array initialization ...... 52 3.15.6 Sequentially searching an array ...... 53 3.15.7 Totalling the values in an array ...... 54 3.15.8 Finding the lowest value in an array ...... 54 3.15.9 Parallel arrays ...... 55 3.16 Exercise 7 ...... 57 3.17 Two-dimensional arrays ...... 57 3.16.1 Declaring a two-dimensional array ...... 58 3.18 File structures...... 59 3.18.1 Types of files ...... 60 3.18.2 File access methods ...... 60 3.18.3 Creating a file and writing data to it ...... 60 3.18.4 Delimiters and the EOF marker ...... 61 3.18.5 Using loops to process files ...... 62 3.18.6 Processing records ...... 64 3.18.7 Writing records ...... 64 3.18.8 Reading records ...... 65 3.18.9 Managing records ...... 66

© CTI Education Group

Concluding remarks ...... 67 UNIT 4 – TEST PROCEDURAL PROGRAMMING SOLUTIONS ...... 68 Learning objectives ...... 68 Prescribed reading ...... 68 Introduction ...... 69 4.1 Error-checking mechanisms ...... 69 4.1.2 Defensive programming ...... 73 4.2 Supportive documentation ...... 73 4.2.1 Onscreen manuals ...... 74 4.2.2 The classical “help” function ...... 75 4.2.3 Wizards ...... 75 4.2.4 “Helpers” ...... 75 4.3 Design reviews ...... 77 4.4 Exercise 8 ...... 77 Concluding remarks ...... 77 GLOSSARY ...... 78 BIBLIOGRAPHY ...... 79

© CTI Education Group Introduction Page 5

Introduction Welcome to Procedural Programming. This unit serves as an introduction to the course. We will provide you with a description of the course and a summary of the learning outcomes and assessment criteria.

Module aim To provide students with an understanding of the principles of procedural programming and to enable them to design and implement procedural programming solutions.

Module description Irrespective of framework or delivery platform, the development of procedural code is still at the core of many commercial application development projects. Event-driven systems and object-oriented platforms all use procedural code for the critical command content of their objects, events and listeners.

This unit allows students to become familiar with the underpinning principles of procedural programming. Many languages have the capacity to develop procedural code and it is not important which language is chosen for this unit.

Ideally, for students who are new to programming, this unit would be considered the starting point before progressing onto one (or all) of the many programming units. Whilst the student is not expected to develop any complex code in this unit, the foundations will enable the development of their programming skills.

Learning outcomes and assessment criteria On successful completion of this module, you will:

• Understand the principles of procedural programming

• Be able to design procedural programming solutions

• Be able to implement procedural programming solutions

• Be able to test procedural programming solutions

© CTI Education Group Introduction Page 6

The following table outlines the assessment criteria that are aligned to the learning outcomes.

Summary of learning outcomes and assessment criteria

Learning outcomes Assessment criteria to pass LO1 1.1 Discuss the principles, characteristics and features of Understand the principles of procedural programming procedural programming 2.1 Identify the program units and data and file LO2 structures required to implement a given design Be able to design procedural 2.2 Design a procedural programming solution for a programming solutions given problem 3.1 Select and implement control structures to meet the LO3 design algorithms Be able to implement procedural 3.2 Correctly use parameter passing mechanisms programming solutions 3.3 Implement a procedural programming solution based on a prepared design 4.1 Critically review and test a procedural programming solution 4.2 Analyse actual test results against expected results to identify discrepancies LO4 4.3 Evaluate independent feedback on a developed Be able to test procedural procedural program solution and make programming solutions recommendations for improvements 4.4 Create onscreen help to assist the users of a computer program 4.5 Create documentation for the support and maintenance of a computer program

These outcomes are covered in the module content and they are assessed in the form of written assignments and semester tests. If you comply with and achieve all the pass criteria related to the outcomes, you will pass this module.

Learning and assessment may be performed across modules, at module level or at outcome level. Evidence may be required at outcome level, although opportunities exist for covering more than one outcome in an assignment.

Module content 1. Understand the principles of procedural programming

Characteristics of programming: low-level languages; high-level languages; generations, e.g. first, second, third, fourth, fifth; programs; applications; instructions; algorithms

Types of language: procedural languages; object-oriented; event-driven; others, e.g. script and mark-up languages; simple overviews and uses

© CTI Education Group Introduction Page 7

Reasons for choice of language: organisational policy; suitability of features and tools; availability of trained staff; reliability; development and maintenance costs; expandability

Data structures: variables, e.g. naming conventions, local and global variables, arrays (one-dimensional, two-dimensional); file structures; loops, e.g. conditional (pre-check, post-check, break-points), fixed; conditional statements; case statements; logical operators; assignment statements; input statements; output statements

Data types: constants and literals; integer; floating point; byte; date; Boolean; others, e.g. character, string, small int; choice of data types, e.g. additional validation, efficiency of storage

Programming syntax: command rules, variable declaration

Standards: use of comments, code layout, indentation

2. Be able to design procedural programming solutions

Requirements specification: inputs, outputs, processing, user interface; constraints, e.g. hardware platforms, timescales for development; units; data; file structures

Program design: tools, e.g. structure diagrams, data flow diagrams, entity relationship models, flow charts, pseudo code

Technical documentation: requirements specification; others as appropriate to language, e.g. form design, flowcharts, pseudo code, structured English, action charts, data dictionary, class and instance diagrams

3. Be able to implement procedural programming solutions

Modular design: elements, e.g. functions, procedures, method, widgets, graphical user interface (GUI) components, symbols

Software structures: as appropriate to language chosen, e.g. iteration, decisions, units, functions, procedures; control structures; conditional commands

Parameters: data types, passing data, return values

Scope of variables: global, local, static, overloaded results, instance

Programming: use of programming standards; relationship to program design

© CTI Education Group Introduction Page 8

4. Be able to test procedural programming solutions

Mechanisms: valid declarations, debugging code, checking naming conventions; checking functionality against requirements, error detection, error messages, compiler errors, runtime errors, in code response, dry running

Supportive documentation: test plan; test results; programmer guidance; user guidance; onscreen help

Review: design against specification requirements, interim reviews

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.

Review questions and Let’s do it exercises Students will be required to complete a number of exercises and activities in class. These activities and exercises may also contribute to obtaining a pass, therefore, it is 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 and lab programs 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.

Information resources You should have access to a resource centre or library with a wide range of relevant resources. Resources can include textbooks, e-books, newspaper articles, journal articles, organisational publications, databases, etc. You can access a range of academic journals in electronic format via EBSCOhost. You will have to ask a campus librarian to assist you with accessing EBSCOhost.

Prescribed textbook Gaddis, T. 2016. Starting out with programming logic and design. 3rd edition. Boston: Pearson Education, Inc. ISBN: 9780132805452.

© CTI Education Group Introduction Page 9

Recommended information sources

Textbooks/e-Books Davis, S.R. 2009. C++ for dummies. Hoboken, NJ: John Wiley & Sons.

McBride, P.K. 1997. Turbo Pascal programming made simple. 1st edition. Southampton: Butterworth-Heinemann.

McGrath, M. 2012. C programming in easy steps. Warwickshire: In Easy Steps Limited.

Parkin, A. and Yorke, R. 1995. COBOL for students. 4th edition. Burlington: Butterworth-Heinemann.

Online documents Cplusplus. 2014. [Online] Available at: http://www.cplusplus.com/doc/tutorial/ [Accessed: 15 October 2014].

Cprogramming.com. 2011. [Online] Available at: http://www.cprogramming.com/ [Accessed: 15 October 2014].

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.

Using this Study Guide As we indicated earlier, the prescribed textbook is your main source of information for this module and the Study Guide serves as a guide to the prescribed textbook.

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 master said outcomes; and directs you to the appropriate sections in the prescribed textbook. It is, therefore, 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 module outcomes at the beginning of the Study Guide and at the beginning of each unit.

© CTI Education Group Introduction Page 10

It is essential that you complete the exercises and other learning activities in the Study Guide as your module assessments (examinations, tests and assignments) will be based on the assumption that you have completed these activities.

The Study Guide accompanies the prescribed textbook and, therefore, it should be read in conjunction with such: it should not be deemed as a replacement for the prescribed text.

Purpose The purpose of the Study Guide is to facilitate the learning process and to help you to structure your learning and to master the content of the module. The textbook covers certain themes in detail.

Where applicable, we give more simplified explanations in the Study Guide. It is important for you to work through both the prescribed textbook and the Study Guide attentively and to follow all the instructions set out in the Study Guide. In this way, you should be able to deepen your learning and enhance your chances of success.

Structure The Study Guide is structured as follows:

Introduction Unit 1: Principles of procedural programming Unit 2: Design procedural programming solutions Unit 3: Implement procedural programming solutions Unit 4: Test procedural programming solutions Glossary Bibliography

Individual units The individual units in the Study Guide are structured in the same way and each unit contains the following features, which should enhance your learning process:

Each unit title is based on the title and content of a specific Unit title outcome or assessment criterion (criteria) as discussed in the unit. The unit title is followed by an outline of the learning outcomes and assessment criteria, which will guide your learning process. Learning outcomes and It is important for you to become familiar with the learning assessment criteria outcomes and assessment criteria, because they represent the overall purpose of the module as well as the end product of what you should have learnt in the unit.

© CTI Education Group Introduction Page 11

Learning objectives, which follow the learning outcomes and assessment criteria, are statements that define the expected goal of the unit in terms of the specific knowledge and skills Learning objectives that you should acquire as a result of mastering the unit content. Learning objectives clarify, organise and prioritise learning and they help you to evaluate your own progress, thereby taking responsibility for your learning. The learning objectives are followed by information outlining prescribed reading. This section indicates the relevant sections Prescribed reading in the prescribed textbook that you are expected to study for the unit. The prescribed reading section is followed by an introduction Introduction that identifies the key concepts of the unit. The content of each unit contains the theoretical foundation of the module and is based on the work of experts in the field of Content this module. The theory is illustrated by means of relevant examples. The concluding remarks at the end of each unit provide a brief Concluding remarks summary of the unit as well as an indication of what you can expect in the following unit. The unit ends off with a number of theoretical self-assessment Self-assessment questions that test your knowledge of the content of the unit.

Glossary As you can see, we include a glossary at the end of the Study Guide. Please refer to it as often as necessary in order to familiarise yourself with the exact meaning of terms and concepts involved in procedural programming.

The use of icons Icons are used to highlight (emphasise) particular sections or points in the Study Guide, to draw your attention to important aspects of the work, or to highlight activities. The following icons are used in the Study Guide:

Exercise – Let’s do this This icon indicates learning activities/exercises that have to be completed, whether individually or in groups, in order to assess (evaluate) your understanding of the content of a particular section.

Learning outcome alignment This icon is used to indicate how individual units in the Study Guide are aligned to a specific outcome and its assessment criteria.

© CTI Education Group Introduction Page 12

Prescribed reading This icon indicates reference to relevant chapters and/or sections in the textbook that you are expected to study.

Alignment to prescribed textbook The following table reflects the alignment between the learning outcomes, assessment criteria, units in the Study Guide and chapters in the prescribed textbook.

Study Guide/prescribed textbook alignment

Study Learning outcome Assessment criteria Textbook chapter guide unit 1. Understand the 1.1 Discuss the principles, • Chapter 1: principles of characteristics and • Unit 1 pp. 1 – 22 procedural features of procedural • Unit 3 • Chapter 8: programming programming pp. 282 – 327 2.1 Identify the program units • Chapter 8/Unit 3, 2. Be able to and data and file Section 3.6 design structures required to • Unit 2 • Chapter 10/Unit procedural implement a given design • Unit 3 3, Section 3.6.3 programming 2.2 Design a procedural • Chapter 2: solutions programming solution for pp. 27 – 29 a given problem • Chapter 4: pp.121-166 Unit 3, Section 3.3 • Chapter 5: 3.1 Select and implement pp. 182 – 210/ control structures to meet Unit 3, Section 3. Be able to the design algorithms 3.4 implement 3.2 Correctly use parameter • Unit 4 • Chapter 6: procedural passing mechanisms • Unit 3 pp. 242 – 259/ programming 3.3 Implement a procedural Unit 3, Section solutions programming solution 3.5 based on a prepared • Chapter 3: design pp. 95 – 107 • Unit 3, Section 3.2.1 • Chapter 2: pp. 39 – 42 4.1 Critically review and test a • Chapter 7: 4. Be able to test procedural programming pp. 268 – 276 procedural solution • Unit 3 • Unit 4, Section programming 4.2 Analyse actual test results • Unit 4 4.1 solutions against expected results to • Chapter 7: identify discrepancies pp. 269 – 277

© CTI Education Group Introduction Page 13

4.3 Evaluate independent • Unit 4, Section feedback on a developed 4.1 procedural program • Chapter 6: solution and make pp. 252 – 257 recommendations for • Unit 3, Section improvements 3.5 4.4 Create onscreen help to • Unit 4, Section assist the users of a 4.2 computer program • Unit 4, Section 4.5 Create documentation for 2.3 the support and maintenance of a computer program

Concluding remarks At this point, you should be familiar with the module design and structure as well as with the use of the prescribed textbook in conjunction with the Study Guide.

In Unit 1, we start with the actual module content.

© CTI Education Group Unit 1 – Principles of procedural programming Page 14

Unit 1 – Principles of procedural programming

Unit 1 is aligned with the following learning outcomes and assessment criteria:

Learning outcomes: LO1: Understand the principles of procedural programming.

Assessment criteria: AC1.1: Discuss the principles, characteristics and features of procedural programming.

Learning objectives

After studying this unit, you should be able to: • Describe characteristics of programming • Identify types of language • Describe reasons for choice of language • Identify different data types

Prescribed reading

Gaddis, T. 2016. Starting out with programming logic and design. 3rd edition. Boston: Pearson Education, Inc. Chapters 1 and 8.

Introduction This unit looks into the principles of procedural programming. There are different types of programming languages in the industry and one needs to be aware of them. There are many reasons why people choose certain programming languages and refrain from using others. All programming languages use data types, although the way in which they are used differs from one language to another.

1.1 Characteristics of programming A computer program is a sequence of instructions written using a computer programming language to perform a specified task by the computer. A computer programmer lists all the steps required to resolve a problem before starting to write the actual code; the steps are better known as algorithms.

© CTI Education Group Unit 1 – Principles of procedural programming Page 15

An algorithm is a step-by-step procedure to resolve any problem. An algorithm is an effective method expressed as a finite set of well-defined instructions.

Today, computer programs are being used in almost every field: household, agriculture, medical, entertainment, defence, communication, etc. The following are a few applications of computer programs: • MS Word • MS Excel • Adobe Photoshop • Internet Explorer • Chrome, etc.

Computer programs are being used to develop graphics and special effects in movie making; computer programs are being used to perform Ultrasounds, X- Rays, and other medical examinations; computer programs are also being used on our mobile phones for SMS, chat and voice communication.

There are two types of programming languages, based on the code or syntax which they use. One is low-level programming languages and the other is high-level programming languages. The difference between them is in the way we write their code.

1.1.1 Low-level Low-level languages are appropriate for writing operating systems or firmware for micro-controllers. They provide little or no abstraction from a computer’s microprocessor. Assembly language is primarily a direct substitute for machine language, and like machine language, it requires that you know a lot about the CPU. Because assembly language is so close in nature to machine language, it is referred to as a low-level language.

Characteristics • Direct memory management • Little-to-no abstraction from the hardware • Register access • Statements usually have an obvious correspondence with clock cycles • Superb performance

1.1.2 High-level A high-level programming language is a programming language that is more abstract, easier to use, and more portable across platforms. High- level programming languages make complex programming simpler and easier to read, write and maintain. Programs written in a high-level programming language must be translated into machine language by a compiler or interpreter.

© CTI Education Group Unit 1 – Principles of procedural programming Page 16

Characteristics • Interpreted • Dynamic constructs • Poor performance • Concise code • Flexible syntax • Hybrid paradigm (object-oriented and functional) • Fanatic community

1.2 Interpreters and compilers A compiler is a program that translates a high-level language program into a separate machine language (Gaddis, 2016). The machine language program can then be executed any time that it is needed. As shown in the figure below, compiling and executing are two different process

Compiling a high-level program and executing

Source: Gaddis (2016)

An interpreter is a program that both translates and executes the instructions in a high-level language program. As the interpreter reads each individual instruction in the program, it converts it to a machine language instruction and then immediately executes it. This process repeats for every instruction in the program. This process is illustrated in the figure below:

© CTI Education Group Unit 1 – Principles of procedural programming Page 17

Executing a high-level program with an interpreter Source: Gaddis (2016)

1.3 Generations of programming languages

• First generation: The first generation of programming language, or 1GL, is machine language. Machine language is a set of instructions and data that a computer’s central processing unit can execute directly. Machine language statements are written in binary code, and each statement corresponds with one machine action. • Second generation: The second generation of programming language, or 2GL, is assembly language. Assembly language is the human-readable notation for the machine language used to control specific computer operations. An assembly language programmer writes instructions using symbolic instruction codes that are meaningful abbreviations or mnemonics. An assembler is a program that translates assembly language into machine language. • Third generation: The third generation of programming language, 3GL, or procedural language uses a series of English-like words that are closer to human language, to write instructions. Pascal, Fortran, BASIC, COBOL, C and C++ are examples of third-generation programming languages. • Fourth generation: The fourth generation of programming language or non-procedural language, often abbreviated as 4GL, enables users to access data in a database. An especially high-level programming language is often referred to as goal-oriented programming language, because it is usually limited to a very specific application and it might use syntax which is never used in other programming languages. SQL, Nomad and FOCUS are examples of fourth-generation programming languages. • Fifth generation: The fifth generation of programming language, or visual programming language, is also known as natural language. It provides a visual or graphical interface, called a visual programming environment, for creating source codes. Fifth-generation programming allows people to interact with computers without needing any specialised knowledge. People can talk to computers and the voice recognition systems can convert spoken sounds into written words. Prolog and Mercury are the best known fifth-generation languages.

© CTI Education Group Unit 1 – Principles of procedural programming Page 18

• Open Programming Language: The Open Programming Language (OPL) is an embedded programming language found in portable devices that run the Symbian Operating System; for example, mobile telephones and PDAs. OPL is an interpreted language that is analogous to BASIC.

1.4 Paradigms In programming 1.4.1 Procedural languages Procedural languages use a list of instructions to tell the computer what to do, step-by-step. Procedural programming relies on procedures, also known as routines or subroutines. A procedure contains a series of computational steps to be carried out. Procedural programming is also referred to as imperative programming. Procedural programming languages are also known as top- down languages. A top-down design means that the whole program is broken down into smaller sections that are known as modules (Gaddis, 2016).

Procedural programming is intuitive in the sense that it is very similar to how you would expect a program to work. If you want a computer to do something, you should provide step-by-step instructions on how to do it. It is, therefore, no surprise that most of the early programming languages are all procedural. Examples of procedural languages include Fortran, Pascal, COBOL and C.

1.4.2 Object-oriented languages Object-oriented programming, or OOP, is an approach to problem-solving whereby all computations are carried out using objects. An object is a component of a program that knows how to perform certain actions and how to interact with other elements of the program. Objects are the basic units of object-oriented programming.

A method in object-oriented programming is like a procedure in procedural programming. The key difference here is that the method is part of an object. In object-oriented programming, you organise your code by creating objects, and then you can give those objects properties and you can make them do certain things.

A key aspect of object-oriented programming is the use of classes. A class is a blueprint of an object. You can think of a class as a concept, and the object as the embodiment of that concept. So let us say that you want to use a person in your program. You want to be able to describe the person and have the person do something. A class called “person” would provide a blueprint for what a person looks like and what a person can do. Examples of object-oriented languages include C#, Java, Perl and Python (Gaddis, 2016).

© CTI Education Group Unit 1 – Principles of procedural programming Page 19

1.4.3 Event-driven languages An event-driven application is a computer program that is written to respond to actions generated by the user or the system. In a computing context, an event is any identifiable occurrence that has significance for system hardware or software. As such, events include both user-generated actions, like mouse clicks and keystrokes, and system-generated events such as program loading.

Event-driven programming separates event-processing logic from the rest of a program’s code. The event-driven approach contrasts with batch processing. Because event-driven programming is an approach rather than a type of language, event-driven apps can be created in any programming language. Depending on the specific application, event-driven processing can improve responsiveness, throughput and flexibility.

1.5 Data Types -using a program to solve real world problems can require input, manipulation and output of data. Example can include payroll processing, you might require personnel details like name and contact numbers, hours worked, rate per hour and commission if necessary. From the above you can identify different data formats like comparing name with rate per hour. In programming these formats are refereed as data types. Standard data types are integer, real and string. Further manipulation of these data types can result in other data structures as pointes, arrays and structures.

Summary of data types Data type Description Example Integer Can hold whole number 42, 0, and –99

Can hold either whole numbers or numbers Real 3.5, –87.95, and 3.0 with a fractional part

String Can hold any string of characters name, address and password Source: Gaddis (2016)

It is however important to note that data types vary partially on the language being used. In Java we can use a double which can also be a real data type in Pascal.

1.6 Variables A variable is refers to a named placeholder that identifies a memory location in the computer used for input, manipulation and output of data. A variable declaration is a statement that typically specifies two things about a variable, according to Gaddis (2016): • The variable’s name

© CTI Education Group Unit 1 – Principles of procedural programming Page 20

• The variable’s data type

The purpose of a variable declaration statement is to tell the compiler or interpreter that you plan to use a particular variable in the program. A variable declaration statement typically causes the variable to be created in memory. For this reason, you have to write a variable’s declaration statement before any other statements in the program that use the variable. This makes perfect sense, because you cannot store a value in a variable if the variable has not been created in memory.

1.7 Good Programming practice 1.7.1 Use of Comments A comment is a programmer-readable annotation in the source code of a computer program. They are added with the purpose of making the source code easier to understand, and are generally ignored by compilers and interpreters. The syntax of comments in various programming languages varies considerably.

1.7.2 Indentation Indenting will definitely make the program readable and therefore easy to debug. The program would be structured in such a way that statements can be associated with its respective header.

1.7.3 Variable naming Among other good practice a variable name should be named close to what it would hold and also as short as possible. However variable naming has rules which includes • Should not start with a number but a letter or special character • It cannot have spaces in the name, you can use underscore or other special characters in case. • Reserved words however cannot be used.

1.7.4 Use of modules The breaking of a program into smaller manageable units called modules which can be called during execution. This topic is explained further in detail on the next chapter.

© CTI Education Group Unit 1 – Principles of procedural programming Page 21

1.8 Exercise 1

Let’s do this

1. In detail explain the concept of variable highlighting its importance, how it’s declared and scope.

2. What is the main difference between Procedural and OOP?

3. Distinguish between high and low-level programming languages and give examples of each.

Concluding remarks Writing programs takes a number of concepts into consideration. Declaration of variables can be achieved in a single statement, paying attention to data types. After identifying the different parts of the program – input, process and output – the programmer must consider the layout of the code. The layout of the code and comments are essential in program maintenance. Two types of comments can be included in programs: line and block comments. Structure of the code improves its clarity.

© CTI Education Group Unit 2 – Design procedural programming solutions Page 22

Unit 2 – Design procedural programming solutions

Unit 2 is aligned with the following learning outcomes and assessment criteria:

Learning outcomes: LO2: Be able to design procedural programming solutions. LO3: Be able to implement procedural programming solutions.

Assessment criteria: AC2.1: Identify the program units and data and file structures required to implement a given design. AC2.2: Design a procedural programming solution for a given problem. AC3.1: Select and implement control structures to meet the design algorithms. AC3.2: Correctly use parameter passing mechanisms. AC3.3: Implement a procedural programming solution based on a prepared design.

Learning objectives After studying this unit, you should be able to: • Understand requirements specification • Understand program design • Understand technical documentation

Prescribed reading

Gaddis, T. 2016. Starting out with programming logic and design. 3rd edition. Boston: Pearson Education, Inc. Chapters 2, 8 and 10.

© CTI Education Group Unit 2 – Design procedural programming solutions Page 23

2.1 Introduction In this unit we are going to address how we design solutions given a scenario. Designing solutions to tasks performed by programs is perhaps the most challenging and interesting aspect of programming. Experienced programmers, treading a path that they know well, may decide to bypass the design step and yet arrive at a good solution to the problem. The reason for this is that experience has already provided a solution. The drawback to this approach is that, in all probability, somebody else will be maintaining the program, and for that person it would be most convenient to find a graphic representation of what the program does; this saves time.

2.2 Requirements specification A requirements specification is a comprehensive description of the intended purpose and environment for software under development, usually referred to as Software Requirements Specification (SRS). The RS fully describes what the software will do and how it will be expected to perform Software in Practice (2014).

The purpose of the SRS is to: • Establish the basis for agreement between the customers and the suppliers on what the software product is to do: The complete description of the functions to be performed by the software specified in the SRS will assist the potential user to determine if the software specified meets their needs or how the software must be modified to meet their needs. • Provide a basis for developing the software design: The SRS is the most important document of reference in developing a design. • Reduce the development effort: The preparation of the SRS forces the relevant groups in the customer’s organisation to thoroughly consider all of the requirements before design work begins. A complete and correct SRS reduces effort/time spent on redesign, recoding and retesting. Careful review of the requirements in the SRS can reveal omissions, misunderstandings and inconsistencies early in the development cycle, when these problems are easier to correct. • Provide a basis for estimating costs and schedules: The description of the product to be developed as given in the SRS is a realistic basis for estimating project costs and can be used to obtain approval for bids or price estimates. • Provide a baseline for validation and verification: Organisations can develop their test documentation much more productively from a good SRS. As a part of the development contract, the SRS provides a baseline against which compliance can be measured • Facilitate transfer: The SRS makes it easier to transfer the software product to new users or new machines. Customers thus find it easier to transfer the software to other parts of their organisation and suppliers find it easier to transfer it to new customers. • Serve as a basis for enhancement: Because the SRS discusses the product but not the project that developed it, the SRS serves as a basis for later enhancement of the finished product. The SRS may need to be

© CTI Education Group Unit 2 – Design procedural programming solutions Page 24

altered, but it provides a foundation for continued product evaluation.

The software requirements specification is carefully laid out to highlight the following:

Some aspects of SRS This provides a context for the system within the organisation. For Scope of the system instance, the scope will often define what it will not do as a general explanation of what it will do. These are usually laid out as bullet points, so that it is very clear Objectives what the system needs to do. Tables can also be used to lay these out. This section provides a timeline for how the project will proceed Timing and when it is to finish. Typically, a Gantt chart is used to show milestones. The budget and manpower that are available for the project. The Constraints budget also determines the type of hardware and software that will be used in the project. This section defines what inputs are needed by the system. It will provide outline details of the data capture forms, input screens, Inputs automated system feeds and so on. It does not try to be particularly technical at this point; just an overall idea of what will be going into the system and how this is to be achieved. Systems have to produce an output in one form or another. This section will describe the expected form of outputs. For example, Outputs printed reports and graphs, output viewing screens, files created and stored, any output data feeds to other systems, and so on. Between input and output, dome processing should be taking place. This part of the SRS describes the processing to be carried out. Processing Processing details include: requirements • Procedures to be used • Important validation details The acceptable limits of processing times The requirements specification is, in effect, a contract between the Contract end user and the people responsible for delivering the project. Source: Software in Practice (2014)

2.3 Program design tools The design stage describes how the solution will be built to satisfy the requirements specified in the previous stage. The final set of programs will be produced in accordance with this description, so it has to be a detailed, technical and logical definition of the final system. Where programmers are involved in writing programs for large systems, the systems analyst would provide the program specifications and the programmer would begin work at this stage. The tools this unit will focus would be on flowchart and pseudo code.

2.3.1 Flow Chart A problem solving diagram that uses different shapes and lines to represent steps and actions taken to the solution.

© CTI Education Group Unit 2 – Design procedural programming solutions Page 25

2.3.2 Pseudo code Most of program illustrations in this unit are done using this tool. A pseudo code is rather a programming design tool that uses statements independent of any programming language specifying steps and actions of which programmer has to incorporate.

2.4 Technical Documentation This is intended for technical maintenance of the system. Engineers and software developers will refer to the technical documentation in order to make changes to the system after it has been installed.

Technical documentation is created from the very first stages of the development phase, when the original project team sets down the details as they build the system.

The typical topics which are addressed in technical documentation are: • Source code, with copious commentary explaining how that part of the code works • Data structures used within the system • File formats used • File naming conventions • Validation ranges for data input

© CTI Education Group Unit 2 – Design procedural programming solutions Page 26

• Macro scripts, including comments to explain each stage of the macro • Internal details of a database, such as tables, relationships, records, queries used • Navigation layout, such as a site map or link map of the system

Other technical details for help with maintenance include: • Test logs and test results • Security details of the system • How to install the system • How to back up and restore the system

2.5 Exercise 2

Let’s do it

Using Pascal 1. Write a program that prints “Hello world ,Pascal is lekker” 2. Write a program that prompts a user to enter a name then display “Your name is” Rodney, if the user entered Rodney on the name. 3. Write a program that captures two integers and display their sum. 4. That prompts a user to enter the dimensions of a triangle and calcite the area. The result should display “The area of the triangle is”___.

Concluding remarks An SRS is basically an organisation’s understanding, in writing, of a customer or potential client's system requirements and dependencies at a particular point in time, usually prior to any actual design or development work. It is a two-way insurance policy that assures that both the client and the organization understand each other's requirements from that perspective, at a given point in time.

The SRS is vital to the success of software development projects. The design stage describes how the solution will be built to satisfy the requirements specified in the previous stage. At this stage, a number of tools are used; we mentioned only a few of them in this unit. Further reading on Unified Modelling Language (UML) may help you to gain a deeper understanding of these tools. UML is the most commonly used specification, and the means by which the world models not only application structure, behaviour and architecture, but also business process and data structure.

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 27

Unit 3 – Implement procedural programming solutions

Unit 3 is aligned with the following learning outcomes and assessment criteria:

Learning outcomes: LO1: Understand the principles of procedural programming. LO2: Be able to design procedural programming solutions. LO3: Be able to implement procedural programming solutions.

Assessment criteria: AC1.1: Discuss the principles, characteristics and features of procedural programming. AC2.1: Identify the program units and data and file structures required to implement a given design. AC2.2: Design a procedural programming solution for a given problem. AC3.1: Select and implement control structures to meet the design algorithms. AC3.2: Correctly use parameter passing mechanisms. AC3.3: Implement a procedural programming solution based on a prepared design.

Learning objectives After studying this unit, you should be able to: • Understand modular design • Understand software structures • Understand parameters • Understand scope of variables • Understand use of programming standards and relationship to program design • Understand data structures

Prescribed reading

Gaddis, T. 2016. Starting out with programming logic and design. 3rd edition. Boston: Pearson Education, Inc. Chapters 2, 3, 5 and 6.

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 28

Introduction In this unit, we are going to learn how to implement procedural programming solutions. This is the phase after the design phase which is carried out by the programmer or developer. No specific programming language is being used in this unit.

3.1 Modular design The basic idea underlying modular design is to organise a complex system (such as a large program) as a set of distinct components that can be developed independently and then plugged together. Although this may appear to be simple, experience shows that the effectiveness of the technique depends critically on the manner in which systems are divided into components, and the mechanisms used to plug components together. A module is a group of statements that exist within a program for the purpose of performing a specific task (Gaddis, 2016).

This approach is sometimes called divide and conquer, because a large task is divided into several smaller tasks that are easily performed.

Although every modern programming language allows you to create modules, they are not always referred to as modules. Modules are commonly called procedures, subroutines, subprograms, methods and functions.

3.1.1 Benefits of using modules • Simpler code: A program’s code tends to be simpler and easier to understand when it is modularized. Several small modules are much easier to read than one long sequence of statements. • Code reuse: Modules also reduce the duplication of code within a program. If a specific operation is performed in several places in a program, a module can be written once to perform that operation, and can then be executed any time that it is needed. This benefit of using modules is known as code reuse, because you are writing the code to perform a task once and then reusing it each time that you need to perform the task. • Better testing: When each task within a program is contained in its own module, testing and debugging become simpler. Programmers can test each module in a program individually, to determine whether it correctly performs its operation. This makes it easier to isolate and fix errors. • Faster development: Suppose that a programmer or a team of programmers is developing multiple programs. The programmer/team discovers that each of the programs performs several common tasks, such as asking for a username and a password, displaying the current time, and so on. It does not make sense to write the code for these tasks multiple times. Instead, modules can be written for the commonly needed tasks, and those modules can be incorporated into each program that needs them. • Easier facilitation of teamwork: Modules also make it easier for programmers to work in teams. When a program is developed as a set of modules that each performs as an individual task, then different

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 29

programmers can be assigned the job of writing different modules.

3.1.2 Calling a module To create a module, you write its definition. In most languages, a module definition has two parts: a header and a body. The header indicates the starting point of the module, and the body is a list of statements that belong to the module. The syntax of a module definition is shown in the pseudo code below:

Module definition

Source: Gaddis (2016)

Let us look at an example. Keep in mind that this is not a complete program:

Module example

Source: Gaddis (2016)

This pseudo code defines a module named showMessage. As its name implies, the purpose of this module is to show a message on the screen. The body of the showMessage module contains one statement: a Display statement that displays the message “Hello world.”

To fully demonstrate how module calling works, we will look at the following program:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 30

Module calling

Source: Gaddis (2016)

Program output

I have a message for you. Hello world That’s all, folks!

The program executes from main, which is the starting point, executes Line 2, on Line 3 a module is called so it jumps to Line 7 to execute the Module up to Line 9 and returns back to the main program on Line 4 before exiting on Line 5 (Gaddis, 2016).

The term “scope” is used to describe the part of a program in which a variable may be accessed. A variable is visible only to statements inside the variable’s scope.

3.2 Modules in procedural programming In Procedural Programming modules take form of functions and procedures

3.2.1 Function Functions are "self-contained" modules of code that accomplish a specific task. Functions usually "take in" data, process it, and "return" a result. Once a function is written, it can be used over and over and over again. Functions can be "called" from the inside of other functions.

How a function works • The program comes to a line of code containing a "function call". • The program enters the function (starts at the first line in the function code). • All instructions inside of the function are executed from top to bottom. • The program leaves the function and goes back to where it started from. • Any data computed and RETURNED by the function is used in place of the function in the original line of code.

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 31

3.2.2 Procedures A procedure works almost the same as the function however it doesn’t return a value as functions do. Procedures are therefore not used where there are calculations but rather steps in performing a task e.g. for registering student to a subject or course we can create a procedure called register() with necessary steps in there like check the payment, check qualifications, add course etc.

3.3 Exercise 3

Let’s do it

Using Pascal 1. Create a program that uses a procedure with name greetings (). The procedure should display “Hello, how are you” when it’s called in the program. 2. Create a program with procedure greeting2 (). The program should prompt a user to enter hey name and call the procedure to complete”Hello”____”how are you”, filling up the gap with the name provided.

3.4 Types of variables 3.4.1 Local A local variable is declared inside a module and cannot be accessed by statements that are outside the module. Different modules can have local variables with the same names, because the modules cannot see each other’s local variables. An error will occur if a statement in one module tries to access a local variable that belongs to another module, as shown in the program below (Gaddis, 2016):

Local variables

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 32

Source: Gaddis (2016)

The name variable is declared in Line 7, inside the getName module. Because it is declared inside the getName module, it is a local variable belonging to that module. Line 8 prompts the user to enter his or her name, and the Input statement in Line 9 stores the user’s input in the name variable. The main module calls the getName module in Line 2. Then, the Display statement in Line 3 tries to access the name variable. This results in an error because the name variable is local to the getName module, and statements in the main module cannot access it.

3.4.2 Global A global variable is a variable that is visible to every module in the program. A global variable’s scope is the entire program, so all of the modules in the program can access a global variable (Gaddis, 2016). The program below shows how a global variable is declared:

According to Gaddis (2016), most programmers agree that you should restrict the use of global variables, or not use them at all. The reasons are as follows: • Global variables make debugging difficult: Any statement in a program can change the value of a global variable. If you find that the wrong value is being stored in a global variable, you have to track down every statement that accesses it to determine where the bad value is coming from. In a program with thousands of lines of code, this can be difficult. • Modules that use global variables are usually dependent on those variables: If you want to use such a module in a different program, you will most likely have to redesign it so that it does not rely on the global variable. • Global variables make a program hard to understand: A global variable can be modified by any statement in the program. If you are to understand any part of the program that uses a global variable, you have to be aware of all the other parts of the program that access the global variable.

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 33

Global variables

Source: Gaddis (2016)

3.5 Passing arguments to modules An argument is any piece of data that is passed into a module when the module is called. A parameter is a variable that receives an argument that is passed into a module.

If you want a module to receive arguments when it is called, you must equip the module with one or more parameter variables. Here is an example of a pseudo code module that has a parameter variable:

Parameter variables Source: Gaddis (2016)

This module’s name is doubleNumber. Its purpose is to accept an integer number as an argument and display the value of that number doubled. Look at the module header and notice the words Integer value that appear inside the

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 34 parentheses. This is the declaration of a parameter variable. The parameter variable’s name is value and its data type is Integer. The purpose of this variable is to receive an Integer argument when the module is called (Gaddis, 2016). The program below demonstrates the module in a complete program:

Demonstrating parameter variables Source: Gaddis (2016)

When this program runs, the main module will begin executing. The statement in Line 2 calls the doubleNumber module. Notice that the number 4 appears inside the parentheses. This is an argument that is being passed to the doubleNumber module. When this statement executes, the doubleNumber module will be called with the number 4 copied into the value parameter variable (Gaddis, 2016).

We can also pass the contents of a variable as an argument. See the program below:

Pass the contents of a variable as an argument Source: Gaddis (2016)

The main module declares an Integer variable named number in Line 2. Lines 3 and 4 prompt the user to enter a number, and Line 5 reads the user’s input into the number variable. Notice that in Line 6 number is passed as an argument to the doubleNumber module, which causes the number variable’s contents to be copied into the value parameter variable.

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 35

3.5.1 Argument and parameter compatibility When you pass an argument to a module, most programming languages require that the argument and the receiving parameter variable be of the same data type. If you try to pass an argument of one type into a parameter variable of another type, an error usually occurs (Gaddis, 2016).

Arguments and parameter variables must be of the same type Source: Gaddis (2016)

3.5.2 Passing multiple arguments A parameter variable’s scope is usually the entire module in which the parameter is declared. No statement outside the module can access the parameter variable. Most languages allow you to write modules that accept multiple arguments.

The program below shows a pseudo code module, named showSum, that accepts two Integer arguments. The module adds the two arguments and displays their sum:

Passing multiple arguments

Source: Gaddis (2016)

Notice that two parameter variables, num1 and num2, are declared inside

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 36 the parentheses in the module header. This is often referred to as a parameter list. Also notice that a comma separates the declarations.

The statement in Line 3 calls the showSum module and passes two arguments: 12 and 45. The arguments are passed into the parameter variables in the order that they appear in the module call.

3.6 Types of passing arguments 3.6.1 Passing arguments by value

Passing an argument by value means that only a copy of the argument’s value is passed into the parameter variable. All the programs that we have looked at so far pass arguments by value (Gaddis, 2016).

3.6.2 Passing arguments by reference Passing an argument by reference means that the argument is passed into a special type of parameter, known as a reference variable. When a reference variable is used as a parameter in a module, it allows the module to modify the argument in the calling part of the program.

When a module calls another module and passes a variable by reference, communication between the modules can take place in the following ways: • The calling module can communicate with the called module by passing an argument. • The called module can communicate with the calling module by modifying the value of the argument via the reference variable.

• In pseudo code, we will declare that a parameter is a reference variable by writing the word Ref before the parameter variable’s name in the module header. For example, see the following pseudo code module:

Arguments by reference

Source: Gaddis (2016)

The word Ref indicates that value is a reference variable.

3.7 Exercise 4

Let’s do it

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 37

Using Pascal: • Write a program that uses a function called doubleNumber() that accepts integers. The function should be able to double (multiply by 2) if an integer is passed to it. • Write a program with name salary. The program should have two functions calcTax() and calcComm for salary calculation for a group salesreps. To calculate commission it is 30% of sales. The PAYE Tax is set at 15% of basic salary. The net salary is therefore basic salary plus commission less tax. The user input own values for basic salary and sales.

3.8 Decision structures A decision structure allows a program to perform actions only under certain conditions. Decision structures are also known as selection structures. A control structure is a logical design that controls the order in which a set of statements executes (Gaddis, 2016). We are going to study the decision structures that are used in the majority of programming languages.

3.8.1 If–Then The If-Then statement is used to write a single alternative decision structure. The following is the general format of the If-Then statement:

Syntax for If-Then statement Source: Gaddis (2016)

3.8.2 Boolean expressions and relational operators Expressions that can be evaluated as either true or false can be called Boolean expressions. A relational operator determines whether a specific relationship exists between two values. The Boolean expression that is tested by an If-Then statement is formed with a relational operator.

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 38

Relational operators Operator Meaning > Greater than < Less than >= Greater than or equal to <= Less than or equal to == Equal to != Not equal to Source: Gaddis (2016)

Boolean expressions using relational operators Operator Meaning x > y Is x greater than y? x < y Is x less than y? x >= y Is x greater than or equal to y? x <= y Is x less than or equal to y? x == y Is x equal to y? x != y Is x not equal to y? Source: Gaddis (2016)

The following pseudo code conditionally executes a set of statements:

Demonstrating conditional statements

Source: Gaddis (2016)

3.8.3 If-Then-Else A dual alternative decision structure will execute one group of statements if its Boolean expression is true, or another group if its Boolean expression is false. In pseudo code we write a dual alternative decision structure as an If- Then-Else statement (Gaddis, 2016). The general format of the If-Then-Else statement is as follows:

Syntax for If-Then-Else statement

Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 39

The following pseudo code shows an example of an If-Then-Else statement:

Syntax for If-Then-Else statement Source: Gaddis (2016)

3.8.4 The If-Then-Else If statement In pseudo code we will write the If-Then-Else If statement using the following general format:

Syntax If-Then-Else If statement Source: Gaddis (2016)

When the statement executes, condition_1 is tested. If condition_1 is true, the statements that immediately follow are executed, up to the Else If clause. The rest of the structure is ignored. If condition_1 is false, however, the program jumps to the very next Else If clause and tests condition_2. If it is true, the statements that immediately follow are executed, up to the next Else If clause. The rest of the structure is then ignored. This process continues until a condition is found to be true, or no more Else If clauses are left. If none of the

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 40 conditions are true, the statements following the Else clause are executed.

3.8.5 The case structure The case structure lets the value of a variable or an expression determine which path of execution the program will take; it is a multiple alternative decision structure. It allows you to test the value of a variable or an expression and then use that value to determine which statement or set of statements to execute (Gaddis, 2016).

To write a case structure in pseudo code, we will use a Select Case statement, as shown below:

Study the following pseudo code:

Demonstrating Select Case statement

Source: Gaddis (2016)

In the pseudo code above, the testExpression is the month variable. If the value in the month variable is 1, the program will branch to the Case 1: section and execute the Display "January" statement that immediately follows it. If the value in the month variable is not 1, 2 or 3, the program will branch to the Default: section and execute the Display

"Error: Invalid month" statement that immediately follows it. In many languages the case structure is called a switch statement.

3.9 Logical operators The logical AND operator and the logical OR operator allow you to connect multiple Boolean expressions to create a compound expression. The logical NOT operator reverses the truth of a Boolean expression (Gaddis, 2016). The logical operators are explained in the table below:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 41

Logical operators Operator Meaning The AND operator connects two Boolean expressions into one compound AND expression. Both sub-expressions must be true for the compound expression to be true. The OR operator connects two Boolean expressions into one compound expression. One or both sub-expressions must be true for the compound OR expression to be true. It is only necessary for one of the sub-expressions to be true, and it does not matter which. The NOT operator is a unary operator, meaning it works with only one operand. The operand must be a Boolean expression. The NOT operator NOT reverses the truth of its operand. If it is applied to an expression that is true, the operator returns true. Source: Gaddis (2016)

Suppose that a certain bank, Bank A, is losing customers to a competing bank, Bank B, which is not as strict about whom it loans money to. In response, Bank A decides to change its loan requirements. The bank usually only offers loans after checking two conditions. But, going forward, customers will only have to meet only one of these conditions, not both. Study the pseudo code below, which shows the loan qualifier program:

Loan qualifier program Source: Gaddis (2016)

3.10 Boolean variables

A Boolean variable can have one of two values: true or false. Boolean variables are commonly used as flags which indicate whether specific conditions exist. Boolean variables can be declared as shown below:

Boolean variables demonstration Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 42

Examples of how we assign values to a Boolean variable:

Assigning values to Boolean

Source: Gaddis (2016)

3.11 Exercise 5

Let’s do it

• Write a program that checks a mark captured, if it’s 50 and above should display “Passed “otherwise “Fail”. • Rewrite the above program but now with more grading, from Redo, Fail, Pass, Distinction to merit. • Write a program using the select case such that if a user press 1 it will display January, 2-February and so on.

3.12 Repetition structures A repetition structure causes a statement or set of statements to execute repeatedly. A condition-controlled loop uses a true/false condition to control the number of times that it repeats. A count-controlled loop repeats a specific number of times (Gaddis, 2016).

3.12.1 The While loop The While loop gets its name from the way it works: While a condition is true, do some task. The loop has two parts: • A condition that is tested for a true or false value • A statement or set of statements that is/are repeated as long as the condition is true

The general format of the While statement in pseudo code is as follows:

Syntax for While statement Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 43

The code below shows how we might use a While loop to write the commission-calculating program of a salesperson:

Commission-calculating program

Source: Gaddis (2016)

The While loop is known as a pre-test loop, which means that it tests its condition before performing an iteration.

3.12.2 The Do-While loop The Do-While loop is a post-test loop. This means that it performs an iteration before testing its condition. As a result, the Do-While loop always performs at least one iteration, even if its condition is false to begin with.

The general format of the Do-While statement in pseudo code is as follows: When the loop executes, the statements in the body of the loop are executed, and then the condition is tested. If the condition is true, the loop starts over and the statements in the body are executed again. If the condition is false, however, the program exits the loop.

The code below shows how we might use a Do-While loop to write the commission-calculating program of a salesperson:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 44

Using Do While loop

Source: Gaddis (2016)

Although the Do-While loop is convenient to use in some circumstances, it is never required. Any loop that can be written as a Do-While loop can also be written as a While loop (Gaddis, 2016).

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 45

3.12.3 The Do-Until loop A Do-Until loop iterates until a condition is true. Here is the general format of the Do-Until statement:

Syntax for Do–Until loop Source: Gaddis (2016)

When the loop executes, the statements in the body of the loop are executed, and then the condition is tested. If the condition is true, the program exits the loop. If the condition is false, the loop starts over and the statements in the body are executed again. The pseudo code below shows the loop in lines 6 through 16, which repeatedly ask the user to enter a password until the string "prospero" is entered (Gaddis, 2016).

Using Do-Until loop Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 46

3.13 Deciding which loop to use You want to use the While loop to repeat a task as long as a condition is true. The While loop is ideal in situations where the condition might be false to start with, and in such cases you do not want the loop to iterate at all.

The Do-While loop is also a candidate in situations in which a task must be repeated as long as a condition is true. It is the best choice, however, when you always want the task to be performed at least once, regardless of whether the condition is true or false to start with.

The Do-Until loop also performs a task at least once. It is the best choice, however, when you want to perform a task until a condition is true. The Do- Until loop will repeat as long as its condition is false (Gaddis, 2016).

3.12.1 The For loop A count-controlled loop iterates a specific number of times. Although you can write the logic of a condition-controlled loop so that it iterates a specific number of times, most languages provide a loop known as the For loop, which is specifically designed as a count-controlled loop.

The following is the general format that we will use to write the For statement in pseudo code:

Syntax for For loop Source: Gaddis (2016)

When the loop executes, the following actions are performed: 1. The counterVariable is set to the startingValue. 2. The counterVariable is compared to the maxValue. If the counterVariable is greater than maxValue, the loop stops.

Otherwise: • The statements that appear in the body of the loop are executed. • The counterVariable is incremented. • The loop starts over again at Step 2.

The pseudo code below displays “Hello world” five times:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 47

Using For loop

Source: Gaddis (2016)

Incrementing by values other than 1 The amount by which the counter variable is incremented in a For loop is known as the step amount. This gives you the ability to increment the counter variable by any value you wish. For example, look at the following pseudo code:

Using step amount

Source: Gaddis (2016)

The program below displays all of the odd numbers from 1 through 11:

For loop example

Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 48

While can be used as a count-controlled loop like a For loop, as shown below:

Using While loop for a counter controlled loop

Source: Gaddis (2016)

Calculating a running total Programs that calculate the total of a series of numbers typically use two elements (Gaddis, 2016): • A loop that reads each number in the series • A variable that accumulates the total of the numbers as they are read

Have a look at the pseudo code below, which allows the user to enter five numbers, and it displays the total of the numbers entered:

Calculating a running total Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 49

3.14 Exercise 6

Let’s do it

1. Write a program that prints integers between 1 and 5 inclusive. 2. Write a program that prints even integers between 1 and 10 inclusive. 3. Write a program that captures integers summing them up until the total is above 20. 4. Do question3 using a post test loop and check the difference

3.15 Data structures A data structure is a specialised format for organising and storing data. General data structure types include the array, the file, the record, the table, the tree, and so on. Any data structure is designed to organise data to suit a specific purpose so that it can be accessed and worked with in appropriate ways. In computer programming, a data structure may be selected or designed to store data for the purpose of working on it with various algorithms. In this module we will address arrays, in detail (Gaddis, 2016).

3.15.1 Arrays An array allows you to store a group of items of the same data type together in memory. Processing a large number of items in an array is usually easier than processing a large number of items stored in separate variables.

All of the values in an array must be the same data type. You can have an array of Integers, an array of Reals, or an array of Strings, but you cannot store a mixture of data types in an array (Gaddis, 2016). The following example shows how we will declare an array in pseudo code:

Array declaration Source: Gaddis (2016)

Notice that this statement looks like a regular Integer variable declaration, except for the number inside the brackets. The number inside the brackets, called a size declarator, specifies the number of values which the array can hold. Here is another example:

Size of an array Source: Gaddis (2016)

This statement declares an array named salesAmounts that can hold 7 real numbers. To make array sizes easier to maintain, many programmers prefer to

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 50 use named constants as array size declarators. Here is an example:

Using named constants in arrays

Source: Gaddis (2016)

When you use a named constant as an array’s size declarator, you can use the constant to refer to the size of the array in your algorithms. If you ever need to modify the program so that the array is a different size, you need only change the value of the named constant.

3.15.2 Array elements and subscripts The storage locations in an array are known as elements. Each element in an array is assigned a unique number, known as a subscript. Subscripts are used to identify specific elements in an array; the first element is usually assigned the subscript 0 (Gaddis, 2016). For example, suppose that a pseudo code program has the following declarations:

Array elements and subscripts

Source: Gaddis (2016)

As shown in the figure below, the numbers array has five elements. The elements are assigned the subscripts 0 through 4. (Because subscript numbering starts at zero, the subscript of the last element in an array is one less than the total number of elements in the array.)

Array subscripts Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 51

3.15.3 Assigning values to array elements You access the individual elements in an array by using their subscripts. For example, assuming numbers is the Integer array just described, the following pseudo code assigns the values to each of its five elements:

This pseudo code assigns the value 20 to element 0, the value 30 to element 1, and so forth. In the figure below shows the contents of the array after these statements execute:

Values assigned to each element Source: Gaddis (2016)

3.15.4 Using a loop to step through an array Most programming languages allow you to store a number in a variable and then use that variable as a subscript. This makes it possible to use a loop to step through an entire array, performing the same operation on each element. For example, see the pseudo code below:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 52

Using a loop to step through an array

Source: Gaddis (2016)

In Line 2, an Integer array named series is declared with 10 elements, and in Line 5 an Integer variable named index is declared. The index variable is used as a counter in the For loop that appears in lines 8 through 10. In the loop, the index variable takes on the values 0 through 9. The first time the loop iterates, index is set to 0, so the statement in Line 9 causes the array element series[0] to be set to 100. The second time the loop iterates, index is set to 1, so the array element series[1] is set to 100. This continues until the last loop iteration, in which series[9] is set to 100 Gaddis (2016).

Let us look at another example. The code above could be simplified by using two For loops: one for inputting the values into the array and the other for displaying the contents of the array. This is shown in the program below:

3.15.5 Array initialization Most languages allow you to initialise an array with values when you declare it. In this guide’s pseudo code, we will initialise arrays in the following manner:

Array initialisation Source: Gaddis (2016)

The series of values separated by commas is called an initialisation list. These values are stored in the array elements in the order in which they appear in the list. (The first value, 10, is stored in numbers[0]; the second value, 20, is stored in numbers[1]; and so forth.) Here is another example:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 53

Initialisation list Source: Gaddis (2016)

This pseudo code declares days as an array of 7 Strings, and initialises days[0] with "Sunday", days[1] with "Monday", and so forth.

3.15.6 Sequentially searching an array The sequential search algorithm is a simple technique for finding an item in an array. It steps through the array, beginning at the first element, and compares each element to the item being searched for. The search stops when the item is found or the end of the array is reached.

Let us look at the pseudo code below:

Sequentially searching an array

Source: Gaddis (2016)

Here is a summary of the data items in the code above: • Array is the array being searched. • Searchvalue is the value that the algorithm is searching for. • Found is a Boolean variable that is used as a flag. Setting found to false indicates that searchvalue has not been found. Setting found to true indicates that searchvalue has been found. • Index is an integer variable used as a loop counter.

When the algorithm finishes, the found variable will be set to True if the searchValue was found in the array. When this is the case, the index variable

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 54 will be set to the subscript of the element containing the searchValue. If the searchValue was not found in the array, found will be set to False.

3.15.7 Totalling the values in an array To calculate the total of the values in an array, you use a loop with an accumulator variable. The loop steps through the array, adding the value of each array element to the accumulator (Gaddis, 2016). See the code below, which demonstrates totalling values in an array:

Totalling the values in an array Source: Gaddis (2016)

3.15.8 Finding the lowest value in an array In some programs you are more interested in finding the lowest value than the highest value in a set of data. For example, suppose that you are designing a program that stores several players’ golf scores in an array and you need to find the best score. In golf, the lower the score the better, so you would need an algorithm that finds the lowest value in the array. The pseudo code below shows you how to find the lowest value:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 55

Finding the lowest value in an array Source: Gaddis (2016)

3.15.9 Parallel arrays By using the same subscript, you can establish relationships between data stored in two or more arrays. It is useful to store related data in two or more arrays. For example, assume that you have designed a program with the following array declarations (Gaddis, 2016):

Parallel arrays Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 56

The names array stores the names of five people, and the addresses array stores the addresses of the same five people. The data for each person is stored in the same relative location in each array. For instance, the first person’s name is stored in names[0], and that same person’s address is stored in addresses[0], as shown in the figure below:

The names and addresses arrays Source: Gaddis (2016)

The names and addresses arrays are examples of parallel arrays. Parallel arrays are two or more arrays that hold related data, and the related elements in each array are accessed with a common subscript.

To access the data, you use the same subscript with both arrays. For example, the loop in the following pseudo code displays each person’s name and address:

Accessing the data Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 57

3.16 Exercise 7

Let’s do it

1. The scores of a soccer team in a day tournament are stored separately per match. Given that the team in its 7 matches scored 3, 4, 1,3,2,0 and 1 a. Create a program with the array scores b. Initialize the array with the scores. c. Display all the scores. Use a for loop d. Display only the 3rd score. e. Calculate and display the total scores.

3.17 Two-dimensional arrays The arrays that you have studied so far are known as one-dimensional arrays. They are called one-dimensional because they can hold only one set of data. A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data (Gaddis, 2016).

For example, suppose that you are designing a grade-averaging program for a teacher. The teacher has six students, and each student takes five exams during the semester. One approach would be to create six one-dimensional arrays, one for each student, as illustrated in the figure below:

Two-dimensional array with six rows and five columns Source: Gaddis (2016)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 58

3.16.1 Declaring a two-dimensional array To declare a two-dimensional array, two size declarators are required: The first one is for the number of rows and the second one is for the number of columns. The following pseudo code is an example of how to declare a two- dimensional array:

Declaring a two-dimensional array Source: Gaddis (2016)

This statement declares a two-dimensional Integer array with three rows and four columns. The name of the array is values, and there are a total of twelve elements in the array. As with one-dimensional arrays, it is best to use named constants as the size declarators. Here is an example:

Using named constants

Source: Gaddis (2016)

When processing the data in a two-dimensional array, each element has two subscripts: one for its row and another for its column (Gaddis, 2016). The figure below illustrates the array with the subscripts shown for each element:

Subscripts for each element of the values array

Source: Gaddis (2016)

Most languages allow you to initialise a two-dimensional array with data when you declare the array. The syntax varies from language to language. Here is an example of how you can initialise a two-dimensional array in pseudo code:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 59

Initialising two-dimensional arrays

Source: Gaddis (2016)

In this declaration the value 88 is stored in testScores [0][0], the value 72 is stored in testScores [0][1], the value 90 is stored in testScores [0][2], and so forth.

3.18 File structures When a program needs to save data for later use, it writes the data in a file. The data can be read from the file at a later time (Gaddis, 2016).

Most of the commercial software packages that you use on a day-to-day basis store data in files. The following are a few examples: • Word processors: Word processing programs are used to write letters, memos, reports and other documents. The documents are then saved in files so that they can be edited and printed. • Image editors: Image editing programs are used to draw graphics and edit images such as the ones that you take with a digital camera. The images that you create or edit with an image editor are saved in files. • Spreadsheets: Spreadsheet programs are used to work with numerical data. Numbers and mathematical formulas can be inserted into the rows and columns of the spreadsheet. The spreadsheet can then be saved in a file for use later. • Games: Many computer games keep data stored in files. For example, some games keep a list of player names with their scores stored in a file. These games typically display the players’ names in order of their scores, from highest to lowest. Some games also allow you to save your current game status in a file so that you can quit the game and then resume later without having to start from the beginning. • Web browsers: Sometimes when you visit a Web page, the browser stores a small file known as a cookie on your computer. Cookies typically contain information about the browsing session, such as the contents of a shopping cart.

There are always three steps that must be taken when a file is used by a program. • Open the file: Opening a file creates a connection between the file and the program. Opening an output file usually creates the file on the disk and allows the program to write data to it. Opening an input file allows the program to read data from the file. • Process the file: In this step data is either written to the file (if it is an output file) or read from the file (if it is an input file). • Close the file: When the program is finished using the file, the file must be closed. Closing a file disconnects the file from the program.

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 60

3.18.1 Types of files 1. A text file contains data that has been encoded as text, using a scheme such as ASCII or Unicode. 2. A binary file contains data that has not been converted to text. As a consequence, you cannot view the contents of a binary file with a text editor.

3.18.2 File access methods • Sequential access file accesses data from the beginning of the file to the end of the file. If you want to read a piece of data that is stored at the very end of the file, you have to read all of the data that comes before it; you cannot jump directly to the desired data. • Direct/random access file allows you to jump directly to any piece of data in the file without reading the data that comes before it.

This guide focuses on sequential access files. Sequential access files are easy to work with, and you can use them to gain an understanding of basic file operations.

3.18.3 Creating a file and writing data to it The following example shows how we declare a name for an output file in our pseudo code (Gaddis, 2016):

Output file declaration Source: Gaddis (2016)

This statement declares two things. • The word OutputFile indicates the mode in which we will use the file. In our pseudo code, OutputFile indicates that we will be writing data to the file. • The name customerFile is the internal name that we will use to work with the output file in our code.

Although the syntax for making this declaration varies greatly among programming languages, you typically have to declare both the mode in which you will use a file and the file’s internal name before you can work with the file.

The next step is to open the file. In our pseudo code we will use the Open statement. Here is an example:

Opening a file Source: Gaddis (2016)

The word Open is followed by an internal name that was previously declared, and then a string that contains a filename. After this statement executes, a

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 61 file named customers.dat will be created on the disk, and we will be able to use the internal name customerFile to write data to the file.

Once you have opened an output file you can write data to it. In our pseudo code we will use the Write statement to write data to a file. For example:

Writing to a file Source: Gaddis (2016) writes the string "Charles Pace" to the file that is associated with customerFile. You can also write the contents of a variable to a file, as shown in the following pseudo code:

Writing contents to a file

Source: Gaddis (2016)

The second statement in this pseudo code writes the contents of the name variable to the file associated with customerFile.

Once a program is finished working with a file, it should close the file. Closing a file disconnects the program from the file. In our pseudo code, we will use the Close statement to close a file. For example:

Closing a file Source: Gaddis (2016)

Closes the file that is associated with the name customerFile. The statement in Line 2 declares the name myFile as the internal name for an output file. Line 6 opens the file philosophers.dat on the disk and creates an association between the file and the internal name myFile. This will allow us to use the name myFile to work with the file philosophers.dat.

3.18.4 Delimiters and the EOF marker A delimiter is simply a predefined character or set of characters that marks the end of each piece of data. The delimiter’s purpose is to separate the different items that are stored in a file. In addition to delimiters, many systems write a special character or set of characters, known as an end-of-file (EOF) marker, at the end of a file (Gaddis, 2016).

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 62

Contents of the file philosophers.dat with delimiters and the EOF marker Source: Gaddis (2016)

Let us look at the pseudo code below:

Creating a file and writing data to it Source: Gaddis (2016)

3.18.5 Using loops to process files Files usually hold large amounts of data, and programs typically use a loop to process the data in a file. When a program uses a file to write or read a large amount of data, a loop is typically involved. For example, look at the pseudo code below:

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 63

Using loops to process files Source: Gaddis (2016)

This program acquires sales amounts, for a series of days, from the user and stores these amounts in a file named sales.dat. The user specifies the number of days of sales data that he or she needs to enter. In the sample run of the program, the user enters sales amounts for five days.

Suppose that you need to write a program that reads all of the amounts in the file and calculates their total. You can use a loop to read the items in the file, but an error will occur if the program tries to read beyond the end of the file. The program requires some way of knowing when the end of the file has been reached, so that it will not try to read beyond it.

Most programming languages provide a library function for this purpose. In our pseudo code we will use the eof function. Here is the function’s general format: eof(internalFileName)

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 64

The eof function accepts a file’s internal name as an argument, and returns True if the end of the file has been reached or False if the end of the file has not been reached. Study the pseudo code below (Gaddis, 2016):

Using eof function Source: Gaddis (2016)

3.18.6 Processing records The data that is stored in a file is frequently organised in records. A record is a complete set of data about an item, and a field is an individual piece of data within a record.

For example, suppose that we want to store data about employees in a file. The file will contain a record for each employee. Each record will be a collection of fields, such as name, ID number and department.

3.18.7 Writing records Assume that the variables name, idNumber, and department contain data about an employee, and employeeFile is the file that we will write the data to. We can write the contents of these variables to the file with the following statement:

Writing variables to a file Source: Gaddis (2016)

See the pseudo code below for an example of how this statement might

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 65 be used:

Writing records

Source: Gaddis (2016)

Lines 16 through 18 prompt the user for the number of employee records that he or she wants to create. Inside the loop, the program acquires an employee’s name, ID number and department. This data is written to the file in Line 39. The loop iterates once for each employee record.

3.18.8 Reading records In pseudo code we will read an entire record from a file using a single Read

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 66 statement. The following statement shows how we can read three values from employeeFile into the name, idNumber and department variables

Reading values from a file

Source: Gaddis (2016)

Look at the program below which reads the records written to the employees.dat file:

Reading records Source: Gaddis (2016)

3.18.9 Managing records Applications that store records in a file typically require more capabilities than those that simply write and read records. Managing records can involve adding records to a file, searching a file for specific records, modifying a record and deleting a record using simple commands; this topic is, however, beyond the scope of this guide.

© CTI Education Group Unit 3 – Implement procedural programming solutions Page 67

Concluding remarks Most programming languages have built-in library functions to manipulate data. In addition, most programming languages allow you to create arrays, which are specifically designed for storing and processing lists of data. Arrays can be one, two or multi-dimensional. Programs that are used in daily business operations rely extensively on files. Payroll programs keep employee data in files, inventory programs keep data about a company’s products in files, accounting systems keep data about a company’s financial operations in files, and so forth. Programmers usually refer to the process of saving data in a file as “writing data to” the file. The term “output” file is used to describe a file that data is written to. It is called an output file because the program stores output in it.

© CTI Education Group Unit 4 – Test procedural programming solutions Page 68

Unit 4 – Test procedural programming solutions

Unit 4 is aligned with the following learning outcomes and assessment criteria:

Learning outcomes: LO4: Be able to test procedural programming solutions.

Assessment criteria: AC4.1: Critically review and test a procedural programming solution. AC4.2: Analyse actual test results against expected results to identify discrepancies. AC4.3: Evaluate independent feedback on a developed procedural program solution and make recommendations for improvements. AC4.4: Create onscreen help to assist the users of a computer program. AC4.5: Create documentation for the support and maintenance of a computer program.

Learning objectives After studying this unit, you should be able to: • Understand checking error mechanisms • Understand supportive documentation • Review design against specification requirements

Prescribed reading

Gaddis, T. 2016. Starting out with programming logic and design. 4th edition. Boston: Pearson Education, Inc. Chapters 6 and 7.

© CTI Education Group Unit 4 – Test procedural programming solutions Page 69

Introduction In this unit we explore some of the error-checking mechanisms that can be used to test procedural programming solutions. We will also look at supportive documentation that can be included with the software to help users.

4.1 Error-checking mechanisms One of the most famous sayings among computer programmers is, “Garbage in, garbage out”. This saying, sometimes abbreviated as GIGO, refers to the fact that computers cannot tell the difference between good data and bad data. If a user provides bad data as input to a program, the program will process that bad data and, as a result, will produce bad data as output. Notice what happens in the sample run when the user supplies bad data as input (Gaddis, 2016):

Bad data as input Source: Gaddis (2016)

The payroll clerk who entered 400 as the number of hours worked in week probably meant to enter 40. The computer, however, is unaware of this fact, and the program processed the bad data just as if it were good data. We are going to look at some error-checking mechanisms using a process known as input validation.

© CTI Education Group Unit 4 – Test procedural programming solutions Page 70

4.1.1 The input validation loop Input validation is commonly done with a loop that iterates as long as an input variable contains bad data.

The first input operation, just before the loop, is called a priming read Gaddis (2016), and its purpose is to acquire the first input value that will be tested by the validation loop.

Let us consider an example. Suppose that you are designing a program that reads a test score and you want to make sure that the user does not enter a value less than 0. The following pseudo code shows how you can use an input validation loop to reject any input value that is less than 0:

Priming read Source: Gaddis (2016)

This pseudo code first prompts the user to enter a test score (this is the priming read), and then the While loop executes. If the user has entered a valid test score, this expression will be false and the loop will not iterate. If the test score is invalid, however, the expression will be true and the statements in the body of the loop will execute. This kind of an input validation loop is sometimes called an error trap or an error handler (Gaddis, 2016).

This pseudo code only rejects negative test scores. The pseudo code can be modified to reject test scores that are greater than 100, as shown in the pseudo code:

The loop in this pseudo code determines whether the score is less than 0 or greater than 100. If either is true, an error message is displayed and the user is prompted to enter a correct score.

© CTI Education Group Unit 4 – Test procedural programming solutions Page 71

4.1.1.1 Using a Post-test loop to validate input Post-test does not display an error message when the user enters an invalid value; it simply repeats the original prompt each time that the loop iterates. This might confuse the user, so it is better to use priming read.

4.1.1.2 Writing validation functions Suppose that you are designing a program that prompts the user to enter a product model number and should only accept the values 100, 200 and 300. You could design the input algorithm as shown below:

Writing validation functions

Source: Gaddis (2016)

The validation loop above can be simplified by writing a Boolean function to test the model variable and then calling that function in the loop. The validation loop can be written as follows:

© CTI Education Group Unit 4 – Test procedural programming solutions Page 72

Using a Boolean function Source: Gaddis (2016)

The loop is now easier to read and iterates as long as model is invalid.

4.1.1.3 Validating string input Suppose that you are designing a program that asks a yes/no question, and you want to make sure that only the strings “yes” or “no” are accepted as alid input. The following pseudo code shows how this might be done:

Validating string input Source: Gaddis (2016)

The following pseudo code is an example using the toLower function:

Using toLower function Source: Gaddis (2016)

© CTI Education Group Unit 4 – Test procedural programming solutions Page 73

To check the length of a string, you use the length function. In the following pseudo code, the length function is used to make sure that a password is at least six characters long:

Using length function Source: Gaddis (2016)

4.1.2 Defensive programming

Defensive programming is the practice of anticipating errors that can occur while a program is running, and designing the program to avoid those errors (Gaddis, 2016).

To use these functions in an input validation algorithm, you typically follow these steps: • Read the input as a string. • Determine whether the string can be converted to the desired data type. • If the string can be converted, convert it and continue processing; otherwise, display an error message and attempt to read the data again.

Thorough input validation also requires that you check for accurate data. Even when the user provides the right type of data, it might not be accurate. Consider the following examples: • Hourly wages and salary amounts should be checked to make sure that they are numeric values and within the range of allowable wages established by the company. • Dates should be checked for validity; for example, the date February 29 should be accepted only in leap years, and invalid dates such as February 30 should never be accepted. • Time measurements should also be checked for validity; for example, there are 168 hours in a week, so a payroll program should verify that no value greater than 168 is entered for the number of hours worked in a week.

4.2 Supportive documentation Most computer programs use symbols or icons such as F1,? (Question mark) or an icon named Help. A screen pops up to actually ask questions on the precise needs of the user (e.g. wizards). Links for help are usually placed where users can find them easily, such as in the navigation bar, side bar, or at

© CTI Education Group Unit 4 – Test procedural programming solutions Page 74 the top or bottom of screens. Onscreen help makes a computer program easier to use, especially because it is provided in the form of easily readable onscreen assistance with program navigation. It, therefore, increases the program’s user-friendliness.

Onscreen help has mainly been used for software products (applications/programs), but is increasingly being used for complex professional products, too; e.g. control equipment, including a system PC.

Currently, there are seven different types of onscreen help/manuals/tutorials: • The classical help function • Wizards • “Helpers” • Onscreen book-type help (e.g. Acrobat) • Onscreen videos • HTML-help • Interactive tutorials

Selecting a combination depends, consequently, on a large number of factors, e.g. • Which kind of product are we to document? • Which users are to be addressed? • Economy: In which country is it going to be used?

Onscreen help is user assistance in the form of documentation that directs and navigates a user of a computer through step-by-step instructions to follow when s/he does not know what to do next or encounters problems with an application/program. It is also called “guidelines”.

4.2.1 Onscreen manuals Advantages • Can contain internal and external links (all modern versions) • Can contain large amounts of information without having a "bulky look" • Relatively inexpensive or completely cost-free distribution • Fast and easy to update from the Internet

Disadvantages • Difficult to display large screenshots without reducing the image quality. The problem is that the original onscreen fonts and thin lines are optimised for the full screen and cannot be reduced without becoming almost unreadable • In most cases, available for pirate-users, too • User must have access to a computer with a suitable reader program

Some additional information should be presented to the user, independently from the onscreen manual: • About 15% of all users want to read the manual from A to Z at least once before they even attempt the installation. They need at least a "How to get

© CTI Education Group Unit 4 – Test procedural programming solutions Page 75

started" chapter/booklet in order to reassure themselves that they are not going to do anything wrong during installation. Onscreen guidance during the installation is not enough. • How to start the installation program. If it is advisable to terminate all other programs before starting the installation – including a virus checker – before starting the installation. • What to do if, for some reasons, you cannot access the onscreen help. This information should include the local hotline telephone number.

4.2.2 The classical “help” function The classical "Help" function has developed over at least the last 20 years from primitive text files to today’s much more sophisticated functions, including links, images, context oriented entries, sounds, videos, etc.

Advantages • It provides possibilities for explaining professional terms, abbreviations, etc., to beginners without interrupting the professional’s reading habits.

• Not page oriented: a "page" can have any size, from one line to thousands of lines, with as many graphics as you want

Disadvantages • Difficult/impossible to use the same content for a paper-based manual and the onscreen help • Many people have problems “getting on top of” the screen windows at the same time that they are performing the processes described. Consequently, they almost automatically print the pages needed

4.2.3 Wizards Wizards are not really a form onscreen help; instead, they are semi-automatic procedures whereby the user has to arrive at certain decisions in some of the steps. Make sure that the user knows the background in order to answer the questions. Very often, they do not. If not, offer some help. Wizards are most often used in addition to some other sort of help, e.g. "classical" help.

Advantages • Useful method to guide the user through a complex procedure • Suited for one-time procedures like installation

Disadvantages • The user never learns the "real" procedure – if it exists at all.

4.2.4 “Helpers” Helpers are the "intelligent" help functions, e.g. in MS Word 1997, you can, for instance, type in a question and thereby receive assistance. Helpers are most often used in addition to some other sort of help, e.g. "classical" help.

© CTI Education Group Unit 4 – Test procedural programming solutions Page 76

Advantage • It does not look scary/intimidating.

Disadvantages • Still not intelligent enough. Example: If the user does not find the "correct" term, no meaningful help will appear. Try, for example, typing "secret" text instead of "hidden" text in MS Word 1997. • If unsuccessful a couple of times, many users give up • Many users – especially academics – find it "childish" and consequently avoid using it.

4.2.4.1 The onscreen book type of help The Adobe Acrobat format seems to have “won the race”, becoming the de facto standard.

Advantages • You can use the files for the printed version directly and even include internal and external links • List of contents and index can automatically become links • Easy to print out with a 100% controlled layout • Platform independent (Windows, Mac, UNIX) Disadvantages • Page oriented • Dependent of the font used: may be difficult to read on a low–resolution (800x600 or less) screen • Many people still do not have an Acrobat reader, or still only have the Acrobat 2.0 reader. Solution: Always include the installation program for the reader with the help/manual file

4.2.4.2 Creating onscreen help Guidelines for onscreen help design: • Anticipate problems which the users may encounter and prepare solutions. • Provide a convenient access mechanism to the help function (easy access). • Make sure that users can easily and readily understand/grasp the help content. • Help information should be well organised, logical and easy to comprehend by the users who are skimming through the information. • Present help information in a format that is easily readable on screen. • Refer users to additional methods of getting help when they require assistance beyond what is provided in the help. • Maintain the help content by updating it as often as possible and revising the content to eliminate existing errors.

Some of the benefits of using onscreen help as a form of user assistance: • The onscreen help directs and navigates users of a computer through step- by-step instructions to follow when s/he does not know what to do next or encounters problems.

© CTI Education Group Unit 4 – Test procedural programming solutions Page 77

• Onscreen help makes a computer program easier to use because of the guidance offered to the user in the form of easily readable onscreen assistance. • It includes program navigation and, therefore, increases the program’s user- friendliness. • Onscreen help also refers users to additional methods of getting help when they require assistance beyond what is provided in the help. • The computer program or software will attain longevity. The faster and easier a user can use this software, the more reliable it becomes; and users are keen to use such programs/products. • Sales: Improved sales will result from the availability of easy-to-use product/software information.

4.3 Design reviews Design review is the process in which the design is evaluated against the requirements specifications presented before. This includes the presentation of planned software design at early stages of the lifecycle so that changes can be made easily. Design reviews facilitate communication between the design team, management and the customer.

Purpose served by design reviews: • Design reviews facilitate in ensuring that the proposed design will meet the specified requirements. • Design reviews facilitate in ensuring that the technical goals of the organisation will be met. • Design reviews facilitate in ensuring that the software design principles will be met.

4.4 Exercise 8

Let’s do this

1. What is a priming read? What is its purpose? 2. What are some of the benefits of using onscreen help as a user assistance? 3. Distinguish between a post-test and priming read in input validation.

Concluding remarks Numerous error-checking mechanisms can be used to test procedural programming solutions. It is important to test that the given procedural programming solution gives a valid solution. Supportive documentation must be included in the final system, and must be accurate so that it will be of help to users. There are currently seven different types of onscreen help/manuals/tutorials. Each has its own advantages and disadvantages, so it is up to the developer to decide which one to use for their computer program.

© CTI Education Group Glossary Page 78

Glossary

Structure that holds many variables of the same data type and Array referenced with the same name Boolean It accepts a Boolean as a value The flow of program is directed to other parts of the program, Control structure based on a condition or the result of a decision made Documentation Giving information about all the parts of a program The ability to detect errors that may occur during the writing, Error detection compiling and running of programs Functions It always returns value but may or may not accept parameters Global variable Variable declared to be used throughout an entire program English-like program that has to convert to machine language High-level programming before it can be executed Integer Basic data type that stores whole numbers as values Uses binary numbers (0’s and 1’s) to communicate directly with Low-level programming the computer Register of a computer’s control unit that contains the data to be Memory registers stored in the computer storage, such RAM and ROM NAND False only if both inputs are true NOT An inverter which changes true input to false and false to true NOR Result is false if either input is true OR Result is true if either input is true Parameters The arguments that are passed inside a function Procedures May accept or not accept parameters but do not return values Used to show the steps in the computer programs and movement Program flowchart of each step in the process Also called unchecked exceptions and occur while the program is Run-time errors executing String Basic data type that accepts words as a value Decide where the flow of control will be directed in the program, Structures depending on the outcome of the decision made Variable declared inside the main program and re-declared inside Static variable a procedure or function Syntax error Wrong spelling of keywords in the code Shows the structure and the fitness of computer programs in an System flowchart information system Used to store data used by the program; it is a name formed with Variable rules that can represent a number, character or word XNOR Result is false if, and only if, one of the inputs is true XOR Result is true, if and only if, one of the inputs is true

© CTI Education Group Bibliography Page 79

Bibliography

Edwards, T.; Kolle, T.; Mc Evilly, R. & Maenetja, C. 2010. Software engineering. 1st edition. : CTI Education Group.

Gaddis, T. 2016. Starting out with programming logic & design. 3rd edition. USA: Addison-Wesley.

Software in Practice. 2014. Software requirements specification. [Online] Available at: http://www.chambers.com.au/glossary/software_requirements_specification.p hp [Accessed: 10 November 14].

© CTI Education Group

Contact details

Bedfordview Campus Campus 9 Concorde Road East, Bedfordview Tourist Centre, 60 Park Avenue, Willows, Bloemfontein P.O. Box 1389, Bedfordview, 2008 P.O. Box 1015, Bloemfontein, 9300 Tel: +27 (0)10 595 2999, Fax: +27 (0)86 686 4950 Tel: +27 (0)51 430 2701, Fax: +27 (0)51 430 2708 Email: [email protected] Email: [email protected]

Cape Town Campus Campus The Brookside Building, 11 Imam Haron Str 1 Lunar Row, Umhlanga Ridge, Durban (old Lansdowne Road), Claremont P.O. Box 20251, Durban North, 4016 P.O. Box 2325, Clareinch, 7740 Tel: +27 (0)31 564 0570/5, Fax: +27 (0)31 564 8978 Tel: +27 (0)21 674 6567, Fax: +27 (0)21 674 6599 Email: [email protected] Email: [email protected] Durbanville Campus East London Campus Kaapzicht, 9 Rogers Street, Tyger Valley 12 Stewart Drive, Berea, East London P.O. Box 284, Private Bag X7 PostNet Suite 373 Tyger Valley, 7536 Private Bag X9063, East London, 5200 Tel: +27 (0)21 914 8000, Fax: +27 (0)21 914 8004 Tel: +27 (0)43 721 2564, Fax: +27 (0)43 721 2597 Email: [email protected] Email: [email protected] Campus Nelspruit Campus 50 Murray Street, Nelspruit Building 4, Ascot Office Park P.O. Box 9497, Sonpark, Nelspruit, 1206 Cnr Ascot & Conyngham Roads, Greenacres Tel: +27 (0)13 755 3918, Fax: +27 (0)13 755 3918 P.O. Box 40049, Walmer, 6065 Email: [email protected] Tel: +27 (0)41 374 7978, Fax: +27 (0)41 374 3190 Email: [email protected] Campus Campus 12 Esselen Street, Cnr Esselen Street 22 Umgazi Street, Menlo Park, Pretoria & Steve Biko Avenue, Die Bult, Potchefstroom PostNet Suite A147, Private Bag X18, P.O. Box 19900, Noordbrug, 2522 Lynnwood Ridge, 0040 Tel: +27 (0)18 297 7760, Fax: +27 (0)18 297 7783 Tel: +27 (0)12 348 3060, Fax: +27 (0)12 348 3063 Email: [email protected] Email: [email protected] Campus Vanderbijlpark Campus 6 Hunter Avenue, Cnr Bram Fischer Drive Building 2, Cnr Rutherford & Frikkie Meyer Boulevards Ferndale, Randburg Vanderbijlpark P.O. Box 920, Randburg, 2125 P.O. Box 6371, Vanderbijlpark, 1900 Tel: +27 (0)11 789 3178, Fax: +27 (0)11 789 4606 Tel: +27 (0)16 931 1180, Fax: +27 (0)16 933 1055 Email: [email protected] Email: [email protected] Group Head Office Management Services Building 44 Alsatian Road, Glen Austin Extension 3, P.O. Box 1398, Randburg, 2125 Tel: +27 (0)11 467 8422, Fax: +27 (0)86 583 6660 Website: www.cti.ac.za

CTI is part of Pearson, the world’s leading learning company. Pearson is the corporate owner, not a registered provider nor conferrer of qualifications in . CTI Education Group (Pty) Ltd. is registered with the Department of Higher Education and Training as a private higher education institution under the Higher Education Act, 101, of 1997. Registration Certificate number: 2004/HE07/004. www.cti.ac.za.

© CTI Education Group