Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
148 views

2021 Computer Science Problem-Solving Module Coursebook Student

This document outlines the objectives and contents of a module on problem-solving with computers. The objectives are for students to develop skills in creative, collaborative and critical thinking using technology. Students should understand the problem-solving process, the role of algorithms, and be able to describe stages of problem-solving, apply problem-solving approaches, interpret and develop algorithms. The contents cover topics like the problem-solving process, algorithms, representation of algorithms, control structures, arrays, records, files and testing algorithms.

Uploaded by

Big Head
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views

2021 Computer Science Problem-Solving Module Coursebook Student

This document outlines the objectives and contents of a module on problem-solving with computers. The objectives are for students to develop skills in creative, collaborative and critical thinking using technology. Students should understand the problem-solving process, the role of algorithms, and be able to describe stages of problem-solving, apply problem-solving approaches, interpret and develop algorithms. The contents cover topics like the problem-solving process, algorithms, representation of algorithms, control structures, arrays, records, files and testing algorithms.

Uploaded by

Big Head
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 198

C-A.

Jardette

MODULE OBJECTIVES

At the end of the Problem-Solving with Computers module students should:


1. Develop creative, collaborative, communicative and critical thinking skills, using
appropriate Information and Communication Technologies
2. Understand the problem-solving process
3. Appreciate the role and importance of algorithms in the problem solving process
4. Understand the process of developing algorithms

They should be able to:


1. Describe the stages in the problem-solving process
2. Explain concepts related to related to problem-solving
3. Apply approaches to problem-solving
4. Explain the concept of, and need for, algorithms
5. Identify the necessary properties of algorithms that are well-designed
6. Identify and evaluate ways of representing algorithms
7. Explain constructs used in structured programming
8. Interpret given algorithms
9. Correct given algorithms based on case problems
10. Develop correct algorithms from case problems

[1]
Computer Science Unit 1 Module 2

CONTENTS

Section/Topic Page

1. Introduction ...................................................................................................................... 4

Steps in Problem Solving ............................................................................................. 5

Functional and Non-functional Requirements ......................................................... 9

Problem-Solving Methods ........................................................................................... 14

2. The Need for Algorithms ............................................................................................... 15

3. Ways of Representing Algorithms ................................................................................ 20

4. Narrative Algorithms ...................................................................................................... 22

5. Simple Data Handling .................................................................................................... 28

6. Control Structures ........................................................................................................... 29

7. Flowcharts ........................................................................................................................ 34

8. Simple Algorithms........................................................................................................... 36

Guidelines for Writing/Drawing Algorithms ........................................................... 46

9. Selection Algorithms ....................................................................................................... 50

If ....................................................................................................................................... 51

Case ................................................................................................................................. 66

10. Iteration ............................................................................................................................. 73

While Loops ................................................................................................................... 73

Repeat ...Until Loops..................................................................................................... 87

For Loops ........................................................................................................................ 99

11. Introduction to Functions ............................................................................................... 114

12. Arrays ................................................................................................................................ 130

Parallel Arrays ............................................................................................................... 134

Passing Arrays ............................................................................................................... 141

Linear Search of an Array ............................................................................................ 141

13. Records .............................................................................................................................. 144

[2]
C-A. Jardette

14. Files.................................................................................................................................... 148

15. A Complete Program ...................................................................................................... 168

16. Testing Your Algorithm ................................................................................................. 175

Testing Techniques ....................................................................................................... 178

Trace Tables ................................................................................................................... 179

Testing Glossary ............................................................................................................ 188

17. Determining Output ....................................................................................................... 188

18. Programming Glossary .................................................................................................. 193

Worksheets

1. Problem Solving Process ................................................................................................ 13

2. Sequential and Selection Algorithms ........................................................................... 72

3. Unbounded Loops .......................................................................................................... 97

4. Bounded Loops................................................................................................................ 113

5. Arrays................................................................................................................................ 143

6. Trace Tables...................................................................................................................... 185

[3]
Computer Science Unit 1 Module 2

PROBLEM-SOLVING WITH COMPUTERS

1. AN INTRODUCTION

1.1
How did you go about deciding what to do about schooling
after 5th form? Notes
How did you decide what subjects to study in 6th form?
How do or did you decide what to have for lunch today?

Humans are by nature decision makers. Every situation that


requires that one makes a decision can be regarded as a
‘problem’. And because we meet these situations in our lives
on a daily basis, numerous times per day, we are all problem
solvers to one degree or another. In this course we will be
examining the concepts of problems and problem-solving.
Consider the following situation which you may very well
find yourself facing in a year and a half –
A student who is on the cusp of leaving high school has
received three very good offers from highly desirable
universities in a foreign country. All three schools are offering
the student a full 4-year scholarship. How does this student
go about deciding which offer to accept? What process will
she follow in making the decision? What factors will she
consider?

1.2
Problem:
a) A situation that presents perplexity, challenge or
difficulty; a misgiving, question or puzzle to be solved or
answered.
b) The difference between the current state and the
goal state; an opportunity for improvement.

[4]
C-A. Jardette

Computer Science has grown in relevance as a subject


Notes
because of the increased dependence by society on the
computer as a problem solving tool. The computer
achieves this through the use of programs. A computer
program is really just software that solves a problem.
But as we know, computers on their own do not know
how to solve problems, they must be told what to do by
someone. That someone is – you – the programmer.
That means that you must firstly know how to solve the
problem before you can tell the computer how to do it.
To be a good programmer then, we must be good
problem solvers.

What is problem solving therefore? Simply it is the


ability to determine the best solution for a problem in a
quick and efficient manner. Put another way, it is a
process that enables one to find an answer to,
explanation for, or means of effectively dealing with,
a matter or situation regarded as unwelcome or
harmful and needing to be dealt with and overcome.

1.3 The Steps in Problem Solving


Some people are better at problem solving than others.
Whether it is from experience or because they adopt a
systematic approach to problem solving, they are able
to extricate themselves from problems more efficiently
than others. But everyone can improve their problem
solving skills by using the following methodology
when presented with a problem situation –

[5]
Computer Science Unit 1 Module 2

Stages in the problem solving process:


1. PROBLEM DEFINITION
2. PROBLEM ANALYSIS
3. IDENTIFICATION AND EVALUATION OF POSSIBLE SOLUTIONS
4. SELECTION AND JUSTIFICATION OF THE OPTIMAL SOLUTION
5. IMPLEMENTATION AND REVIEW

Notes
This process is not particular to computing. Anyone in any
industry or in their personal life can benefit from using this
systematic approach to dealing with problems. Because we
are computer scientist however, we will look at the stages in
terms of the computing issues (the issues which can be solved
by computing/software within an organization). Bear in mind
that problem solving takes place before a program or a
computer system is developed. It helps one to identify the
goals of a new system so that you can then decide if the
derived solution is relevant to the situation presented.

1.4
Let us examine in detail, what happens at each stage of the
problem solving process.

Step 1 : PROBLEM DEFINITION


This is an integral though often consciously overlooked, step.
How can we proceed to solve a problem if we do not know
exactly what that problem is? So in this stage one a) verifies
that there is a problem, and b) clarifies exactly what that
problem is. Often what we first see are the results or causes of
problems but we need to get past that to the underlying real
problem. It is important not to get side tracked on side issues
and also not to miss critical aspects of the real problem.

[6]
C-A. Jardette

In the computer system/program development world, Notes


the problem may be something that is not working
properly, or it may even be an acknowledgement that
something could be working better. For example, if
employees are disgruntled and underperforming, it
may be that the problem is that they are unhappy
because their pay package has been late for the last 3
months. If customers are grumbling when they wait in
the cashier line it could be that the cashier’s printer is
too slow and so it increases each customer’s wait time.

Many projects require that the Systems Analyst


document the problem to be addressed right at the
beginning. The Problem Definition is a written document
which outlines the fundamental difficulties being
experienced. It should be clear and concise.

Note that this is the first stage in the Computer Science SBA
project. Students are required to identify a problem and
produce a problem definition document.

Step 2 : PROBLEM ANALYSIS


So now we know what the problem is, but do we know
what’s causing it, or who it’s affecting, or what the
repercussions of this situation are? Analysis is aimed at
answering these critical questions. A thorough
understanding of the problem situation is crucial before
we can be in a position to devise a solution to the
problem. It is important therefore that you thoroughly
study and understand the existing underlying system.

[7]
Computer Science Unit 1 Module 2

Consider the Analysis phase like a visit to the doctor. Step 1 - You Notes
know that you feel sick. Step 2 – You visit the doctor.
You would be pretty worried if you told the doctor you had a
headache (the problem as far as you’re concerned) and the doctor
immediately started merrily injecting you with various drugs before
even looking at you or asking you any other questions. Such
behaviour is likely to cause more problems than it solves, so though
you tell the doctor what you think is wrong, she always analyses –
by observing, questioning, testing – to determine the cause, before
beginning any treatment.

In the same way problem solvers break down their task into
sub-tasks and study the components of the system they
intend to change, and the organisation it's in, before they
decide what needs to be done. By thoroughly understanding
a system, its operation, its people, its context, its strengths and
weaknesses, one can better decide how to start improving it.

All personnel on whom the problem impact should be


identified and be involved in the analysis. One may use any
of the following methods to analyze a system/organisation:

 Interviews
 Surveys/questionnaires
 Observation
 Examining documentation and policies

The results/findings should always be documented.


Narrative or diagrams can be used. Structure charts, system
flowcharts, decision trees and data flow diagrams are very
useful in this context; they help to illustrate one’s findings.

[8]
C-A. Jardette

The Objectives of Analysis: Notes


One of the main things that happen during analysis is
the elicitation and specification of the requirements for
the new system. A requirement is a feature that is
desired in the new program. Requirements can be
functional or non-functional.

Functional requirements – Briefly, a functional


requirement is a statement of one service that the
program should provide i.e. what the program should
do. To be more precise, the functional requirements are
the set of descriptions of what inputs the program
should accept, how it should handle this input, and
what outputs it is to give. Functional requirements are
about the internal workings of a program: its data
manipulations and its calculations.
Examples:
1. The user shall be able to search the records for
appointments using the client’s surname.
2. Each staff member shall be identified by a unique 6
digit employee number.
3. A consumption tax charge at rate of 15% shall be
added to every purchase.
4. The client shall be able to buy as many different items
as they wish in one order.
5. Authorised cafeteria staff shall be able to view a
complete list of orders for the day at any time.

Non-Functional requirements – the non-functional


requirements are the set of statements about how the
program should behave or how the development project
should proceed.

[9]
Computer Science Unit 1 Module 2

Examples:
1. The program should be able to be installed on any computer which is using the MS Windows
operating system.
2. The program must be available 24 hours per day except if being backed up after office hours.
3. The system should be able to process at least 30 transactions per second.
4. The development project is to be completed within 18 months from the start date.
5. The system should be accompanied by a hard copy user manual.

At the end of analysis therefore,, the analyst should understand the problem more and also be
able to describe what causes it. He/she should also know what the goals/aims of a solution
are. What does a solution to the problem look like? Not how the solution is to be achieved,
just the changes to be effected by the solution. In the realm of computing, the analysis phase
should help the analyst to identify the inputs, outputs, storage and processing needed in a
system.

Step 3 : IDENTIFY AND EVALUATE POSSIBLE SOLUTIONS


This stage is about three things -
 Determination of the criteria on which to compare/judge the alternatives
 Identification of alternative courses of action and gathering detailed information on
them
 Rating the alternatives according to the criteria

Some of the factors to consider are-


 What features are desirable in a solution?
 How desirable is a particular feature? (critical? must have? very important? Important?
nice to have? not important? not needed?)
 How effectively does each solution provide each needed feature?
 How long will it take to implement a particular solution?

[10]
C-A. Jardette

 Cost :
Notes
o What is the cost of constructing this solution?
o What will be the cost of implementing this
solution?
o What will it cost to maintain over its lifetime?
 What kind of support will be needed/available over its
life?
 What kind of interface will there be between the system
and users?
 What kind of security measures are included?
 How adaptable is this solution (for future changes)?

Exposure to current
trends in IT and
knowledge of what
is available on the
market in terms of
both hardware and
software is needed in order for one to be good at this step.
Solutions may be prepackaged or they may involve
developing a system from the ground up.
At the end of this process, the analyst or team of analysts
submits a report to the management of the organisation. This
is a detailed report which restates the problem, states the goals
of a new system, identifies the feasible choices and rates each
one according to the criteria which are important to the
company. It also should conclude with recommendations on
which solution is best and why.

Note carefully that while the analysts may favour one solution
above the others, they must give the organisation choices and
include the advantages and disadvantages of each one.

[11]
Computer Science Unit 1 Module 2

Step 4 : SELECT AND JUSTIFY THE OPTIMAL SOLUTION


At this stage a decision is made on which solution to
Notes
create/implement. The decision is the prerogative of the
main stakeholder in the organization (shareholders,
board, management) and not the analyst. However, the
analyst’s recommendation will go a long way.
The computer/system persons may be the main
technical people on the project but the people who
control the organisation’s finances and will be using the
system hold the bigger sway in what happens.
There are many instances where a project stalls at this
point. Sometimes the organisation finds that it can not
or does not want to pay the cost (in money/in time/in
energy) required to implement a new system.

Step 5 : IMPLEMENTATION AND REVIEW


The chosen solution is now put in place and then
assessed.
Implementation may be short and simple or it may be
very long and complex. It may involve buying
hardware and/or software or even creating new
software and converting data from an old system to the
new one. Implementation should always involve
training users in the new ways of operating; and also
testing a system before it goes ‘live’. On major projects
implementation could take up to 60% of the project
time.
Since the objective was to eradicate the particular
problem identified in the first stage, there should now
be a review to determine if the problem has been
resolved.
If a problem is identified during review… you are back
at step 1.

[12]
C-A. Jardette

WORKSHEET 1 - THE PROBLEM SOLVING PROCESS

Answer the following questions making sure that your responses relate specifically to the particular
cases in the questions.

1. A school library uses a manual system for recording information on books borrowed
by its members. The school has hired a computer professional to automate the manual
system.
a) Identify 4 problem solving steps which must be undertaken before the
manual system can be smoothly automated. [4]
b) Describe 3 of the activities you identified in a) in the context of the school
library. [6]

2. A company which sells stationery items has been experiencing problems adequately
servicing its customers over the past 2 years and is facing a loss of confidence and
consequent loss of business. The management thinks that their manual way of
operating may be a major contributing factor to their difficulties and has asked a
software house to assist.
a) Identify 4 problem solving activities which the organization should perform
before the manual system can be smoothly automated. [4]
b) Describe 3 of the activities you identified in a) in the context of the sales
company. [6]

3. The management of the Gude Rest Inn has decided to use a computer system to
automate
its operations. The company has hired a team of technology experts to do the job.
a) Identify 4 problem solving steps that the experts should perform to achieve
the company’s automation goal [4]
b) Describe 3 of the activities making specific reference to this situation [6]

4. Clients of a dressmaking establishment complain that their orders get mixed up way
too often and that they have to wait too long to get an item made. The proprietors of
the business think computerizing their operations many make them more efficient and
have called in some systems analysts to assist.
a) Identify 4 activities the systems analyst must undertake to fix the organisation's
problems [4]
b) Describe the activities which make up 3 of those steps making specific
reference to this situation [6]

[13]
Computer Science Unit 1 Module 2

1.5 Problem-Solving Methods


This refers to the various possible approaches to solving a big problem. The possibilities are:
top-down, bottom-up, and step-wise refinement.

Top-down problem solving involves breaking down a large complex problem into smaller
parts. This is a very intuitive human problem solving methodology which results in smaller
and smaller modules until the designer deems them small enough to be solved.

In Bottom-up problem solving, the starting point is the details, and these low level details are
continuously combined into larger and larger modules until the overall system abstraction
level is achieved. There is often an assumption in bottom-up problem solving that small
solutions already exists to the minor problems, and that these solutions can be successfully
combined to solve the large problem.

Step-wise Refinement is the process of systematically and sequentially breaking down an


issue into its components until the resulting components are programmable. If this sounds
like the top-down approach, it is. The term step-wise refinement is used more specifically in
computing however, to indicate not just that the problems are broken down, but that the other
aspects of the algorithm, (the data structure and file usage for example) are also being refined
as the development is taking place. While top-down strategy is a general term/approach used
by many industries therefore, step-wise refinement is a computing industry term which
depicts the progressive refinement of program specifications into an algorithm which involves
both the processes to take place and the data that is being manipulated.

[14]
C-A. Jardette

2. THE NEED FOR ALGORITHMS

2.1 Case Study

The PTA at Omega-Pi High School decided that the school should be using technology
more so it employed a programmer to write a program for the school. The program was to be
used to manage the personal data and grades of students and to generate periodic reports for
sending home to parents. The PTA President and the Treasurer met with the programmer
and agreed on the terms for the project, and then the programmer went off to write the
program. He delivered the first phase of the software 4 months later.
Three years later the principal of Omega Pi High is facing serious rebellion among teachers.
They have been given a program to use that after 5 report exercises still does not work
properly. One of the major problems is the disappearance of grades. Teachers will spend
hours entering their students’ grades, only to see blank slots when they return the following
day. Another problem is the inability of the program to accommodate two users doing a
particular function at the same time.
Initially very few of the functions operated the way the school operates. This meant that
the programmer was called in once or twice every week to make corrections. Sadly 80% of the
time the correction then needed to be corrected or the correction caused another part of the
program to malfunction.
The school paid the programmer for the system on delivery and continues to pay him
$3,500 per hour each time he is called.
The teachers however are absolutely and thoroughly frustrated, and are calling a halt. They
have refused to use the program this term, and have voted, against the principal’s wishes, to
return to the manual method of recording grades and writing reports.

1. What is the problem being faced by the school’s administration?

[15]
Computer Science Unit 1 Module 2

2. What is your opinion of the method used to commission the programmer?

3. What role did the principal play in deciding how the program should work?

4. What role did the teachers play in determining what should be in the program?

5. If you were the president of the PTA what would you have done differently?

6. If you were the programmer what would you have done differently?

2.2
We must move away from seeing the computer simply as a game machine or a tool for
chatting with friends or for viewing photographs or movies. As Computer Scientists we must
appreciate that the computer is much more than that. Can you name some areas of life in
which computer programs are now integral?

[16]
C-A. Jardette

Business processes like accounting, stock control and payroll calculations,


Industrial operations like process control, mining, manufacturing of goods,
Education,
Medicine,
Aeronautics,
Communication,
Weapons research and management, etc.

Let us imagine what would result if the methodology seen in the case study above was used
to create the programs in these areas of life:
budget over run, malfunctioning programs,
dissatisfied users, injury to personnel,
even loss of life

Who benefits from such an approach?


No one benefits from such an ad-hoc approach to creating new programs. While it may
appear that the programmer is doing well out of the situation, he has however damaged his
professional reputation. Very few people would employ someone who after many years is
unable to produce a reliable product. In the world of programming your reputation matters,
not just how much money you make on a single project.

We know that that is not the correct approach to writing programs, one does not simply hear
about a problem and sit at the computer and begin to program. We must firstly analyze the
situation, find out the needs from the actual intended users of the system, and then we must
create a plan – a design.

2.3
Algorithm – the set of steps or operations which will lead to the accomplishment of a task.

It is important to note that


 not every problem can be solved
 not every set of steps we encounter in life constitutes an algorithm. Well-designed
algorithms have some necessary characteristics. What are they?

[17]
Computer Science Unit 1 Module 2

Well-designed algorithms must have these necessary properties:


- be a general solution to the problem at hand
o they must solve the problem,
o they must work in all instances
- have clearly defined and unambiguous steps
o each step must be clear so that one does not have to guess what it means
o each step must have only one interpretation
- have a finite number of steps
o algorithms must come to an end at some point
- have a structured flow of control from one process to another
o the steps must be in a particular order and it must be obvious which step
comes next
o there cannot be places where things simply trail off and it is not known
how to get to the end from there

NOTES

[18]
C-A. Jardette

2.4 Algorithms as a Problem-solving Strategy


The use of algorithms can also be found in areas other than computing. Why are algorithms
used? In other words, what do you think the role of algorithms in life should be?
Algorithms are important so that time is not wasted
Algorithms are important so that effort is not wasted
Algorithms are important so that money is not wasted
Algorithms are important so that one does not continually find oneself doing devising
a methodology for doing the same things over and over
Algorithms are important as they reduce the instances of failed projects and many
regrets.
The truth is that given the size, complexity and importance of real life computer programs, if
one attempts to write those programs without a plan, they will invariably be wrong/have
many errors.
Note too that is during the planning process as we attempt to create the algorithm that we
begin to see some of the gaps in our knowledge. We then use the opportunity to speak to the
stakeholders again and clarify their requirements. Thus making our programs better
solutions to their problems.

PS. Not all problems have algorithms, as not all problems have a solution

[19]
Computer Science Unit 1 Module 2

3. WAYS OF REPRESENTING ALGORITHMS

Algorithms can be represented in a variety of ways. In this course we are concerned about 3
representations:
1. narrative 2. pseudocode 3. flowcharts

3.1 Narrative
This is the use of natural language and natural language rules
to construct sentences and paragraphs which describe the
steps to take.

The advantages of using narrative are that -


 it can be applied outside of computing,
 It is in a human’s natural language and is easy to read
and understand b the lay person, and
 It requires no special training to construct

The disadvantages of a narrative are that -


 it can be too verbose (too wordy)
 It can be context-sensitive (interpretation varies
depending on person’s background and experience)

The use of bullets and point form is highly recommended


when writing algorithms in a narrative form.

3.2 Pseudocode
A type of structured English that is used to specify an
algorithm in the world of computing. Pseudocode uses
English-like expressions and mathematical statements.

The advantages of pseudocode are that -


 it is independent of any particular programming
language so programmers using different languages
can all still understand it
 programmers do not have to worry about syntax, the
emphasis is on the logic
 lay people can help to determine the validity of the
logic because it is not that difficult to understand

[20]
C-A. Jardette

The disadvantages of pseudocode are that -


 It is very detailed and so requires a high level of
concentration to determine the overall logic
 The loose standards mean that one solution may
be depicted in several different ways by different
persons

Note the following when writing pseudocode:

• You should give your pseudocode a name, this


name can later serve as the name of the program
• Include a global comment (a brief description to
indicate what the program does)
• At the top, practice listing all the variables used
and what data type they are.
• The use of constants is encouraged
• You must always have start and stop.
• Use indentation to help depict the logic
• For longer programs use local comments to
explain what each section does
• Use clear prompts to give instructions to the user;
prompts are always followed by a read operation
• The following terminology can be used
• Input statements - input, get, read
• Output statements – display, print
• Assignment statements -  , set to, let be
• IF –THEN ENDIF
• IF – THEN – ELSE ENDIF
• CASE
• FOR .. TO
• WHILE … DO
• REPEAT.. UNTIL

3.3 Program Flowcharts


A diagrammatic representation of the sequence of steps needed to perform a task using
predefined symbols. They show the sequence of operations, movements, decisions and
storage activities within a system.

The advantage of flowcharts is that -


 it is easy to understand by persons at all levels because of the visual nature

[21]
Computer Science Unit 1 Module 2

The disadvantages of flowcharts are that -


 They can become large and unwieldy when the programs are long and complex
 When alterations are required the flowchart will have to be completely redrawn.
 Production of flowcharts is a complex exercise.

Note the following when drawing flowcharts:

 Flowcharts should have a title/label


 All flowcharts must have one start and one stop point
 Flow lines should run from top to bottom (or left to right)
 Flow lines should not cross
 Start symbols have only one flow line going out
 Stop symbols have one flow line going in
 Decision symbols should have one flow line going in and no less than two coming
out
 Most other symbols have one line going in and one coming out
 Symbols must have the operation that they depict written in them

4. NARRATIVE ALGORITHMS

4.1
There are no hard and fast rules about how narrative algorithms should be written. The only
requirements are that they be as clear, concise and succinct as possible. Let us examine 2
problem situations and the corresponding narrative algorithms.

4.2
Example 4a: At a beauty salon the following services are offered.
■ cream - $3,500
■ wash and set - $1,500
■ style - $1,000
■ pedicure - $2,000
■ manicure - $2,000
How would a computer program go about calculating a client’s bill? Write the
narrative algorithm.

[22]
C-A. Jardette

Narrative – Salon Bill


1. Get client name
2. Display the list of services available and attendant cost
3. Initialize bill amount to zero
4. For each service selected
a. Add the cost of the service to the bill amount
5. Calculate the tax amount
6. Add tax amount to bill amount to arrive at the final total

Example 4b: BettaBody Gym offers the following membership packages where the Platinum
and Silver packages offer any day access and the Gold and Bronze packages
only allow weekend access to the gym facilities.
Platinum - $55,000 for 12 months Gold - $45,000 for 12 months
Silver - $30,000 for 6 months Bronze - $25,000 for 6 months
Members who sign up for group packages are entitled to discounts as follows:
Group of 3 to 5 people - 4% discount each
Group of 6 to 10 people - 7% discount each
Group of more than 10 people - 10% discount each
Organizational account
- less than 21 employees - $750,000 per year
- more than 20 employees - $1,000,000 per year

Write the narrative algorithm showing how a program would determine how much a
prospective gym member should pay.

Narrative – Gym Membership


1. Get prospective member’s name.
2. Determine if prospective member is an individual or is an organization.
3. If prospective member is an organization
a. get number of employees in the company.
b. if number of employees is less than or equal to 20 set $750,000
as the bill amount.
c. if number of employees is greater than 20 set $1,000,000 as the
bill amount.

[23]
Computer Science Unit 1 Module 2

4. If prospective member is not an organization,


a. determine if prospective member wants a 6 month or 1 year
plan
b. determine if prospective member wants in the week access to
the gym
c. if prospective member wants yearly access with weekday
privileges set bill amount as $55,000
d. if prospective member wants a 6 months plan with weekday
privileges set $30,000 as the bill amount
e. if prospective member wants weekends only for 6 months set
bill amount as $25,000
f. otherwise set bill amount as $45,000
g. set discount amount as zero
h. if prospective member is part of a group
i. determine how many members want to sign up as part
of the group
ii. if group size is less than 6 but greater than 2 set
discount percentage as 4%
iii. if group size is between 6 and 10 inclusive set discount
percentage as 7%
iv. if group size is more than 10, set discount percentage as
10%
v. calculate the discount amount
i. subtract discount amount from bill amount
5. Display cost of membership

Example 4c: Members of the public apply to Bank A for a loan to buy a house. They must be
a customer with a certain savings balance or meet the earnings criteria.

Narrative – Housing Loan


1. Get cost of house
2. Determine net salary
3. Get savings account balance
4. Determine eligibility

[24]
C-A. Jardette

2. Determine net salary


a. Get gross salary
b. Get bill amounts
c. Get debt amounts
d. Calculate net

4. Determine eligibility
a. Add net salary to account balance
b. If sum is greater than 10% of house cost then
grant loan
otherwise
deny loan

[25]
Computer Science Unit 1 Module 2

PRACTICE EXERCISE 1

1. Write the narrative algorithm that determines for each student in a certain high school,
if that student is eligible for an academic prize at the school’s award ceremony and say
which award he/she will get. You may use a simplified award criteria.

[26]
C-A. Jardette

2. Write the narrative for the cost of a child attending a day care centre. The cost per day
depends on the child’s age - 0 to 11 months : $300, 1 year to 2 years : $250, 3 years to 5
years : $200. The cost of additional services such as bathing and administration of
medicine is also added. (Make up any figures not given).

[27]
Computer Science Unit 1 Module 2

5. HANDLING DATA

5.1
The purpose of computer software is to process data into useful information for computer
users. Our programs must therefore be able to read, store and output data. Constants and
variables are used for data storage during the execution of a program.
A constant is a named piece of data whose value can not be changed during the running of
the program
A variable is a named slot in memory reserved for storing a particular type of data. The actual
value in the slot can be modified any time during the running of the program.

5.2
The data handled by a program can be classified as simple/scalar/basic or as structured.
Scalar Data - This implies that one variable stores one single piece of data – an integer, a
floating point number (real), or a character. For our purposes we could also include strings in
this category though strictly speaking a string is not scalar but instead is a set of characters.

Integer – any whole number positive or negative e.g. 12, 567, -94, -384567
Real/Float – any number, positive or negative, which has a decimal point e.g. 45.67, 9.0, -3.8
Character - any single letter, number or symbol, which can be typed on the keyboard,
surround characters by single quotes ‘ ’ e.g. ‘T’, ‘ ‘, ‘4’, ‘#’
String - a combination of one or more characters, surround string values by double
quotes “ ” e.g. “End”, “Enter a number”, “Hello World!”

5.3
Naming Data
Each piece of data has a unique symbolic name given to it by the programmer. Names should
begin with a letter and be descriptive. Generally, only letters, numbers and the underscore
should be used.

E.g. costofgoods1 costOfGoods1 cost_of_goods_1

[28]
C-A. Jardette

6. CONTROL STRUCTURES

6.1
The term ‘control structure’ refers to the mechanism used to decide which statement in a
program will be executed next. Irrespective of the size and complexity of a problem, there are
three basic control structures which can be used to construct a solution, and thus create a
program of any size. These are 1) sequencing, 2) selection, and 3) iteration. Recursion – when
a module calls itself – is also regarded as a control structure. However, it is not a basic control
structure and is not required for this course.

6.2
Sequencing – the execution of a set of statements one after the other in the order in which
they appear. This is the default mode of operation for most programs and does not require the
programmer to do anything except specify the operations in the correct order.
The operations implied by sequencing are – output statements (including prompts), input
statements, and assignment statements (including calculations).

Output statements: in this kind of statement the program gives out information, whether in
the form of textual or graphic prompts/directives to the user, or the results of processing.
Terms used in output statements include output, print, write and display.
E.g. display name
print “Enter Y or N’
write “The total is”, total

Input statements: this kind of statement instructs the program to accepts data. Terms used to
indicate input include get, input and read.
E.g. read amount
input name, date_of_birth,

Assignment statements: these statements result in a change in the value of a variable.


E.g. num  23
sum  val1 + val2
let total equal 0
set name to “Blank”

6.3
Selection – also known as branching, selection sees the program evaluating a condition and
then, depending on the truth value of the condition, taking one of two or more paths. There
are 2 types of terminology associated with selection – if and case

[29]
Computer Science Unit 1 Module 2

IF Statements
An if statement takes the form
If (conditional_expression) then
statements1
else
statements2
endif

The conditional expression is evaluated. If the result is true, the set of operations –
statements1 – are executed and the else section is skipped entirely. If the condition evaluates
to false however, statements1 is skipped and only the operations at statements2 are executed.
Some if statement do not have an else clause.

E.g. if (name = “End”) then


display “The program will now end”
endif

E.g. if (days_worked >= 90) then


bonus  0.5
else
bonus  0
endif

Switch Statements
Also known as a case statement in some languages, this provides possible value matches for a
variable and a block of statements to be executed if the variable matches that value. They are
a substitute for long if statements and can usually only be used with ordinal objects1 such as
integers and characters. An example follows:

1 Scalar or ordinal objects have a discrete and finite range of values. Integers are scalar but reals/floats are not.

[30]
C-A. Jardette

switch month
case “January” – display “New Years’ Day”
display “The start of the year”
case “February” – display “Ash Wednesday”
case “March” – display “Good Friday”
case “April” – display “Easter Monday”
otherwise - display “No holidays”
endcase

6.4
Iteration – when a set of one or more statements is executed over and over again. The
statements to be repeated are normally enclosed in a block that indicates how many times
they are to run. They may be set to run for a fixed number of iterations or until a condition is
met. The formats are:

while (conditional expression) do


statements to be repeated
enddo

repeat
statements to be repeated
until (conditional expression)

for (initial_value, conditional expression, increment)


statements to be repeated
endfor

[31]
Computer Science Unit 1 Module 2

PRACTICE EXERCISE 2

1. Explain the necessary characteristics of a well-designed algorithm?

2. Why is it important to design a program before coding it?

3. Why are programs not written based solely on narrative algorithms?

[32]
C-A. Jardette

4. What advantage is there in using flowcharts to represent an algorithm?

5. What is the difference between selection and iteration?

6. Distinguish between the usage and operation of while loops and repeat until loops.

[33]
Computer Science Unit 1 Module 2

7. FLOWCHARTS

7.1 Here is a list of the most common flowcharting symbols.


SYMBOL NAME USE
Terminator * Indicates the start and the end of processing

Input / Output * Shows data input to, or output from a process

Process * An operation on data such as a calculation

Decision * The conditional statement to be evaluated to


give a true or false value

Predefined Process * A sub-process/function defined in detail


elsewhere

Flow line * Shows the direction of processing or of the


movement of data
Preparation * An initialization or set up process

Document A hard copy output

Data Storage A file (secondary storage)

Magnetic Tape Sequential Access storage medium (file)

Connector / On-page Jump from one point to another on the same


Connector * page
Connector /Off-page Continuation onto/from another page
Connector *
Callout Used to add comments to a flowchart

[34]
C-A. Jardette

PRACTICE EXERCISE 3

Match the symbol to the statement by writing a letter into each shape.

1. 2. 3.

4. 5. 6.

7. 8. 9.

10. 11. 12.

A. read name from file J. sort marks


B. accept age K. D
C. print answer L. while option = ‘T’
D. display “Enter a number” M. total <= 100
E. choice  ‘N’ N. output client record
F. sum  sum + newnum
G. verify password
H. stop
I. name < > “Last”

[35]
Computer Science Unit 1 Module 2

8. SIMPLE ALGORITHMS

8.1 We will now examine various examples of algorithms represented by pseudocode and
flowcharts, and also create some of our own. This first set will involve only sequential
operations.

8.1 Design a program that accepts 3 numbers and displays their total and product.

Solution

Pseudocode : SumofNums Flowchart : SumofNums


// Find the sum and product of 3 numbers

DECLARATIONS START
Variables
prod, sum, num1, num2, num3 – data type real

PROCESS display “Enter a number”


// Get the input data
display “Enter the first number”
read num1
display “Enter the second number”
read num2 read num1
display “Enter the third number”
read num3
display “Enter another number”
// Perform the calculations
sum  num1 + num2 + num3
prod  num1 * num2 * num3

// Show the result read num2


display “The total is ”, sum
display “The product is ”, prod
STOP
display “Enter another number”

Note:
read num3
// indicates an inline comment
 is the assignment symbol, read
it as ‘is assigned the value’ sum  num1 + num2 + num3

prod  num1 * num2 * num3

STOP display sum, prod

[36]
C-A. Jardette

8.2 Design a program that finds the area of a triangle given its base.

Solution

Pseudocode : TriangleArea Flowchart : TriangleArea


// Find the area of a triangle given its height and base

DECLARATIONS
START
Constants
factor = 0.5
Variables
base, height, area - data type real display “Enter the base”

PROCESS
// get the input data
display “Enter the base”
read base
read base
display “Enter the height”
read height

// perform calculation display “Enter the height”


area  factor * base * height

// show result
display “The area of that triangle is ”, area
read height
STOP

area  0.5 * base * height

display “The area of the triangle is ”, area

STOP

[37]
Computer Science Unit 1 Module 2

8.3 Design a program to accept a student’s name and 3 assignment marks, and calculates and
displays her average mark.

Solution

Pseudocode : ThreeMarks Flowchart : TriangleArea


// Find a student’s average

DECLARATIONS
START
Variables
name – data type string
mark1, mark2, mark3, avg – data type real

PROCESS
// get the input data display “Name?”
display “What is the student’s name?”
read name
display “Enter the 3 marks”
read mark1, mark2, mark3
read name
// perform calculation
avg  (mark1 + mark2 + mark3) / 3

// show result
display “The average for ”, name, “ is ”, avg display “Enter the 3 marks”
STOP

read mark1, mark2, mark3

avg  (mark1 + mark2 + mark3)/3

display “The average for“, name, “is“, avg

STOP

[38]
C-A. Jardette

8.4 Design a program that acts as a robot having a simple conversation with the user.

Solution

Pseudocode : Conversation Flowchart : Conversation


// Talk with a robot

START
DECLARATIONS
Variables
name – data type string
age, dif – data type integer display “Hey, Welcome”

PROCESS
display “Hey, welcome”
display “what is your
display “… and what is your name?” name?”
read name
display “Pleased to meet you “, name
display “My name is Progie” read name
display “How old are you?”
read age
display “I am 5 years old” display “Pleased to meet you ”, name
dif <- age – 5
display “You are “, dif, “ years older than I am.”
display “Well goodbye now” display “My name is Proogy”
STOP

display “How old are you?”

read age

display “I am 5 years old”

dif  age - 5

display “You are “, dif, “ years older than me”

STOP
display “Well, goodbye now”

[39]
Computer Science Unit 1 Module 2

8.5 Design a program to determine someone’s phone bill amount. The flat rate is $850.00. It costs
$20.00 per minute for local calls and $60.00 per minute for long distance calls.

Solution

Pseudocode : PhoneBill
// Calculate an individual’s phone bill based on their fixed rental charge and the number of calls they make.

DECLARATIONS
Constants
localrate = 20.00
farrate = 60.00
flatamount = 850.00

Variables
localmins, farmins, localbill,
farbill, total – data type real

PROCESS
//get data
display “How many minutes were spent on local calls?”
read localmins
display “How many minutes were spent on long distance calls?”
read farmins

//calculate bill amount


localbill  localmins * localrate
farbill  farmins * farrate

total  flatamount + localbill + farbill

//display bill total


display “Amount due $”, total
STOP

Flowchart : PhoneBill

START

display “How many minutes were spent on local calls?”

[40]
C-A. Jardette

read localmins

display “And how long on long distance calls?”

read farmins

localbill  localmins * 20.00

farbill  farmins * 60.00

bill  850.00 + localbill + farbill

display “Amount due: $”, bill

STOP

[41]
Computer Science Unit 1 Module 2

8.6 Design a program to accept 2 integers val1 and val2, switch them and display val1
followed by val2.

Solution

Pseudocode : Switchy
// this program switches the values in 2 variables

DECLARATIONS
variables
val1, val2, temp – data type integer

PROCESS
//get the input data
display “Enter 2 numbers and I will switch them for you”
read val1, val2

// switch the numbers using a third variable as temporary storage


temp  val1
val1  val2
val2  temp

//display the variables again


display val1, val2
STOP

Flowchart : SwitchValues

START

display “Enter 2 numbers, I will switch them”

read val1, val2

[42]
C-A. Jardette

temp  val1

val1  val2

val2  temp

display val1, val2

STOP

8.7 Design a program that calculates the commission due to an athlete’s coach when that athlete
competes at track meets. The coach gets 5% of the athlete’s earnings. Athletes who place first
earn $70,000, 2nd place garners $40,000 and 3rd place finishers get $15,000.

Solution

Pseudocode : Runrun
// this program calculates how much money is due to an athlete’s coach based on the athlete’s performance

DECLARATIONS
Constants
rate1 = 70000.00
rate2 = 40000.00
rate3 = 15000.00
crate = 0.05
Variables
first, second, third, commission, total – data type real

[43]
Computer Science Unit 1 Module 2

PROCESS
//get input data
display “How many races did the athlete win?”
read first
display “In how many races did he/she come second?”
read second
display “In how many races did he/she come third?”
read third

//compute total earnings


total  (first * rate1) + (second * rate2) + (third * rate3)

//compute commission
comision  total * crate

//display results
display ‘The coach is due to get $”, commission
STOP

Flowchart : Athlete
START

display “How many races did the athlete win?”

read first

display “How many 2nd places?”

read second

[44]
C-A. Jardette

display “How many 3rd places?”

read third

total  (first * 70000.00) + (second * 40000.00 ) + ( third * 15000.00)

comision  total * 0.05

display “Coach’s commission : $“, comision

STOP

[45]
Computer Science Unit 1 Module 2

SOME GUIDELINES FOR WRITING/DRAWING ALGORITHMS

8.8 PSEUDOCODE
- Give an appropriate name to your pseudocode, this name can later serve as the name of the
program
- Always write a global comment explaining the overall intent of the algorithm at the top;
include the date and your name as the author in the global comment
- Give a list of any constants that you plan to use in your program
- Give a list also of all variables to be used and indicate their data type
- Always use START and STOP to show the beginning and end of the executable statements
- As the algorithms get longer and more complex, use local comments to describe what each
sub-section does
- Be sure to include prompts to the user when necessary
- A prompt must always be followed by a read operation, that is how the data actually gets
into the program variable
- Reading of input can be done item by item or several items together depending on the
nature of the items e.g. 3 statements - read num1
read num2
read num3
or 1 statement - read num1, num2, num3
- Output can be a combination of literals and variables e.g. display ‘the answer is “, result
 ‘the answer is’ is literally what you want to show on the screen
 result is the name of a variable and you want the content of the variable to be
displayed. If you include a variable name in quotation marks you will get the
actual word displayed and not the value.
 the different phrases form a list so they must be separated by a comma
- There are no restrictions on the number or types of statements you may use in your
solution
- Nesting of constructs is often necessary

8.9 FLOWCHARTS
- Give your flowchart a name
- Always include two terminator symbols, one for START, and one for STOP
- Remember that input and output use the same symbol, be sure that the label clarifies which
is which
- All paths should lead to the final terminator symbol
- Avoid having flow lines cross each other

[46]
C-A. Jardette

PRACTICE EXERCISE 4

1. Write the pseudocode for a program to determine and display how much weight the
second floor of a building can bear if each square metre can hold 350 Kg.

2. Complete the flowchart for a program that gives the fuel consumption of a car given the
amount of gas used and the distance travelled.

START

[47]
Computer Science Unit 1 Module 2

3. Write the pseudocode for a program to determine and display the earnings for a theatre
for one evening. The theatre has 2 types of seats – gallery seats and house seats. It
charges children $500 each to sit in a house seat and $700 to sit in the gallery. Adults
pay $900 for a house seat and $1,300 to sit in the gallery.

[48]
C-A. Jardette

4. Draw the flowchart for a program that reads 5 marks earned by a student in one term
and displays the student’s term average. The 5 marks represent 4 assignments and 1
test. Note that the assignments are worth 60% of the term average and the test is worth
40% of the term average.

[49]
Computer Science Unit 1 Module 2

9. SELECTION ALGORITHMS

9.1
There are three forms of selection, the first two are:

IF (conditional expression) THEN IF (conditional expression) THEN


statement(s) statement(s)
ENDIF ELSE
statement(s)
ENDIF

Conditional expressions include one or more relational operators. The possibilities are:
Relational Operator Meaning
= is equal to
<> is not equal to
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to

Conditional expressions may be simple expressions or compound expressions. Compound


conditionals use the Boolean operators AND, OR and NOT as connectors. It is recommended
that you use brackets to clarify meanings and precedence.

The third form of selection is called the CASE construct and is used when there are many
possible paths and the IF-THEN-ELSE construct would become too large, cumbersome and
difficult to follow.

CASE variable_name OF
value1 - statement(s)
value2 - statement(s)
value3 - statement(s)
OTHERS - statement(s) optional
ENDCASE

The case construct indicates mutually exclusive multi-way branching and is used for
comparing a variable of an ordinal data type to a series of exact values, or ranges.

[50]
C-A. Jardette

If Statements - Here are some examples of selection algorithms

9.2 Design a program that determines what to do if it rains


Solution

Pseudocode : Rainrain
DECLARATIONS
Variables
weather – data type string
PROCESS
display “What is the weather today?” Flowchart : Rainrain
read weather
START
if (weather = “rainy”) then
display “Stay home”
endif
STOP display “What is the weather today?”

read weather

weather = “rainy”
N
Y

display “Stay home”

STOP

[51]
Computer Science Unit 1 Module 2

9.3 Design a program to determine how much entrance fee a cinema patron should pay

Solution

Pseudocode : EntranceFee
//Determines how much entrance fee a cinema patron should pay

DECLARATIONS
Constants
adultfee = 600.00
kidfee = 300.00
Variables
choice – data type character

PROCESS
// get data
display “Are you an adult or a child?”
display “Enter ‘A’ or ‘C’ "
read choice

// make decision
if (choice = ‘C’) or (choice = ‘c’) then
display “You pay $”, kidfee
else
display “You pay $”, adultfee
endif
STOP

Flowchart : EntranceFee
START

display “Choose ‘A’ for adult or ‘C’ for child”

read choice

Y (choice = ‘C’) or N
A B
(choice = ‘c’) ?

[52]
C-A. Jardette

A B

display “You pay $300.00"

display “You pay $600.00 "

STOP

9.4 Design a program that determines if interest in due on a bank account, and if it is, calculates the
new balance in the account. Accounts that have an opening balance of $18,000 or more get a 6%
interest.

Solution

Pseudocode : BankInterest
//Determines an account new balance

DECLARATIONS
Constants
trigger = 18000
irate = 6%
Variables
balance, interest, newbalance – data type real

PROCESS
// get balance
display “Enter the account balance”
read balance

//initialize the new balance


newbalance  balance

[53]
Computer Science Unit 1 Module 2

// determine the new balance with interest for applicable accounts


if (balance >= trigger) then
newbalance  balance + (balance * irate)
endif

//show new balance


display "The new balance is $", newbalance
STOP

Flowchart : Interest

START

display “Enter the present balance”

read balance

newbalance  balance

balance >= 18000 ?


Y N

newbalance  balance + (balance * 0.06)

display “The new balance is $”, newbalance

STOP

[54]
C-A. Jardette

9.5 Design a program that identifies the largest of 3 given numbers.

Solution

Pseudocode : Large3
//Find the largest of 3 numbers

DECLARATIONS
Variables
num1, num2, num3, largest – data type real

PROCESS
// get the numbers
display “Enter three different numbers”
read num1, num2, num3
display ‘Now I will tell you which is largest”

// determine largest
if (num1 > num2) and (num1 > num3) then
largest  num1
else
if (num2 > num3) and (num2 > num1) then
largest  num2
else
largest  num3
endif
endif

display “The largest of the 3 is ”, largest


STOP

Flowchart: Greaterthan
START

display “Enter 3 numbers”

read num1, num2, num3

(num1 > num2)


Y N
A and B
(num1 > num3) ?

[55]
Computer Science Unit 1 Module 2

(num2 > num1)


and
(num2 > num3)
Y ? N

largest  num3
largest  num2

largest  num1

display largest

STOP

[56]
C-A. Jardette

9.6 Design a program that determines the tax rate (based on number of dependents) and earnings for
an employee.

Solution

Pseudocode : TaxAndPay
//Find the salary

DECLARATIONS
Constants
tax1 = 0.25
tax2 = 0.2
limit = 2
Variables
status – data type character
kids, depend – data type integer
earn, salary – data type real

PROCESS
//get data
display "Are you married or single, M or S?"
read status
display "How many children do you have?"
read kids
display "How much do you earn each month?"
read earn

// if the employee is married then 1st dependent is spouse


if (status = ‘M’) then
depend  kids + 1
else
depend  kids
endif

if (depend > limit) then


display “Your tax rate is ”, tax2
salary  earn – (earn * tax2)
else
display “Your tax rate is ”, tax1
salary  earn – (earn * tax1)
endif

display “Your net earnings is $”, salary


STOP

[57]
Computer Science Unit 1 Module 2

Flowchart : TaxAndPay

START

display “Are you married (Y/N)?”

read status

display “How many children do you have?”

read numkids

display “How much do you earn each month?”

read money

status = ‘S’ or status = ‘s’?


N Y

depend  kids + 1 depend  kids

[58]
C-A. Jardette

depend > 2?
N Y

display “Tax rate: “, 0.2 display “Tax rate: “, 0.25

salary  earn – (earn * 0.2) salary  earn – (earn * 0.25)

display “Net salary $”, salary

STOP

9.7 Design a program that determines the toll amount payable by a vehicle using a toll road in Jamaica.
Sedans pay $$300, SUVs pay $400, buses pay $500 and trucks pay $650.

Solution

Pseudocode : TollRate
//Find the toll amount

DECLARATIONS
Constants
rate1 = 300
rate2 = 400
rate3 = 500
rate4 = 650

[59]
Computer Science Unit 1 Module 2

Variables
cartype - data type character

PROCESS
// present a menu to the user
display “Good morning”
display “C – sedan”
display “S – SUV”
display “B – bus”
display “T – truck”
display “Choose C, S, B or T for your vehicle type”
read cartype

if (cartype = ‘C’) then


display “Pay $”, rate1
else
if (cartype = ‘S’) then
display “Pay $”, rate2
else
if (cartype = ‘B’) then
display “Pay $”, rate3
else
display “Pay $”, rate4
endif
endif
endif
STOP

Flowchart : TollToll

START

display “Good morning”

display “C – car, S – SUV, B – bus, T - truck”

[60]
C-A. Jardette

read cartype

N cartype = ‘C’ ? Y

cartype = ‘S’ ?
N
display “Toll : $300.00”
Y

display “Toll : $400.00” B

cartype = ‘B’ ?
B Y N

display “Toll : $500.00” display “Toll : $650.00”

STOP

[61]
Computer Science Unit 1 Module 2

PRACTICE EXERCISE 5

1. Draw the flowchart for a program that accepts a gender and then says “Hello girl” or
“Hello boy”.

2. Write the pseudocode for a program that determines if the temperature of the lab is in
an appropriate range. It reads the temperature; if it is below 20 degrees then it is too
cold, if it above 25 degrees then it is too hot.

[62]
C-A. Jardette

3. Draw a flowchart for a program that calculates a student’s weekly lunch money based
on the following rule: students under 15 years of age get $25.00 times their age per
day; students 15 years and older get $35.00 times their age per day.

[63]
Computer Science Unit 1 Module 2

4. Create the algorithm for a program that calculates and displays the salary for December
for an employee. The employee has a flat monthly salary. An end of year bonus of
$5000 is added to the December salary if the employee was absent from work for less
than 5 days in the year. If the total salary (flat plus bonus) is more than $100,000 the
employee has to pay a tax of 2.5%

[64]
C-A. Jardette

[65]
Computer Science Unit 1 Module 2

9.8 The CASE Construct

CASE is a special type of selection. It indicates multi-way branching based on conditions that
are mutually exclusive. Four keywords, CASE, OF, OTHERS/OTHERWISE, and ENDCASE,
and various possible values are usually used to indicate the options.

The general form is:

CASE expression OF
condition 1 - sequence 1
condition 2 - sequence 2
...
condition n - sequence n
OTHERWISE - default sequence // this is optional
ENDCASE

Expression indicates a variable. Because of restrictions in some programming languages case


should only be used with ordinal values, i.e. the data types integer or character.
Conditions are therefore numbers or characters indicating the value of the variable.

Example 1 CASE option OF


1 - Print "Mr"
2 - Print "Missus"
3 - Print "Miss"
4 - Print "Mizz"
5 - Print "Doctor"
ENDCASE

Example 2 CASE grade OF


A - points  4
B - points  3
C - points  2
OTHERS - points  0
ENDCASE

Example 3 Case age of


0 to 17 - Display "You can't vote."
18 to 64 - Display "You're in your working years."
greater than 65 - Display "You should be retired."
Endcase

[66]
C-A. Jardette

CASE is normally only used when there are lots of nested IFs which makes for cumbersome
code. The statements to be executed can be any simple or compound programming statement
including a function call.

Example 4
If (mark < 35) then
grade  'E'
else if (mark < 50) then
grade  'D'
else if (mark < 65) then
grade  'C'
else if (mark < 80) then
grade  'B'
else
grade  'A'
display "Congratulations"
endif
endif
endif
endif

This can be restated more compactly as


Case mark of
0 to 35 - grade  'E'
36 to 49 - grade  'D'
50 to 64 - grade  'C'
65 to 79 - grade  'B'
80 to 100 - grade  'A'
display "Congratulations"
endcase

Case Statements - Here are some examples of selection algorithms which use CASE statements

9.9 Design a program to display the capital of a parish assuming that each parish has a number

Solution

Pseudocode: ParishCapitals
// Program to print the capital of a parish assuming that each parish has a number

DECLARATIONS
Variables
parish – data type integer

[67]
Computer Science Unit 1 Module 2

PROCESS
// Get parish number
display “Kingston –1
St. Andrew –2
St. Thomas –3
St. Ann –4
Hanover –5
Westmoreland –6
display “Choose a parish”
read parish

// Assess choice and display the appropriate capital


case parish of
1 - display “Kingston”
display “Yes, Kingston is a parish, a parish capital and a city”
2 - display “Half-Way-Tree”
display “It’s supposed to be half way from Constant Spring to Town”
3 - display “Morant Bay”
4 - display “St. Anns Bay”
5 - display “Lucea”
6 - display “Savanna-la-mar”
7 - display “Black River”
Otherwise - display “I’m sorry I don’t know those parishes”
endcase
STOP

Flowchart: ParishCaps
START

Display “Kingston –1
St. Andrew –2
St. Thomas –3
St. Ann –4
Hanover – 5”

[68]
C-A. Jardette

display “Choose one”

read parishnum

parishnum?

=1 =2 =3 =4 =5 otherwise

display display “Morant


“Kingston” Bay” display “Lucea”

display “Half-Way- A
A
Tree”

display “St. Anns Bay”


display “Yes, it’s
a city too” display “Wrong
choice”

A display “Half way between up


and down town”

STOP

[69]
Computer Science Unit 1 Module 2

9.10 Design a program to display the season that a particular month falls into
Solution

Pseudocode: MonthSeason

DECLARATIONS
Variables
monthnum – data type integer

PROCESS
display “Enter an integer between 1 and 12 indicating a month”
read monthnum
case monthnum of
3, 4, 5 - display “Spring”
6, 7, 8 - display “Summer”
9, 10, 11 - display “Autumn”
12, 1, 2 - display “Winter”
otherwise - display “The valid options are 1 to 12”
endcase
STOP

Flowchart: Seasons
START

display “Enter an integer between 1 and 12 indicating a month”

read monthum

monthnum?

3,4,5 6,7,8 9,10,11 12,1,2

Display Display Display Display


“Spring” “Summer” “Autumn” “Winter”

STOP

[70]
C-A. Jardette

PRACTICE EXERCISE 6

1. Redo Example 9.7 on page 53 using the case construct

[71]
Computer Science Unit 1 Module 2

WORKSHEET 2 - SEQUENTIAL AND SELECTION ALGORITHMS

Practice creating algorithms by designing :


1. A program that does currency conversion for the user. It should convert from $US to $JA
at the rate of J$132.00 to US$1.00.

2. A program that calculates how much electricity a householder uses in total for her air
conditioning units for one month. She has two a/c units in her home and each one uses
3KW for each hour that it operates.

3. A program to calculate your lunch money for the school week (5 days). The rule is that for
each day you get $20 times your age.

4. A program that accepts two numbers and finds and displays their product if they are both
greater than 10.

5. A program that determines if a student can attend St Andrew High School. The
requirement is that the student be 11 years or older and female.

6. A program for the Gartshore House Competition. Given the name and number of points
earned by two houses, this program will determine and display which of those two houses
won the competition.

7. A program that accept the weight of a person and if that person weights more than 240lbs
asks the person for their age. If the age is less than 21 tell the user that they are way too
young to be so fat; otherwise give a mild warning.

8. A program that takes in 3 marks for a student and finds the average. The program should
then use the following criteria to say what grade the student got.
A 100 - 85 B 84 - 65
C 64 - 55 D 54 - 45
E below 45

9. A program that acts as a simple calculator. This program takes in an operator. Then
depending on the operator it asks for the specific operands, performs the operation and
gives the result. The valid operators are + - / and * . Two operands are sufficient.

10. A program to calculate the salary for a salesman. Salesmen get a flat salary and then to that
is added commission. The commission is calculated as follows
if they made sales of between $0 and $5000 they get 2% of the sales value in commission
if they made sales of over $5000 but below $10001 they get 5% of the sales value in
commission
if they made sales of $10001 or over they get 10% of the sales value in commission

[72]
C-A. Jardette

10 ITERATION

10.1
Iteration (the same thing as looping) is executing a set of program statements over and over
again until a particular condition is met. Loops can be classified as bounded/definite or
unbounded/indefinite.

Unbounded loops are necessary when one does not know before hand exactly how many
times the set of statements (loop) is to be repeated. However,2 there still must be a point when
the loop ends. This is determined by a condition being evaluated each time before the loop is
to be executed. This condition contains a sentinel value – i.e. the value that determines when
the loop ends. Unbounded loops are thus said to be sentinel controlled.

Unbounded loop conditional expressions are similar to the conditions in IF statements. E.g. of
loop conditional expressions num = 99 count <= 50 name < > “End”
answer = ‘Y’ value < limit choice < > endoption

Num, count, name, answer, value and choice are all variables. Limit and endoption may be
variables or constants. “End”, 99, 50, ‘Y’ and the values in limit and endoption are the
sentinel values.

10.2 WHILE Loops


The most common type of unbounded loop is the while loop. In a while loop, whether or not
the loop iterates depends on the value in a particular variable called the controlling variable.
Note -
1. The controlling variable MUST have a value before the loop begins
2. There MUST be either a read statement or an assignment statement somewhere
inside the loop that changes the value of the controlling variable. This
statement is normally near to the end of the loop.

WHILE loops :
WHILE (conditional_expression) DO
statement1
statement2
|
|
ENDWHILE

2 Without a sentinel the loop will run forever. Loops that do not end are called infinite loops

[73]
Computer Science Unit 1 Module 2

The statements between WHILE and ENDWHILE are the ones which will be repeated as long
as the condition remains true and they are called the body of the loop. These may be assignment
statements, input statements, output statements, if statements or even other loops. When the
condition becomes false the loop will end and execution of the program continues with the
statement immediately after endwhile.

Here are some designs that show the use of the WHILE construct

10.3 Design a program that displays the first 30 integers

Solution

Pseudocode : Show30 Flowchart : Show30


// displays the first 30 numbers

DECLARATIONS START
VARIABLE
digit – data type integer

PROCESS
digit  1 digit  1
while (digit <= 30) do
display digit
digit  digit + 1
endwhile
STOP

digit <= 30 ?
N

Y
Note that the dotted box
is only there to show the loop
display digit

digit  digit + 1

STOP

[74]
C-A. Jardette

10.4 Design a game in which the user tries to guess a number

Solution

Pseudocode : GuessingGame
// The user tries to guess the computer’s number

DECLARATIONS
Constants
answer = 21
Variables
guess – data type integer

PROCESS
display “I have an integer in mind, guess what it is”
read guess

while (guess < > answer) do


display “Guess again”
read guess
endwhile

display “Congrats, that’s it”


STOP //note that this will run forever if the user never guesses 21

Flowchart: GuessingGame
START

display “Guess which number I’m thinking of”

read guess

Y
guess = 21 ?

N
display “Congrats,
that’s it”
display “Guess again”

STOP
read guess

[75]
Computer Science Unit 1 Module 2

10.5 Design a program that accepts a mark for a series of students and determines if each mark is a
failing mark or not, given that to pass a student must get more than 55%.

Solution

Pseudocode : FailorPass
// Determine if a class of students failed or passed

DECLARATIONS
Constant
passmark = 55.0
Variables
mark – data type real

PROCESS
// Get the data
display “Enter the first student’s mark”
read mark

// check the marks


While (mark > 0) do
if (mark > passmark) then
display “This student passed”
else
display “This student failed”
endif

// get another mark


display “Enter another mark, a negative mark will end the processing”
read mark
endwhile
STOP

Flowchart: PassorFail
START

display “Enter the first mark”

read mark

[76]
C-A. Jardette

mark > 0 ?
N
Y

mark > 55.0 ?

N Y

display “‘That student display “That student


failed” passed”

display “Enter another mark”

read mark

STOP

10.6 Design a program that finds the sum of a set of numbers. This program should be able to add
any amount of numbers; the list is terminated by 9999.

Solution

Pseudocode : Accumulating
// Keep adding all the numbers supplied until 9999 is entered

DECLARATIONS
Variables
numb, total – data type real

[77]
Computer Science Unit 1 Module 2

PROOCESS
// initialize numbers
total  0

display “Enter a number, type 9999 to end”


read numb

while (numb <> 9999) do


total  total + numb
display “Enter another number, type 9999 to end”
read numb
endwhile

display “The total is ”, total


STOP

Flowchart : Accumulating
START

total  0

display “enter a number, 9999 to end”

read numb

numb = 9999 ?
Y

N
A
total  total + numb

display “enter another number, 9999 to end”

read numb

[78]
C-A. Jardette

display “The total is ”, total

STOP

10.7 Design a program that checks each number entered and decides whether it is even or odd. The
program stops when a 0 is entered after displaying how many odd and even numbers were entered.

Solution

Pseudocode : CheckSign
// Determine if a number is positive and count the occurrences of each type

DECLARATIONS
Variables
number – data type real
postotal, negtotal - data type integer

PROCESS
postotal  0
negtotal  0
display “Enter a number, type 0 to end”
read number

while (number < > 0) do


if number > 0 then
display number, " is positive"
postotal  postotal + 1
else
display number, " is negative"
negtotal  negtotal + 1
endif

display "Enter another number, type 0 to end"


read number
endwhile

display “There were ”, postotal, “ positive numbers and ”, negtotal, “ negative numbers”
STOP

[79]
Computer Science Unit 1 Module 2

Flowchart : CheckSign
START

postotal  0
negtotal  0

display ‘Enter a number’

read number

number = 0 ?
Y
N

number > 0 ?
N Y

negtotal  negtotal + 1 postotal  postotal + 1

display “That number display “That number


is negative” is positive”

display “Enter another number, type 0


to end

read number

display “There were ”, postotal , “ positive numbers


and ”, negtotal , “ negative numbers”

STOP

[80]
C-A. Jardette

10.8 Design a program that calculates a customer’s bill.

Solution

Pseudocode : Purchases
// Find bill amount

DECLARATIONS
Constants
taxrate = 0.2 // 20% tax
Variables
response – data type character
itemcost, totalcost, grosscost – data type real
itemquantity – data type integer

PROCESS
// initialize variables
totalcost  0.0
response  ‘Y’

while (response = ‘Y’) do


display “What is the cost of the item?”
read itemcost
display “How many do you want to buy?”
read itemquantity
totalcost  (itemcost * itemquantity) + totalcost

// are there more items?


display “Do you want to buy more items (Y/N)?”
read response
endwhile

grosscost  totalcost + (totalcost * taxrate)


display “Your total bill is $”, grosscost
STOP

Flowchart : Purchases
START

totalcost  0.00
response  ‘Y’

A response = ‘Y’ ?
N

[81]
Computer Science Unit 1 Module 2

display “How much for the item?”

read itemcost

display “How many?”

read itemquantity

totalcost  totalcost + (itemquantity * itemcost)

display “Do you want to buy again?”

read response C

A grosstotal  totalcost + (totalcost * 0.2)

display “Your total cost is $”, grosstotal

STOP

[82]
C-A. Jardette

PRACTICE EXERCISE 7

1. Write the pseudocode for a program that repeatedly asks the user for a first name and then
greet the person by name. The program should end when the user enters “End”.

[83]
Computer Science Unit 1 Module 2

2. Write the pseudocode for a program that performs addition for the user. The program
should offer to add 2 numbers and continue to add the supplied pairs of numbers and
display their total as long as the user wishes.

[84]
C-A. Jardette

3. Draw a flowchart for a program that finds and displays the toll amount payable for a series
of vehicles passing through a toll booth. Cars pay $300.00, SUVs pay $400.00, buses pay
$500.00 and trucks pay $650.00.

[85]
Computer Science Unit 1 Module 2

4. Draw the flowchart for a program that, given the mark for each child in a class, finds and
displays that student’s letter grade. It also displays the average for the class at the end.
Note that valid marks are between 0 and 100 inclusive and the program should end if
given a mark outside of that range.

[86]
C-A. Jardette

10.9 Repeat .. Until Loops


This is another type of unbounded loop. In a while loop the conditional expression is first
tested and depending on the result the body of the loop may or may not be executed. Because
of this approach, it is called a pretest loop. In the REPEAT .. UNTIL loop however, the body
of the loop is executed once, then the conditional expression is checked. The truth value of the
condition determines if the loop is done again or not.

The REPEAT UNTIL loop is different therefore, from the WHILE loop in that :
a. the condition / criterion / check comes at the bottom not the top of the loop
b. the loop runs as long as the condition is false and stops when the condition
becomes true
Note that the condition in the repeat loop therefore needs to be the opposite of the condition
in a while loop.

The structure of the REPEAT .. UNTIL loop :

REPEAT
statement1
statement2
|
|
UNTIL (conditional expression)

The statements between ‘repeat’ and ‘until’ form the body of the loop and no end statement is
necessary. A priming read may or may not be necessary. The repeat until loop is known as a
post test loop. As a consequence of the repeat loop being a post test loop i.e. testing after
execution, the repeat loop will always run at least once.

This loop is the best one to use when you wish to force the user to make a choice from a set of
predefined options.

Here are some examples of repeat .. until loop algorithms

[87]
Computer Science Unit 1 Module 2

10.10 Design a program to play a guess the number game

Solution

Pseudocode : GuessingGame
// The user tries to guess the computer’s number

DECLARATIONS
Constants
answer = 21
Variables
guess – data type integer

PROCESS
repeat
display “I have an integer in mind, guess what it is”
read guess
until (guess = answer)

display “Congrats, that’s it”


STOP

Flowchart : GuessingGame
START

display “Guess which number I’m thinking of”

read guess

guess = 21 ? N

display “‘congrats”

// Once again the dotted line is


STOP // only there to illustrate the
// loop

[88]
C-A. Jardette

10.11 Design a program that adds pairs of numbers for as long as the user desires.

Solution

Pseudocode : KeepAdding
// A program that adds pairs of numbers

DECLARATIONS
Variables
num1, num2 - data type real
continue – data type character
sum – data type real

PROCESS
repeat
display “Give me the 2 numbers”
read num1, num2
sum  num1 + num2
display “The answer is ”, sum

display “Do you want me to add again(Y/N)?”


read continue
until (continue <> ‘Y’)

display “Goodbye”
STOP

Pseudocode : KeepAdding
START

display “Type the 2 numbers”

read num1, num2

sum  num1 + num2

display “The answer is ”, sum

[89]
Computer Science Unit 1 Module 2

display “Add again?”

read continue

continue = ‘Y’? B
Y

display “Good bye”

STOP

10.12 Design a program that determines the toll for a set of vehicles passing through a toll booth.

Solution

Pseudocode : Tollagain
// program to determine the toll rate for a set of cars

DECLARATIONS
Constants
rate1 = 250.00
rate2 = 380.00
rate3 = 500.00
Variables
vehicletype, answer – data type character

PROCESS
// show the menu
display “C - car, B - bus, T - truck”

repeat
display “What type of vehicle is it (C/B/T/)?”
read vehicletype

[90]
C-A. Jardette

if (vehicletype = ‘C’) then


display “Toll = $”, rate1
else
if (vehicletype = ‘B’) then
display “Toll = $”, rate2
else
if (vehicletype = ‘T’) then
display “Toll = $”, rate3
else
display “Unrecognisable vehicle”
endif
endif
endif

display “Do you want to process another vehicle(Y/N)?”


read answer
until ((answer <> ‘Y’) and (answer <> ‘y’))

display “Have a good day”


STOP

Flowchart : Tollagain
START

display “C is for car, B is for bus and T is for truck”

display “‘What type of vehicle is it?”

read vehicletype

vehicletype = ‘C’ ?
N Y

display “Toll = $250.00”


vehicletype = ‘B’ ?
N Y

A B C

[91]
Computer Science Unit 1 Module 2

vehicletype = ‘T’
N Y

display “Unrecognizable
vehicle”

display “Toll = $500.00”

B
E

display “Toll = $380.00”

display “Do you want to process


another vehicle?”

E C

read answer

answer = ‘Y’? D
Y

display “Have a good day “


STOP

[92]
C-A. Jardette

10.13 Design a program that counts to a user determined value.

Solution

Pseudocode : Count
// counts to a user inputted limit

DECLARATIONS
Variables
stop, count – data type integer

PROCESS
display “I can count from 1, tell me where to stop”
read stop

// initialize counter
count  1

repeat
display count
count  count + 1
until (count > stop)
STOP

Flowchart : County
START

display “Where should I stop counting?”

read limit

count  1

display count

count  count + 1

Y count > limit ? N


STOP

[93]
Computer Science Unit 1 Module 2

10.14 Design a program that displays a menu and forces the user to make a valid choice.

Solution

Pseudocode : Choose
// forces the user to choose

DECLARATIONS
Variables
option – data type character

PROCESS
repeat
display “What is your primary favourite colour – red (R), blue (B), or yellow (Y)?”
read option
until (option = ‘R’) or (option = ‘B’) or (option = ‘Y’)
display “Good choice “, option , “ is a beautiful colour.”
STOP

Flowchart : Choose
START

display “What is your favourite primary colour – red


(R), blue (B) or yellow (Y)?”

read option

(option = ‘R’) or (option = ‘B’) or


(option = ‘Y’) ?
N

display “Good choice ”, option , “


is a beautiful colour.”

STOP

[94]
C-A. Jardette

PRACTICE EXERCISE 8

1. Draw the flowchart for a program that determines if students in a class have passed or
failed an assignment.

[95]
Computer Science Unit 1 Module 2

2. Create the algorithm for a program that determines a passenger’s bus fare based on
the following criteria. Passengers are to be given a menu with the following age ranges
from which they will choose one. 0 to 2 years; 3 to 12 years; 13 to 59 years and 60 years
and older. They are also required to indicate their gender from a menu. The fares for
females are : 3 to 12 years - $50.00; 13 to 59 years - $150.00. Women age 60 and over
pay 75% of the adult fare. All male fares are 120% of the female fares. Note that all
babies (0 to 2) travel free.

[96]
C-A. Jardette

WORKSHEET 3 - UNBOUNDED LOOPS

Use the following situations to practice creating pseudocode and/or flowchart algorithms
which include WHILE loops :

1. A program which determines the average rainfall over a number of days given the
rainfall for each day. The data is terminated by 9999.

2. A program which determines the average number of passengers and the average
earnings per day for a bus which charges $90.00 per passenger. The input will be the
number of passengers for each day. The end of input will be indicated by a 0.

3. A program which reads the population and the name of some Caribbean countries
terminated by 0 for population. It then determines which country has the highest
population, and also display the level of the highest population.

4. A program which displays the lunch menu for the day. The cafeteria only offers three
(3) dishes. Chicken dish is $340.00, the Beef dish is $456.78 and the Fish dish is $505.05.
The program should accept a single order from each customer. The order is
acknowledged (e.g. “You ordered beef. Please pay the cashier $300.00”) and the menu
is displayed again. The program ends when the user chooses quit from the menu.

Use the following situations to practice creating pseudocode and/or flowchart algorithms
which include REPEAT .. UNTIL loops :

5. A program which reads the scores for a set of cricketers with a score of 1000 indicating
no more scores. It then determines how many players scored a century (100 or more)
and how many made duck (a score of 0).

6. A program which reads the names and cost of a set of items and prints a bill for the
customer. The bill should show the name and cost of each item and at the bottom, it
should show the total cost including tax of 15%. The end of input is indicated by an
item named END or a cost of $0.00 ( you decide).

[97]
Computer Science Unit 1 Module 2

7. A program which does subtraction for a user while testing the user’s responses. The
program should ask for numbers in pairs. It should determine which of the pair is
larger and then subtract the smaller from it. Having determined the answer it should
ask the user to guess the answer and tell the user if he/she is right or not. If the user is
wrong the program should display the correct answer. The program ends if either of
the numbers in a pair is zero.

8. A program which displays the lunch menu for the day. The cafeteria only offers three
(3) dishes. Chicken dish is $340.00, the Beef dish is $456.78 and the Fish dish is $505.05.
The program should accept a single order from each customer. The order is
acknowledged
(e.g. “You ordered beef. Please pay the cashier $300.00”) and the menu is displayed
again. The program ends when the user chooses quit from the menu.

Challenge yourself – devise the pseudocode for the following – you may use while, repeat or
both:
9. Design a program that given a whole number (x), finds and displays half of the
number (y) and then half of that number until y becomes a real number. It should then
display the smallest integer y value found

[98]
C-A. Jardette

10.15 FOR Loops


We have been looking at unbounded loops so far. There are situations however, in which we
can tell beforehand how many times a loop will run. In those circumstances it is more
appropriate to use a bounded loop. The number of iterations to be performed may be an
explicit value/a constant, or it may be a value in a variable. As long as the value is available
before the loop begins the bounded loop structure can be used. Bounded loops are also called
definite loops.

The FOR loop is a bounded loop and it is also a pretest loop. It is pretest because the
evaluation of the loop condition takes place at the start of the loop before the body is
executed.

In order to correctly use a FOR loop -


We must designate where it is to start
We must designate where it is to stop
We must designate a particular variable to act as the counter
We say by how much the counter is to be increased (or decreased) after each iteration.

The structure of the FOR loop :


FOR counting_variable  beginning_value TO end_value STEP increment DO
|
|
ENDFOR

Note :
 if we are going to count up, beginning_value needs to be less than end_value
 if we are counting down, beginning_value needs to be greater than end_value
and we use DOWNTO instead of TO
The STEP clause is optional, if it is omitted it means that the controlling
variable is to be incremented by 1 after each iteration
 the controlling variable does not have to start at the value 1, and can increase
by any value the programmer desires.

How the FOR loop works


The counting variable is first set to the beginning value and the body of the loop is executed.
The counting variable is next increased/decreased by the step value and the body of the loop
executed again. This continues until the counting variable becomes the end value. The loop is
done one last time and then it ends.

[99]
Computer Science Unit 1 Module 2

The statements between FOR and ENDFOR are the ones which will be repeated until the end
value is reached. These may be assignment statements, input statements, output statements, if
statements or even other loops. When the number of iterations is finished, execution of the
program continues with the statement immediately after endfor.

10.16
There is no simple straightforward symbol for the FOR loops in flowcharting. What is
important is that you understand that the FOR .. DO statement is actually 3 statements in 1.
That is to say:
count  2
for count  2 to 10 step 1 do  while count <= 10 do ….
count  count + 1

loopy  1
for loopy  1 to 16 step 2 do  while loopy <= 16 do ….
loopy  loopy + 2

To draw the flowchart for a FOR loop all three statements would have to be represented. The
FOR loop’s flowchart therefore resembles that of a while loop or more often a repeat .. until
loop.

Here are some examples of for loop algorithms

10.17 Design a program to display the first 30 integers starting at 1

Solution

Pseudocode : Show30
// displays the first 30 numbers

DECLARATIONS
Constants
max = 30
Variables
digit – data type integer

PROCESS
FOR digit  1 TO max STEP 1 DO
display digit
ENDFOR
STOP

[100]
C-A. Jardette

Flowchart : Show30

START

digit  1

display digit

digit  digit + 1

digit < 30
Y

STOP

10.18 Design a program to greet all the students in the class when they come into the room.

Solution

Pseudocode : GreetAll
// Greet all the students

DECLARATIONS
Variables
count, maxstudents – data type integer
name – data type string

PROCESS
display "How many students are there in the class?"
read maxstudents

FOR count  1 TO maxstudents STEP 1 DO


display "What is your name?"
read name
display "Good morning ", name
ENDFOR
STOP

[101]
Computer Science Unit 1 Module 2

Flowchart : GreetAll

START

display “How many students are there


in the class?”

read max

count  1

display “What is your name?”

read name

display “Hello ”, name

count  count + 1

count < max


Y

STOP

[102]
C-A. Jardette

10.19 Design a program to find the sum, average and largest of a set of numbers. Assume that they are
all positive.

Solution

Pseudocode : SomeNumbers
// Process some numbers

DECLARATIONS
Variables
limit – data type integer
num, total, average, largest – data type real

PROCESS
// initialization
total  0
largest  0
average  0

display “How many numbers do you have?”


read limit
for count  0 to limit step 1 do
display “Enter one number”
read num
total  total + num
if (num > largest) then
largest  num
endif
endfor

if (limit < > 0) then


average  total / limit
endif

// Display results
display “The sum of these “, limit, “ numbers is “, total
display “The average is “, average, “ and the largest number is “, largest
STOP

Flowchart : SomeNumbers

START

total  0
largest  0 A
average  0

[103]
Computer Science Unit 1 Module 2

display “How many numbers


do you have?”

read limit

count  1

display “Enter one number”

read num

count  count + 1
total  total + num

N
num > largest?

highest  num

count < limit? B


Y N

[104]
C-A. Jardette

limit = 0?
Y

average  total / limit

display “the sum is”, total

display “the average is”, average

display “the largest number is”, largest

STOP

10.20 Design a program that will be used to determine the Math grade for a form of 40 students and
find the average % for the form.

Solution

Pseudocode : MathForm
// Find Math grades

Solution

DECLARATIONS
Constants
size = 40
Variables
mark, average, sum – data type real
count – data type integer

[105]
Computer Science Unit 1 Module 2

PROCESS
//initializations
sum  0

// get and check data


FOR count  1 TO size STEP 1 DO
display “Enter a mark”
read mark

case mark of
100 .. 80 - display “Student got an A”
79 .. 70 - display “Student got a B”
69 .. 60 - display “Student got a C”
59 .. 50 - display “Student got a D”
Otherwise - display “Student failed”
endcase

// total marks
sum  sum + mark
ENDFOR

average  sum / size // average  sum / count


display “The average for the class is ”, average
STOP

Flowchart : MarkForm
START

sum  0

count  1

display “Enter a mark”

read mark

[106]
C-A. Jardette

mark?

80 <= mark <= 100 60 <= mark <= 69 mark < 50


70 <= mark <= 79 50 <= mark <= 59

display “Fail”
display “A” display “C”

display “B” display “D”

C
C C

sum  sum + mark

count < 40?

N Y

average  sum / count


count  count + 1

display “Class average ”, average B

STOP

[107]
Computer Science Unit 1 Module 2

10.21 Calculate the wages of a set of workers for one week. The input is the number of hours each
worker worked per day.

Solution

Pseudocode : Wages
// Find employees’ wages

Solution

DECLARATIONS
Constants
rate = 250.00
days = 5
Variables
i, j, numemployees – data type integer
hours, weekwage, totalwage – data type real

PROCESS
totalwage  0

display “How many employees are there?”


read numemployees

for i  1 to numemployees do
weekwage  0 // reset to 0 for each new employee
for j  1 to days do
display “Enter hours worked”
read hours
weekwage  weekwage + (hours * rate)
endfor
display “Wage “, weekwage
totalwage  totalwage + weekwage
endfor

display “You are paying”, totalwage, “out in wages this week”


STOP

Flowchart : WeeklyWages

START

set totalwages to 0 A

[108]
C-A. Jardette

i1

weekwage  0

j1

display “Enter hours worked”

jj+1
read hours

weekwages  weekwages + (hours * 250)

ii+1
j < 5

display weekwages

totalwages  totalwages + weekwages

i < numemployees?

STOP display totalwages

[109]
Computer Science Unit 1 Module 2

PRACTICE EXERCISE 9

1. Design a program which displays “Computer Science is really great” 20 times.

2. Design a program that displays the first 15 odd numbers

[110]
C-A. Jardette

3. Design a program that reads the scores for a cricket team and then determines how
many players scored a century (100 or more) and how many made duck (0). Note that
there are 11 players on a cricket team.

[111]
Computer Science Unit 1 Module 2

4. Design a program that reads the names and cost of 6 items bought by a customer and
prints the bill. The bill should show the name and cost of each item and at the bottom,
it should show the total cost, the tax and the total cost including tax of 15%.

[112]
C-A. Jardette

WORKSHEET 4 - BOUNDED LOOPS

Create the for loop algorithm for the following situations:

1. A program which determines the average rainfall for a 7 day period given the rainfall
for each day.

2. A program that accepts the half term mark for all the students in your computer
science class and displays the class average.

3. A computer program that displays the 9 times table up to 9 times 20.

4. A program that reads the name and the population for 5 Caribbean countries and then
determines which of the countries has the lowest population. It should also display the
level of the lowest population.

5. A system to tell a company their year-to-date sales total for every month in a year. The
input should be the sales figure for each month starting at January.

6. A program that determines the total number of points earned by Asafa Powell in the
diamond league athletics competition. He will take part in 9 of the 14 diamond league
races and scores between 4 and 2 points in each race depending on his placement. First
place = 4 points, 2nd place = 3 points, and 3rd place = 2 points.

[113]
Computer Science Unit 1 Module 2

11 INTRODUCTION TO FUNCTIONS

Cleaning the whole house may seem overwhelming, but cleaning one room
at a time is a much more manageable task.

11.1
Most real world programs are too big to be understood or created in a single go. They must be
divided into smaller pieces that are easier to handle and so can be conquered separately. We
then put the smaller pieces together to form the complete picture. The process of breaking up
a large problem into smaller more manageable, and easier to understand portions is called
modular decomposition or stepwise refinement and when we use this strategy we are said to be
doing top-down programming. The resulting pieces are known as sub-modules or
(sub)procedures or (sub)functions or (sub)routines of the overall program. These are the
building blocks of large programs.

During the design phase of program development, the analyst, programmer or programming
team decides on logical subtasks within the overall project. One function should do one
distinct task.
Each subtask can be programmed by different programmers all working at the same time.
This approach has the additional advantage of reducing the time it takes to complete the
overall solution.

A function is a set of program statements that performs one sub-task within an overall
program, and which has been isolated or extracted from the rest of the program, packaged
together and given a name. Functions may be prewritten i.e. they are a part of the library of
functions available in that particular implementation of the programming language and so are
already known to the compiler, or they may be written by any programmer in his/her
program.

Functions make a program easier to write, easier to read and understand, and easier to
maintain. The use of sub-modules also makes it convenient to reuse code within a program
without having to retype it every time it needs to be executed. The procedure/function can
simply be called at the time that it is needed. Another advantage of using functions is that well
designed modules can be stored in a library of prewritten routines and then reused in other
applications.

[114]
C-A. Jardette

11.2
Declaring a function - in pseudocode sub-modules should be declared after the main program

FUNCTION function_name()
// description

DECLARATIONS

PROCESS
statement1
statement2
:
STOP

To use this function either in the main program or in any other function, we call or invoke it
:
display "About to call"
call function_name(arguments)
display "Back from call"
:
The call replaces the individual lines of code which make up the body of the function. When
execution is taking place, the program will execute up to the call, at the call it will go off and
execute the statements in the function, then at the end of the function it will return to the line
following the function call in the main program and continue execution.

Example
// global comments

program mylargeprogram
// main program

DECLARATIONS
Variables
num1, num2 – data type integer // some comment
PROCESS
display "Beginning"
call initFunction(num1)
do somethings
call nextFunction( )
do somethingelse
STOP // end of main program

[115]
Computer Science Unit 1 Module 2

function initFunction()
// comment

DECLARATIONS
Parameters
num1 – data type integer
Variables
none

PROCESS
do somethun …
STOP

function nextFunction( )
// comment

DECLARATIONS
Parameters
none
Variables
none
PROCESS
La la la …
STOP

The use of functions reduces the size of the main program and makes it easy to understand in
a summary form what the overall program does by simply looking at the main program.
Other names for a function are module, procedure, routine, …

Note that a function name is always followed by ( ), and every function referred to in the main
program must later be defined.

11.3
Parameters are variables which are sent back and forth between functions and are used to
communicate (send data) between them. Values can be sent to the function through the use of
parameters and values can be sent back to the calling function through the use of parameters.
Declaring the parameters tells the function what it should expect to receive each time it is
invoked.

[116]
C-A. Jardette

11.4
Functions with no parameters
The simplest function has no parameters whatsoever.

Example
Declaring the function
Function displaymenu( )

DECLARATIONS
Parameters
none
Variables
none
PROCESS
display “Welcome”
display “A - Add”
display “B - Maintain”
display “C - Exit”
STOP

To call/invoke this function


call displaymenu( );

It is a good idea to give functions like that above names which are verbs since they simply do
something.

11.5
Functions with Parameters
When a variable is sent to a function do we mean to send the value presently in the variable or do we
mean to send access to the actual memory slot so that the function can change the value if it needs to?
There are two types of parameters – value parameters and variable parameters. Here is the
difference -

Sometimes one or more values need to be sent to a function so that the function can use them
in doing its task, example a calculation. This value of the variable itself will not be changed
however, so that the function does not actually need to have access to the memory location
which stores the variable, it really just needs to know what value the variable contains at the
point that this function is being called. This is a value parameter and it is called passing by
value or passing by copy.

[117]
Computer Science Unit 1 Module 2

On the other hand, sometimes a function needs to make changes to a variable; changes which
need to be seen as permanent and the changed value must be transmitted back to the calling
function. In these circumstances the function must have access to the actual memory slot
where the variable is stored so that it can place a new value there. These parameters are
known as variable parameters and they are passed by reference or passed by address.

Here is a function that takes two whole numbers and sends back which is the smallest. We
will use comments to distinguish between the two types of parameters.

function smalltwo ()
// comment
DECLARATIONS
Parameters
smaller – data type integer //will be used as a variable parameter
num1, num2 – data type integer // will be used as value parameters
Variables
none
PROCESS
if (num1 > num2) then
smaller  num2
else
smaller  num1
endif
STOP

num1 and num2, have been separated from smaller to illustrate the difference in their use.
num1 and num2 are passed by value – they are value parameters. All function smalltwo()
needs to know is their value, it will not be making any changes to them.
smaller on the other hand will be changed because the answer is being sent back in that
variable. It must therefore be a variable parameter and be passed by reference.

To call this function


call smalltwo(smaller, num1, num2)

The contents of the brackets are called arguments. Note that when calling a function one does
not include any references to the arguments’ data type. Note too that the call does not
provide any clues as to whether the variables are being passed by value or by reference. It is
simply the list of variables in the same order as the declaration in the function. The list of
arguments must match the list of parameters both in number and in data type.

[118]
C-A. Jardette

Example of a program which uses parameters/arguments

1 pseudocode : TestArguments
// This is the main section of a program which …
DECLARATIONS
Variables
2 value1, value2 – data type integer
PROCESS
3 value1  20
4 value2  50
5 call half_it1(value1)
6 display “The value of num1 after the first function call is ”, value1
7 call half_it2(value2)
8 display “The value of num2 after the second function call is ”, value2
STOP //end of main program

9 function half_it1()
// This function …

DECLARATIONS
Parameters
10 num1 – data type integer //will be used as a value parameter
Variables
none
PROCESS
11 num1  num1 / 2
12 display num1
STOP

13 function half_it2()
// comment

DECLARATIONS
Parameters
14 num2 – data type integer // will be treated as a variable parameter
Variables
none
PROCESS
15 num2  num2 / 2
16 display num2
STOP
The difference between half_it1( ) and half)it2( ) is that the changes made by half_it2( ) will be
reflected in the main program because the variable is passed by address. So the output of the
entire program will be -

[119]
Computer Science Unit 1 Module 2

10 output from line 12 in half_it1( )


20 output from line 6 in the main function
25 output form line 16 in half_it2( )
25 output form line 8 in the main function

11.6
Local Variables
In addition to parameters – values/variables passed between a function and its caller - we can
also set up variables inside a function for use by just that function. Variables declared inside a
function are called local variables and they only exist inside that function. They are created
when the function is called and they die when the function ends.

Example
Declaring the function
function checkweather( )
DECLARATIONS
Parameters
none
Variables
status – data type character
PROCESS
display “How is the weather today”
display “Type ‘S’ for sunny or ‘D’ for dreary”
read status
if (status = ‘S’) then
display “Wear your shades”
else if (status = ‘D’) then
display “Hush”
endif
endif
STOP

Calling the function


call checkweather( )

This function uses no parameters/arguments, only a local variable.

Inside a function all variables, whether they be parameters or local variables, can be accessed
and manipulated in the usual manner.

[120]
C-A. Jardette

11.7
Parameter Passing Summary
The values/variables which are passing between a function and its caller are called arguments
in the call and parameters in the function.

Passing by reference/address
If we want the function to be able to change the value of a variable, we must pass that variable
by address/reference. Passing by reference means that the function gets access to the variable’s
location in memory and so can make changes to it.
The effects of passing by address :
- any changes made to the variable inside the function will be available outside
of the function
- variables which store results being sent back to the calling function must be
passed by address

Passing by value/copy
To pass by value means to send the present contents of the variable to the function but not the
actual variable address itself. Passing by value allows the value of the variable to be used by
the function but it can not permanently change the variable. So if var1 is 25 before the function
is called, it is still 25 after the call.

Calling the function


When the function is being called the list of variables being sent to it is included in the
brackets. These are regarded as the arguments (though most books call them parameters too).
1. The number of arguments must match the number of parameters.
2. The order of the data types declared as parameters must match the list of arguments.

The arguments and the parameters do not have to have the same name. When you are calling
the function you may send any set of variables to it as long as you pay attention to rules 1 and
2 above.

Finally
The implication of parameter passing and the use of local variables is that any variable being
used in a function must be accounted for –

1. either it was passed as a parameter (reference parameter or value parameter)


or
2. it was declared inside the function as a local variable.

[121]
Computer Science Unit 1 Module 2

Here are the designs for some programs that use functions.

11.8
// A program that performs arithmetic for the user
PSEUDOCODE: Arithmetic

DECLARATIONS
Variables
option – data type integer

PROCESS // Main program


// Display the menu and get the user’s choice
repeat
display “1 - Addition”
display “2 - Subtraction”
display “3 - Multiplication”
display “4 - Exit”
display “Choose 1, 2, 3 or 4”
read option
until (option = 1) or (option = 2) or (option = 3) or (option = 4)

//Process the choice


if (option = 1) then
call addition()
else
if (option = 2) then
call subtraction()
else
if (option = 3) then
call multiplication()
endif
endif
endif
STOP

FUNCTION addition()
// Adds 2 numbers

DECLARATIONS
Parameters
none
Variables
num1, num2, total – data type real
PROCESS
display “Enter the 2 numbers to be added”
read num1, num2
total  num1 + num2
display “The sum of”, num1, “and”, num2, “is”, total
STOP

[122]
C-A. Jardette

FUNCTION subtraction()
// Subtracts one number from the other

DECLARATIONS
Parameters
none
Variables
num1, num2, difference – data type real
PROCESS
display “Enter the 2 numbers”
read num1, num2
difference  num1 - num2
display num1, “minus”, num2, “=”, difference
STOP

FUNCTION multiplication()
// Multiplies 2 numbers

DECLARATIONS
Parameters
none
Variables
num1, num2, product – data type real
PROCESS
display “Enter the 2 numbers to be multiplied”
read num1, num2
product  num1 * num2
display “The product of”, num1, “and”, num2, “is”, product
STOP

11.9
// A program that calculates the electricity bill for a series of individuals and organizations where
// different rates are used for each type of consumer.
PSEUDOCODE: Bills

DECLARATIONS
Constants
cutOff1 = 75
cutOff2 = 150
resRate1 = 110.00
resRate2 = 140.00
comRate1 = 100.00
comRate2 = 200.00
Variables
choice, answer – data type character
wattage, grandtotal – data type real
PROCESS
repeat
display “How much electricity was used?”
read wattage

[123]
Computer Science Unit 1 Module 2

// This loop forces the user to choose I or C


repeat
display “I - Individual account”
display “C - Corporate account”
read choice
until (choice = ‘I’) or (choice = ‘C’)

// Call a different function to process the user’s entry


if (choice = ‘I’) then
call processResidential(wattage, grandtotal)
else
call processCommercial(wattage, grandtotal)
endif
display “Bill amount - $”, grandtotal

// Determine if the loop should be repeated


display “Process another (Y/N)?”
read answer
until (answer <> ‘Y’)
display “Program ending …”
STOP

FUNCTION processResidential()
// Calculates the bill for a householder

DECLARATIONS
Parameters
wattage – data type real //passed by copy
grandtotal – data type real //passed by reference
Variables
amount1, amount2, sum1, sum2 – data type real
PROCESS
if (wattage > cutoff1) then
amount1 = cutoff1
amount2 = wattage – cutoff1
else
amount1 = wattage
amount2 = 0
endif

sum1 = amount1 * resRate1


sum2 = amount2 * resRate2
grandtotal = sum1 + sum2
STOP

FUNCTION processCommercial()
// Calculates the bill for a company

DECLARATIONS
Parameters
powerUsed – data type real //passed by copy
billAmount – data type real //passed by reference

[124]
C-A. Jardette

Variables
usage1, usage2 – data type real
PROCESS
if (powerUsed > cutoff2) then
usage1 = cutoff2
usage2 = powerUsed – cutoff2
else
usage1 = powerUsed
usage2 = 0
endif
billAmount = (usage1 * comRate1) + (usage2 * comRate2)
STOP

11.10 Depicting a Function in a Flowchart


Imagine that we have a function defined as below:

FUNCTION Square()
DECLARATIONS
Parameters
num, ans – data type integer
PROCESS
ans = num * num
STOP

And this function is called from another function or the main program as follows:
|
display "Enter an integer"
read value
Square(value, answer)
display "The square of ", value, "is ", answer
|

This is how it can be depicted in flowchart format, notice that the parameters are shown in the
START symbol.

Function Square()
display “Enter an integer”

START
 val
read value
 ans

Square(value, answer)
ans  num * num

display “The square of “,


STOP
value, “ is “, answer”

[125]
Computer Science Unit 1 Module 2

PRACTICE EXERCISE 10

1. Design a program which performs data conversion for the user. It begins by
displaying a menu with the following options: C – Perform currency conversion, T –
Perform temperature conversion, W – Perform weight conversion, D – Perform
distance conversion. It should also provide an option for ending the program. A
different function should be called for each option that the user takes. The currency
conversion function should convert from the US currency to the Jamaican dollar at the
rate of US$1 to JA$130; the temperature conversion function should convert from
Fahrenheit to Celsius; the weight conversion function should convert from pounds to
Kilograms; and the distance conversion function should convert from miles to
Kilometres. The functions should not have any parameters.

[126]
C-A. Jardette

[127]
Computer Science Unit 1 Module 2

2. Create the pseudocode for a program that accepts 4 integers and uses different
functions to find the average, largest and smallest of the 4 numbers. The outputs
should be given in the main program.

[128]
C-A. Jardette

[129]
Computer Science Unit 1 Module 2

12. ARRAYS

12.1
Often, at the beginning of a program, the programmer is required to clearly give a name to the
data items to be processed, and also state the form of that data i.e. give the data’s type. These
data items may be classified as scalar/basic data types or composite/aggregate data types.
The basic data types are integer, real, and character. A composite data type, on the other
hand, is a data element that is made up of other data elements i.e. it is an aggregate of data
items. The data items that it contains may be elementary data types or other data structures.
The most common composite data types are arrays, strings, records and files.

A string is a collection of characters. In pseudocode we will define a string as if it were an


elementary data type (string) and leave the C implementation issues until we are actually
coding.
A record is a collection of data items or fields that all related i.e. together they describe one
item. They do not all have to be the same data type.
A file is a collection of related records. The idea behind a file is to have the data stored on a
secondary storage device so that the data can be available for subsequent runs of a program or
even available to more than one program.

ARRAYS - This is a data structure made up of a number of variables or data items that all
have the same data type and are referred to with the same name but using an index to access
each individual element.
An array is useful where it is necessary to show a relationship among a set of variables or to
store and reference variables as a group. In addition, imagine that we are required to read a
set of values and then print those values in reverse order. We could always use one variable
and a loop to accept the values but to be able to display all the values at the end in reverse
order the truth is we must be keeping all the values we receive when we read them, we cannot
afford to replace any of them. If there are 3 or even 10 values we may be perfectly content to
set up three or ten variables to hold the values. When there are 100000, 1000 or even 50 values
it is impractical to expect the programmer to set up individual variables in those
circumstances. Good programming languages therefore have a data type construct that
allows easy declaration and manipulation of multiple variables of the same data type and this
is the array.

[130]
C-A. Jardette

12.2
A one-dimensional array is a structured collection of components of the same data type
which is given a single name and with each element being individually accessible by
specifying the position of that component in the list with an index.

Values

0 1 2 3 4 5 6 7 8 9
Here we have an array named Values with 10 slots making it therefore capable of storing 10
components i.e. 10 elements. The numbers at the bottom indicate the ‘address’ or index of
each element.

We set up an array by giving its name, stating the data type of the elements, and indicating
the maximum number of elements it can contain name[size] - data type x

Examples of array declarations

values[10] – data type integer ( the array values will contain 10 integers )

heights[20] – data type real ( the array heights will contain 20 real numbers )

answers[40] - data type character ( the array answers will contain 40 characters )

Arrays are set up in the declaration part of the program in the same way that other variables
are declared.
To access individual elements in an array we use the name of the array and indicate the index
of the particular element that interest us. NOTE: WHEN COMPUTER SCIENTIST COUNT
WE ALWAYS BEGIN AT 0, NOT 1. Array indices therefore start at 0. The first element of
an array is element 0, the second is element 1, the third is element 2, etc.

[131]
Computer Science Unit 1 Module 2

Examples values[3] values[7] heights[2] heights[17]


answers[5] answers[0] answers[3]

values[3] is actually the 4th element in values and answers[24] is the 25th element in answers.

12.3
We can use the elements in an array in all the same ways that we can use single variables.
The beauty of arrays though, is that we can use a loop to access the elements easily. Imagine
that we have set up an array as follows : Variables
values[10] – data type integer
count – data type integer

12.4 - Populating an Array


We can get the values for an array from the user one after the other by using a FOR loop to
read the values directly into the elements of the array

for count  0 to 9 step 1 do


display “Enter a whole number”
read values[count]
endfor

When count has the value 0 we populate the first position in the array; when count has the
value 4, what the user types goes into the 5th position. Count goes to 9 and the array also goes
to 9. When the loop ends the array has a value in all the positions i.e. it is initialized.
We could initialize the array to all zeros ourselves using a similar loop.

for count  0 to 9 step 1 do


values[count]  0
endfor

12.5 - Printing/displaying the contents of an array


We can also use a for loop to get to the contents of the array for the purposes of output.

for count  0 to 9 step 1 do


display values[count]
endfor

The FOR LOOP is usually the best choice for accessing all the elements of an array.

[132]
C-A. Jardette

PRACTICE EXERCISE 11

Declare appropriate arrays for the following situations :


1. To store the points received by each house in a SAHS inter-house competition. The
list should be alphabetic

2. To store the marks received by each girl in this class for Computer Science for the
Christmas term

3. To store the yes or no response given by a respondent to a survey with 20


questions

4. To store the ages of the members of a family of 7 persons.

5. To store the names of the months of the year.

How would you reference the particular element described below?


6. The number of points gained by Stockhausen assuming that the houses are in
alphabetic order?

7. The percentage gained by the 9th student in the class

8. The person’s answer to the 11th question

[133]
Computer Science Unit 1 Module 2

9. The age of father (the oldest in the family), assuming that the array is sorted by age
in descending order

10. The position of November in the list

12.6 Parallel Arrays


Parallel arrays are two or more arrays of the same size with related data such that element x in
one array corresponds to element x in all the other arrays. Parallel arrays do not have to have
the same data type. They are defined separately as individual arrays but they are processed
together.
Example : names[15] – data type string
grades[15] – data type real
one array to hold the names of students and the other holds their grades so that the grade in
slot 8 of
the second array is for the student whose name is in slot 8 in the first array.

12.7
2-D Arrays
Multidimensional arrays can be described as "arrays of arrays" all having the same data type.
The bi-dimensional array is the simplest multidimensional array and can be regarded as a flat
table with x number of columns and y number of rows.

Datalist[]

Datalist represents a bi-dimensional array of 3 by 5 elements - using the row, column notation

[134]
C-A. Jardette

The way to declare such an array is datalist[3][5] - data type integer

The shaded element is datalist[1][2] (i.e. row 1 column 2)

62

Some examples of algorithms using arrays now follow

12.8 Pseudocode : garthshoreCup


// Using an array to store the Garthshore Cup house points and tell the winner at the end;
// note that there are 6 houses

DECLARATIONS
Constants
max = 5
Variables
housepoints[6] – data type integer
i, points – data type integer
response – data type character
PROCESS
// set all the house points to zero
for i  0 to max do
housepoints[i]  0
endfor
// Accept the points won for the pieces in the competition and update the points for each house
display “Enter a house number (1, 2, 3, 4, 5, or 6)”
read i
while (i > 0) and (i < 7) do
display “Enter the number of points gained by house”, i
read points
housepoints[i - 1]  housepoints[i - 1] + points
display “Do you want to see the present standings?”
read response
if (response = ‘Y’) then
for i  0 to max do
display i + 1
display housepoints[i]
endfor
endif

display “Enter a house number again (1,2, 3, 4, 5 or 6)”


read i
endwhile

//Give the final results


display “The final standings are :”
for i  0 to max step 1 do
display i + 1, ” ”, housepoints[i]
endfor
STOP

[135]
Computer Science Unit 1 Module 2

12.9 Pseudocode : AllAges


// A program to take the heights of all the persons in the household starting with the tallest; then to display
// the heights from shortest to tallest.

DECLARATIONS
Constants
maxpeople = 7
limit = 6
Variables
heights[maxpeople], onefigure – data type real
i – data type integer
PROCESS
// Get the data into the array
for i  0 to limit do
display “Enter a height”
read onefigure // these two lines could simply be written as
heights[i]  onefigure // read heights[i]
endfor

// Show the heights in reverse order


display “The heights in this family are : ”
for i  limit to 0 step -1 do
display heights[i]
endfor
STOP

12.10 Pseudocode : CricketMatch


// Using arrays to store the scores of the cricketers in a match

DECLARATIONS
Constants
team = 11
max = 10
Variables
names[team] – data type string // stores the names
scores[team] – data type integer // stores the scores
count, runs – data type integer
PROCESS
// initialise both arrays
for count  0 to max step 1 do
display “Enter the name of the batsman “
read names[count] // store his name
scores[count]  0 // give him a zero to start with
endfor

// accumulate their scores as the game goes on


display “Which batsman just scored (enter his number)?”
read count
while (count > 0) and (count < 12) do // there are 11 players
display “and how much did batsman ”, count, “ score?”
read runs
scores[count - 1]  scores[count - 1] + runs
display “Enter the batsman who scored’s order (type an invalid number to end)”
read count
endwhile

// display the score card at the end of the match


for count  0 to max step 1 do
display count + 1, “ ”, names[count], “ ”, scores[count]
endfor
STOP

[136]
C-A. Jardette

12.11 Pseudocode : Merge2to3rd


// Given 2 sorted arrays of size 5 with the following elements put all the elements into
// a third array in sorted order. This is called merging 13 21 57 69 73 and 2 16 48 74 100

DECLARATIONS
Variables
listone[5], listtwo[5], list3[10] – data type integer
i, j, count - data type integer

PROCESS
// initialise the arrays
listone[0]  13
listone[1]  21
listone[2]  57
listone[3]  69
listone[4]  73

listtwo[0]  2
listtwo[1]  16
listtwo[2]  48
listtwo[3]  74
listtwo[4]  100

// initialise the counters


i0
j0
count  0

// perform the merge


While (i < 5) and (j < 5) do // both arrays have values remaining
If (listone[i] < listtwo[j]) then
list3[count]  listone[i]
i  i + 1
else
list3[count]  listtwo[j]
j  j + 1
endif
count  count + 1 // go to the next slot in the large array
endwhile

// assuming that the values in listone are finished, we now copy over listtwo to list3
While (i > 4) and (count <= 9) do
list3[count]  listtwo[j]
j  j + 1
count  count + 1
endwhile

// assuming that the values in listtwo are finished, we now copy over listone to list3
while (j > 4) and (count <= 9) do
list3[count]  listone[i]
i  i + 1
count  count + 1
endwhile

//display the arrays


for i  0 to 4 step 1 do
display listone[i], “ ”

[137]
Computer Science Unit 1 Module 2

endfor
for j  0 to 4 step 1 do
display listtwo[j], “ ”
endfor

for count  0 to 9 step 1 do


display list3[count], “ ”
endfor
STOP

PRACTICE EXERCISE 12

Design a program which will (in the order specified)

a) obtain 30 numbers from the user and store them in an array


b) display the total of the contents of the array
c) display the 30 numbers in reverse order.
d) allow the user to change the 10th, 20th and 30th element in the array
e) display the new total of the array contents
f) find the average of the contents
g) display how many elements in the array are larger than the average

[138]
C-A. Jardette

[139]
Computer Science Unit 1 Module 2

[140]
C-A. Jardette

12.12
Passing Arrays Between Functions
When we pass an array to a function as an argument we are in fact passing the address of the
first element in the array thus making an array by its very nature, a reference parameter, it can
not be passed any other way.

Example of passing an array - Given the array names[15] - data type string

Function nameyNamey()
DECLARATIONS
Parameters
country – data type string // pass by address
names[ ] – data type string // the array is passed
by address
count – data type integer // pass by value

Note
- names[ ] indicates that the entire array is being sent. Any element can then be used or
changed
- Individual elements can be sent by themselves and this is much more efficient if the
entire array is not really needed in the function. Example : a parameter can be
names[3] – data type string. Remember that you need to indicate, for individual
elements, if they are being passed by value or by reference

12.13
Linear Search of An Array
To make the best use of the array structure we must be able though to manipulate it to meet
our particular needs. The need to locate a particular element in an array, or to find out if a
particular element is in the list, is almost universal. This is called searching. The simplest
search is the linear search.

Narrative Algorithm of the Linear Search

1 Starting at the first element, sequentially scan the array comparing each
subsequent item with the item being searched for
2 if a match is found return the index of the match, if not, return – 1 (-1 is not a
valid index)

[141]
Computer Science Unit 1 Module 2

Pseudocode of the Linear Search

Function lsearch()
// searching the array datalist[] for a value called target

DECLARATIONS
Parameters
datalist[ ] – data type character // the array to be searched – pass by reference
index – data type integer // the position at which target was found –
// pass by reference
size – data type integer // the number of elements in the array
target – data type character // what is being searched for
Variables
found – data type integer // found with a value of 1 indicates that
// the item was found
PROCESS
found  0 // found will be set to 1 when the target is
// located
index  0 // start at the first slot
while (index < size) and (found = 0) do // still more items to
// compare and
if (datalist[index] = target) then // check target
found  1
else
index  index + 1 // advance index to next slot
endif
endwhile
if found = 0 then // loop ended and target was not found
index  -1 // so send back a -1
endif
STOP

[142]
C-A. Jardette

WORKSHEET 5 - ARRAYS

Design the following programs which use arrays

1. Accept two columns of 12 integers each (one column at a time) and then display the
total and the product of the corresponding elements in the columns. A sample run of the
program is shown below

Enter the first column of numbers : 2 4 6 8 10 12 3 5 7 9 11 1


Enter the second column of numbers : 10 8 6 4 2 1 9 7 5 3 1 12

Number Number Sum Product


2 10 12 20
4 8 12 32
6 6 12 36
8 4 12 24
10 2 12 20
12 1 13 12
3 9 12 27
5 7 12 35
7 5 12 35
9 3 12 27
11 1 12 11
1 12 13 12

2. Perform currency conversion for the user.


The program should firstly ask for the United States exchange rates for 10 different
currencies
and store this in an array. It will then display the table of rates and ask the user to choose
which currency they have by using a number. Next they will indicate which currency they
wish to change to, also by entering a number. The program should do the conversion and
display the new value.

[143]
Computer Science Unit 1 Module 2

13. RECORDS

13.1
We met composite data types when we first started talking about arrays. As a reminder, the
most common composite data types are strings, arrays, records & files. And now we will be
talking about records. A record is a group of related data items. They do not all have to be the
same data type. Records are used to associate some related variables together, rather like the
way fields are grouped together to form records in a database. The record then describes one
entity being processed.

13.2
Declaring Records
Suppose we are dealing with countries in our program. And we want to store several pieces of
data about each country e.g. the country’s name, its capital, its population and its leader. We
would of course define a variable for each of these attributes :
name – data type string
capital – data type string
population – data type integer
leader – data type string

But we could go further and show that these 4 variables are related by putting them in a
record data type -
countryrecord
name – data type string
capital – data type string
population – data type integer
leader – data type string
endrecord

In effect we have set up a new data type with the tag countryrecord. The four elements of
countryrecord each have their own identifier. We are then free to define as many variables of
data type countryrecord as we desire.

Variables
country1, country2, newcountry, topcountry, lostcountry
– data type countryrecord

To define a record therefore we firstly set up the record type, then we declare variables of
that type. All of this is done in the DECLARATION section of a module.

[144]
C-A. Jardette

Example 2
Records
studentrecord
name – data type string
age – data type integer
yeargroup – data type integer
average – data type real
endrecord

Variables
student1, student2 – data type studentrecord

Example 3
Records
bankrecord
acct_type – data type character
acctname – data type string
acctbal – data type real
endrecord

Variables
myaccount, youraccount, ouraccount – data type bankrecord

Note that the word record does not have to appear in the name but it is a good practice as it
helps one to recognize the structure when we are later setting up the actual variables.

13.3
How do we use the record variable?
We use what is called the dot notation to refer to the component elements of a record as
follows:
read country1.population
display country1.name
newcountry.leader  “President”
read newcountry.capital
country2.leader  “King”
display lostcountry.name
read lostcountry.population
print “It’s capital is ”, newcountry.capital
display country2.leader, “ has been ruling for 20 years”

The use of records in some programming languages is actually a first step towards object-
oriented programming which is about programming around entities.

[145]
Computer Science Unit 1 Module 2

13.4 – A program using records

PSEUDOCODE workers
// This program accepts information on an employee and redisplays the data in a formatted manner

DECLARATIONS
Records
addressrecord //stores an address
addr1 – data type string
addr2 – data type string
endrecord

paystructurerecord
hourly? - data type character // contains Y or N
hourrate - data type real // contains the rate if hourly? is Y
salary – data type real // contains the yearly salary if N
endrecord

employeerecord
name1 – data type string
name2 – data type string
address – data type addressrecord // based on the address record
phone – data type string
maritalstatus – data type character
gender – data type character
dateofbirth – data type string
position – data type string
paystructure – data type paystructurerecord
endrecord

Variables
employee1 – data type employeerecord

PROCESS //Main function


//get data
display “ I will accept data for 1 employee”

display “ Enter first name ‘


read employee1.name1
display “Enter last name”
read employee1.name2

display “Enter number and street”


read employee1.address.addr1
display “Enter area”
read employee1.address.addr2
display “Enter home phone number”
read employee1.phone

display “Select marital status”


read employee1.maritalstatus

display “Is this employee a male or a female (M/F)”


read employee1.gender

[146]
C-A. Jardette

display “Enter data of birth”


read employee1.dateofbirth
display “What position does this employee hold?”
read employee1.position

display “Is this employee paid by the hour (Y/N)?”


read employee1.paystructure. hourly?
// assume that either Y or N is entered
if employee1.paystructure.hourly? = ‘Y’ then
display “Enter his/her hourly rate?”
read employee1.paystructure.hourrate
else
display “Enter his/her yearly salary”
read employee1.paystructure.salary
endif
display ‘Thank you”
display “ “

// redisplay some of the data


displayline( )
display “EMPLOYEE DATA”
displayline( )
displayline( )

display “NAME : “, employee1.name1, “ “, employee1.name2


display “GENDER : “, employee1.gender
display “MARITAL STATUS : “, employee1.maritalstatus
display “POSITION : “, employee1.position

display “PAY : $”
if employe1.paystructure.hourly? = ‘Y’ then
display employee1.paystructure.hourrate, “ per hour”
else
display employee1.paystructure.salary, “ per year”
endif
display “Thank you for your patience”
STOP

FUNCTION displayline( )
// displays a line on the screen
PROCESS
Display “------------------------------------------------------------------------“
STOP

13.5
A record can be sent to a function as a parameter. As for any other variable, the programmer
needs to specify whether it is a variable parameter or a value parameter. One or more
individual elements of a record can also be sent as a variable or value parameter.

In addition one record can be directly copied to another. Example: rec1  rec2

[147]
Computer Science Unit 1 Module 2

14. FILES

14.1
So far all our solutions assume that data entered into a program is coming from the keyboard
and that output is to the screen. This is not always so in real life however. Here are some
situations in which it is impractical to expect to use only the keyboard and the screen.
1. the volume of data being processed is very large
- it is tedious and error prone to enter large amounts of data interactively at the
console
2. data needs to be accumulated over a period of time
3. the output from previous runs of the program needs to be available for further use
4. the data is already stored or is best stored, in a databases

All of this calls for the use of a file. Variables exist only in RAM and live only as long as the
program is running. A data file, however, is an object stored on a secondary storage medium
and so exists even when no program is running. Such a file would in fact be available to as
many programs that need to use it.

14.2
Conceptually we see a file as a set of records stored one after the other sequentially. Each file
also has an end-of-file marker which at any time is positioned immediately after the last entry
in the file.
The basic operations on a file are 1. put data into the file i.e. output/write data to a file, and 2.
get data from the file i.e. input/read data from a file into the program

Using Data Files


For our purposes, to tell a program about a file we declare it as a text file in the declaration of
variables section of our algorithm.

DECLARATIONS
Variables
employeefile, studentfile, customerfile,
patientfile – data type text file

14.3
Ordinarily when we use the command read we are instructing the system to get data from the
standard input device - the keyboard; and when we use the command display we are
instructing the system to output data to the standard output device - the monitor. Now

[148]
C-A. Jardette

however, instead of the standard output (the screen) I want my data to go to one of these
external files declared above.
I first tell the system to position what is called a file pointer at the bottom/end of the file so that
it is ready to accept new lines of data. We do this by saying open filename for output

open employeefile for output


open studentfile for output

I would then use the same command for output (output/display/print) but I must also specify
the name of the file. Examples of outputting to a file
output studentfile, age
output customerfile, invnumber
output patientfile, diagnosis
output employeefile, name

14.4
To tell the system that I want to get data from the file we would firstly issue the following
command : open filename as an input file. This command positions the file pointer at the
beginning of the file so that whatever data is in the file is accessed on each subsequent read
operation.
Examples
open stockfile as an input file
open gradesfile as an input file

In a similar manner, to get data from the file we then use read/input and we also use the file
name.
Examples
input employeefile, hourlyrate
input customerfile, quantitybought
input patientfile ,dateofbirth

14.5
This preparation of the file for use needs to be done only once before reading or once before
writing. When we are finished using the file we will need to issue the following command
close filename
Examples
close stockfile close employeefile
close moviefile close patientfile

If we want to switch from reading to writing or from writing to reading, we also need to close
the file and then reopen it in the appropriate mode.

[149]
Computer Science Unit 1 Module 2

Example 1: Assume declaration of text file named list

open list for output


display “Favourite colour? ”
read favcolour
output list, favcolour // store to file
display “Favourite subject? ”
read favsubject
output list, favsubject // store to file
close list

open list as an input file


input list colour //read from the file and store in variable colour
input list subject //read from the file and store in variable subject
display “My favourite colour is ”, colour
display “and my favourite subject is ”, subject
close list

Note that data in a program must be stored in a variable, whether it is coming from or going
to the keyboard, the monitor, or a file.

Example 2 :
Pseudocode : StoreIt

DECLRATIONS
Variables
sayingsfile – data type textfile
saying1, saying2 – data type string

PROCESS
open sayingsfile for output
display “Whey yu seh ?”
read saying1
output sayingsfile, saying1
close sayingsfile

open sayingsfile as an input file


input sayingsfile, saying2
display “This is what you said ”, saying2
close sayingsfile
STOP

[150]
C-A. Jardette

14.6
Input and output are the elementary operations we do on files. But apart from that we
sometimes need to find and/or change existing data in a file. For example, we may want to
locate an existing record in a file in order to delete it. In computing the act of looking for an
item is called searching (yes, really). Searching a file is a matter of reading each line and
comparing what we get to what we are looking for.
Assuming a file already exists which lists one after the other, all my favourite authors

DECLARATIONS
Variables
myauthorsfile – data type textfile
myauthor, yourauthor – data type string
found - integer
PROCESS
display “Who is your favourite author? ”
read yourauthor

open myauthorsfile as an input file

found = 0 // a flag to indicate when a match is found


while not (eof myauthorsfile ) and (found = 0) do
read myauthorsfile, myauthor
if myauthor = yourauthor then
found = 1
endif
endwhile

if found = 1 then
display “Yeah, I like that person too”
else
display “That person is not on my list”
endif

close myauthorsfile
STOP

Remember the eof marker is an invisible marker that is placed at the end of every file. When
the system reads it, it indicates that there are no more records in the file.

Note that this kind of loop must be based on 2 things :


1 - the fact that what is being searched for has not yet been found, and
2 - there are more records still in the file.

[151]
Computer Science Unit 1 Module 2

14.7
Note the following as you prepare to use files

Files are not automatic or magical. As the program designer it is up to you to decide
what will be stored and how it will be stored. You have to decide
1. how many files you need
2. what kind of data will be stored in each file
3. how the data will be laid out in each file

Having made this decision, the program should then be coded to match the file.
I recommend that you always store one piece of data per line in your files and that you
use notepad to create the files that you need. Always use simple .txt or .dat files.

While file variable names do not have to include the word file, having it helps when
reading through the program as one can then easily distinguish between memory
variables and files.

Example 3 – Random program that uses a file

PSEUDOCODE : Usefile
DECLARATIONS
Variables
datafile – text file
name, data – string

PROCESS
// CREATE A FILE AND STORE SOME DATA IN IT
open datafile for output
display “Enter name”
read name
output datafile name // store name in the file
output datafile “plan once and check twice” // store some text in the
// file
output datafile “that way everything will be nice” // store some more
close datafile // note that for ‘output’ I could have
// used display or print

// ACCESS THE SAME FILE FROM ABOVE AND DISPLAY ITS CONTENTS ON THE SCREEN
display “This is what I found in the file”
open datafile as an input file
input datafile name // read name from file
display name
input datafile data // read data from file
display data

[152]
C-A. Jardette

input datafile data // read data from file


display data
close datafile // note that for ‘input’ I could have used read
STOP

PRACTICE EXERCISE 14

1. Design a program that will create and use a disk file. The program should firstly ask you for
your personal details – name, age, and form letter (A, N, D, R, or E), and store these to a file. It
should then also store the first two lines of the national anthem to this same file. The program
should then read back your personal data from the file and display this on the screen. Finally it
should ask the user to enter a sentence and store this in the file.

[153]
Computer Science Unit 1 Module 2

[154]
C-A. Jardette

[155]
Computer Science Unit 1 Module 2

Example 4
PSEUDOCODE : Studentsys
// A program that accepts and stores data on 1 new student then displays all the students on file
// Uses a record structure

DECLARATIONS
Records
studentrecord
surname, firstname, address - data type string
age - data type integer
form - data type string
endrecord

Variables
studentfile - data type text file
Studentrec - data type studentrecord

PROCESS
// Get the data
display “Surname : ”
read studentrec.surname
display “First name : ”
read studentrec.firstname
display “Address : ”
read studentrec.address
display “Age :”
read studentrec.age
display “Form :”
read studentrec.form

//Store the information to the file


open studentfile for output
output studentfile, studentrec
close studentfile

//Display the file contents


display “Students presently enrolled -”
open studentfile as an input file

// priming read
read studentfile, studentrec
WHILE NOT EOF(studentfile) DO
display studentrec.surname
display studentrec.firstname
display studentrec.address
display studentrec.age
display studentrec.form

// get next record from file


read studentfile, studentrec
ENDWHILE

Close studentfile

STOP

[156]
C-A. Jardette

PRACTICE EXERCISE 15

1. Design a program that displays the following menu to the user:


A – Add a new order
V – View an order
Each order has the following components: name – string
date – string
description – string
amount – real
The key for each order is the name.
Orders are stored in a text file named TRANSFILE. Your solution should show your
grasp of functions, records and files.

[157]
Computer Science Unit 1 Module 2

[158]
C-A. Jardette

14.8
Given the following sample of data from a text file:

122
Byes
Michael
51 Aria Road
Kingston 8
962-5874
450.00
S
123
Hayes
Robert
22 Bee Street
Kingston 14
962-8457
480.00
M
124
Clarke
Janet
78 Hope Lane
Kingston 8
962-5526
450.00
M
125
Williams
Radisha
102 Walkers Path
Kingston 10
962-1234
500.00
S

A careful examination shows that the information is a set of records, in this case it’s a set of 4
records of people employed to an organisation. The layout of the file is:
employee id number integer
employee last name string
employee first name string
employee address line 1 string
employee address line 2 string

[159]
Computer Science Unit 1 Module 2

employee telephone number string


wages hourly rate real
marital status character

It means therefore that in coding the programmer should set up a record structure instead of
unrelated single variables. The record could be defined as :
employeerecord
idnumber - data type integer
lname, fname, address1, address2, telephonenumber - data type string
hourlyrate - data type real
maritalstatus - data type character
endrecord

Example 5
Note for the following algorithm:
- The pay record structure is a subset of the employee record, choosing to store just the
variables which are relevant for the payroll process.
- The file does not have to be passed as a parameter between functions, it is regarded as a
global variable
- Notice that the function is not obliged to use the same name for the variable as used in the
main program
- This program uses an array of records. That means that each slot in the array stores a record
instead of just a simple variable. This calls for the use of the index and the dot notation
combined.
- The text file is not sent as a parameter as it is regarded as a global variable.

Pseudocode : Payroll
// A program to process the employee file and produce the payroll information for one
// week. The data is first read from the file and the pieces of data relevant to
// this process are stored in an array of records. This array is then processed to
// produce the pay for each person for this pay period. The pay information is then
// stored in a new pay file.
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

DECLARATIONS
Constants
maxrecords = 150 // to deal with a maximum of 150 employees

[160]
C-A. Jardette

Records
addressrecord // stores the address
line1, line2 - data type string
endrecord

employeerecord // the data about one employee


empid - data type integer
emplname, empfname - data type string
address - data type addressrecord
telephonenumber - data type string
emprate - data type real
maritalstatus - data type character
endrecord

payrecord // the employee’s payroll data; will be used for output


idnumber - data type integer
name - data type string
hourlyrate, wage - data type real
endrecord

Variables
emprec - data type employeerecord // the record for one employee
payrec - data type payrecord // the pay record for one employee
empfile, // the file which stores the employee’s data
payfile - data type text file // the file which stores the pay data
paydata[maxrecords] - data type payrecord
// an array with 25 slots to store the pay records
numberofemployees - data type integer // stores the actual number of
// employees found in the file

// ---------------------------------------------------------------------------------

// main program
PROCESS
// get the employee data
getdata(numberofemployees, paydata[], emprec)

// calculate the wages


calculatepay(paydata[], numberofemployees)

// display the payroll for the week


showdata(numberofemployees, paydata[])

// store the pay data to a file


storedata(emprec, paydata[], numberofemployees)
STOP
// ----------------------------------------------------------------------------------

FUNCTION getdata ()
// Read the employee file and for each employee found, read and load up the id
// number, name and hourly rate into an array. Also record how many employees were
// found in all.

[161]
Computer Science Unit 1 Module 2

DECLARATIONS
Parameters
count - data type integer // variable parameter
paydata[] – data type payrecord // variable parameter
emprec – data type employeerecord // value parameter

PROCESS
count  0
open empfile as an input file
read empfile emprec //read the entire record in one go
while not eof(empfile) do // a valid record was read
paydata[count].idnumber  emprec.empid
paydata[count].name  emprec.empname
paydata[count].hourlyrate  emprec.emprate
count  count + 1

read empfile emprec // get another record


endwhile
close empfile
count  count - 1 // the number of records is one less than the number
// of slots
STOP
// ----------------------------------------------------------------------------------

FUNCTION calculatepay()
// Go through the array items one by one getting the user’s input for each one,
// calculating the amount due and then storing that back to the same array slot

DECLARATIONS
Parameters
paydata[] – data type payrecord // variable parameter
count – data type integer // value parameter
Variables
i - data type integer
hours - data type real // number of hours worked

PROCESS
for i  0 to count – 1 step 1 do
display “How many hours did ”, paydata[i].name, “ work? ”
read hours
paydata[i].wage  hours * paydata[i].hourlyrate
endfor
STOP
// ----------------------------------------------------------------------------------

[162]
C-A. Jardette

FUNCTION showdata()
// Display the selected fields from the contents of the array showing the pay
// for each person

DECLARATIONS
Parameters
count – data type integer // value parameter
paydata[] – data type payrecord // variable parameter

Variables
j – data type integer

PROCESS
display “Employees for this pay period”
display “Employee Name Wage”
for j  0 to count – 1 step 1 do
display paydata[j].name, “ $”, payrec[j].wage
endfor
STOP
// ----------------------------------------------------------------------------------

FUNCTION storedata()
// Take the data in the array and store it to a new file – the payroll file

DECLARATIONS
Parameters
payrec – data type payrecord // variable parameter
paydata[] – data type payrecord // value parameters
count – data type integer
Variables
k – data type integer

PROCESS
open payfile for output
for k  0 to count – 1 step 1 do
payrec.idnumber  paydata[k].idnumber
payrec.name  paydata[k].name
payrec.hourlyrate  paydata[k].hourlyrate
payrec.wage  paydata[k].wage
output payfile, payrec //store the entire record to the file
endfor
close payfile
STOP
// ---------------------------------------------------------------------------------

[163]
Computer Science Unit 1 Module 2

PRACTICE EXERCISE 16

1. Design a program which reads a file with a series of real numbers – one per line - and
finds and displays the sum and average of all the numbers in the file.

[164]
C-A. Jardette

[165]
Computer Science Unit 1 Module 2

[166]
C-A. Jardette

2. Create a function to be added to the program from number 1. This function will accept
a number from the user and searches the file for that number. If it is found it displays
‘Found’, otherwise it displays ‘Not Found’.

[167]
Computer Science Unit 1 Module 2

15. A COMPLETE PROGRAM

Here is a ‘pawdna’ scheme management program. It uses records and files, and displays the
use of a menu and functions.

// This pseudocode shows a program that manages a partner scheme.


// Each person in the partner has an account; the 'banker' is able to record when they make their
// required contributions and when they get a draw.
// Programmer : Y. Colette Lemard, November 2012
// Amended : Y. Colette Lemard, November 2014
// Amended: Y. Colette Lemard, October 2016

DECLARATIONS
Constants
onehand = 2000.00 // The amount to be deposited each week
draw = 52000 // The total amount due per hand, this is a 6 months partner
Records
accountrecord
lname, fname - data type string
numhands - data type integer
totamountpaid, totamountdrawn - data type real
lastdrawdate - data type string
endrecord
Variables
moneyfile - data type text file // stores the partner records
choice - data type character // records the user's choice

// Main Program
PROCESS
repeat
call showmenu(choice)
case choice of
'T' - call acceptmoney()
'D' - call disbursemoney()
'R' - call reportfuncton()
'X' - display "Program ending …"
otherwise - display "Invalid choice"
endcase
until ((choice = 'X') or (choice = 'x'))
STOP
//****************************************************************************************//

[168]
C-A. Jardette

FUNCTION showmenu()
//This function displays the main menu, and accepts and returns the user's choice to the calling function

DECLARATIONS
Parameters
option – data type character // variable parameter

PROCESS
display "********************************************************"
display "* *"
display "* T - Throw a hand *"
display "* D - Give a draw *"
display "* B - Check Partner Status *"
display "* X - End program *"
display "* *"
display "********************************************************"
display "Your choice : "
read option
STOP
//*******************************************************************************************//

FUNCTION acceptmoney()
// This function updates the amount paid into the partner by a participant; Assumes an existing name
// is inputted

DECLARATIONS
Variables
tempfile - data type text file
onerecord - data type accountrecord
firstname, lastname - data type string
amountpaid, outstanding, amountdue - data type real

PROCESS
// Determine who is making a payment and how much
display "Enter first and last name of payer"
read firstname, lastname
display "How much is ", firstname, " ", lastname, " paying? "
read amountpaid

[169]
Computer Science Unit 1 Module 2

// Search the file for this payer's information. Effect the change to the record by copying all unmatched
// records to a new file; and also changing and writing the matching record to this new file
open moneyfile as an input file // We will read from money file
open tempfile for output // We will write all the records to tempfile
input moneyfile, onerecord // Read first record in moneyfile
while not eof(moneyfile) do
if ((firstname = onerecord.fname) and (lastname = onerecord.lname)) then
onerecord.totamountpaid  onerecord.totamountpaid + amountpaid
amountdue  onerecord.numhands * onehand
endif
output tempfile, onerecord // Store this record to the new file
input moneyfile, onerecord // Read the next record
endwhile
close tempfle
close moneyfile

// Determine if full amount was paid


if (amountpaid < amountdue) then
outstanding  amountdue – amountpaid
display "This payment was short by $", outstanding
endif

// Restore file
copyfiles(tempfile)
STOP
//******************************************************************************************************//

FUNCTION disbursemoney()
// This function updates the system when someone has gotten a draw; Assumes a valid name
// is inputted

DECLARATIONS
Variables
firstname, lastname - data type string
hands, balancedue, amountdrawn - data type real
onerecord - data type accountrecord
tempfile - data type text file

PROCESS
// Determine who is to get the draw
display "Enter first and last name of payee"
read firstname, lastname

[170]
C-A. Jardette

// Determine how much money that person is to get


display "How many hands does ", firstname, " ", lastname, " want? "
read hands
amountdrawn  hands * onedraw

open moneyfile as an input file // We will read from money file


open tempfile for output // We will write all the records to tempfile

// Search file for payee's information. Effect the change to the record by copying all unmatched
// records to a new file; and also changing and writing the matching record to this new file
input moneyfile, onerecord // Initial read from moneyfile
while not eof(moneyfile) do
if ((firstname = onerecord.fname) and (lastname = onerecord.lname)) then
onerecord.totamountdrawn  onerecord.totamountdrawn + amountdrawn
balancedue  (onerecord.numhands * draw) – onerecord.totamountdrawn
get system date // Get today's date from the system
onerecord.lastdrawdate  systemdate
endif
output tempfile, onerecord // Store this record to the new file
input moneyfile, onerecord // Read the next input record
endwhile

close tempfle
close moneyfile
display firstname, " ", lastname,"'s balance due is $", balancedue

// Restore file
call copyfiles(tempfile)
STOP
//****************************************************************************************************//

FUNCTION copyfiles()
// This function copies the content of file1 to moneyfile creating a brand new moneyfile

DECLARATIONS
Parameters
file1 – data type text file
Variables
onerecord - data type accountrecord

[171]
Computer Science Unit 1 Module 2

PROCESS
open file1 as an input file
create a new moneyfile and open for output
input file1, onerecord // Read first record from file1
while not eof(file1) do
output moneyfile, onerecord // Store read record to moneyfile
input file1, onerecord // Read next record
endwhile
close file1
close moneyfile
STOP
//**************************************************************************************************//

FUNCTION reportfunction()
// This function displays the present status of the partner

DECLARATIONS
Variables
choice - data type character
first, last - data type string

PROCESS
display "Do you wish to see one person's record (R) or the overall balances (B)? "
read choice
if (choice = 'R') or (choice = 'r') then // user chose R
display " Whose record do you want to see?"
display "Enter first name"
read first
display "Enter last name"
read last
showonerecord(first, last)
else
if (choice = 'B') or (choice = 'b') then // user chose B
showbalance()
else
display "Invalid choice"
endif
endif
STOP
//*********************************************************************************//

[172]
C-A. Jardette

FUNCTION showonerecord()
// This function displays the present record for one person in the partner

DECLARATIONS
Parameters
firstname, lastname - data type string // variable parameters
Variables
onerecord - data type accountrecord
balance - data type real
found - data type character

PROCESS
open moneyfile as an input file
found  'F'
read moneyfile, onerecord // Initial read from moneyfile
while (not eof(moneyfile) and (found = 'F')) do
if ((firstname = onerecord.fname) and (lastname = onerecord.lname)) then
found  'T'
display "Participant : ", firstname, " ", lastname
display "Number of hands throwing : ", onerecord.numhands
display "Total paid in $", onerecord.totamountpaid
display "Total received $", onerecord.totamountdrawn
display "Date of last draw : ", onerecord.lastdrawdate
balance  onerecord.totamountdrawn – (onerecord.numhands * draw)
display "Still to be paid $", balance
else
read moneyfile, onerecord // Read the next record
endif
endwhile
close moneyfile
if (found = 'F') then
display firsname, " ", lastname, " is not in this partner."
endf
STOP
//*************************************************************************************************//

FUNCTION showbalance()
// This function displays the total amount collected and the total amount paid out

DECLARATIONS
Variables
totalcollected, totalpaidout - data type real

[173]
Computer Science Unit 1 Module 2

PROCESS
totalcollected  0
totalpaidout  0
open moneyfile as an input file
read moneyfile, onerecord
while not eof(moneyfile) do
totalcollected totalcollected + onerecord.totamountpaid
totalpaidout totalpaidout + onerecord.totamountdawn
read moneyfile, onerecord
endwhile
close moneyfile
display "Total amount collected : $", totalcollected
display " Total amount paid out : $", totalpaidout
STOP

[174]
C-A. Jardette

16. TESTING YOUR ALGORITHMS

16.1
Testing is necessary to ensure that a piece of software does exactly what it is required to do.
What a program is required to do is determined in conjunction with the user usually before
the algorithm is created. The two aims of testing are 1) verifying that the software correctly
handles valid input and 2) ensuring that the software handles invalid input properly.
During testing one seeks to :

 Ensure that the software meets the user’s functional requirements that
prompted the system in the first place.
 Identify any errors in the system.
 Determine the conditions under which the program operates best.

The term debugging is closely associated with testing and means both identifying, and
removing any semantic errors found in a program.
Testing is carried out at every stage of the software development process, from design all the
way though to implementation. It is not a random or ad-hoc affair; it must be approached
systematically and planned like all other activities related to software development. Test team
leaders develop what is called a test plan to guide the testing process.

16.2
This Test Plan is based on the program requirements and must be developed before or
independently of the development of the program. The test plan for system testing is
therefore developed after the design but before the coding, and is then used to test the final
product for correctness, performance and reliability.
A test plan specifies the process and scheduling of an application test. It documents what to
test, how to test, when to test, and who is to do the test. It contains a test plan identification
number, a brief description of the project, estimated testing start date, the actual project
testing start date, the estimated project testing end date, the actual project testing end date, the
test data to be used and how the test results are to be communicated to stakeholders.

16.3
Some Stages of Testing

 Dry runs
 Unit tests
 Integration test
 System test
 Alpha testing
 Acceptance test
 Stress test
 Beta testing

[175]
Computer Science Unit 1 Module 2

 Testing by the development team


o The first tester is the program designer in the form of the systems analyst or the
software engineer or even the programmer. They test the algorithm before it is
converted to program code. This kind of test is called dry runs or desk checks.
Trace Tables are an important tool used for desk checks. If the proposed
algorithm passes the test it is passed on the programming team.
o Unit testing - Having coded the program, the programmer must test it to see
that it works properly. Usually each programmer works on one or more
modules and they are responsible for testing that module when they have
created it. Programmers test their work for both syntax and semantic errors
and it is their job to completely remove all such errors that they detect. Where
a software house has an in-house testing team, completed programming
modules can also be passed on to them for further testing.
o While modules are programmed independently of each other and are then
tested as individual units, they must be brought together into an overall
software product. Before delivery to the user, integration testing must be done
to make sure that the sub-modules work smoothly together to give a complete
and correct solution. Modules which work perfectly well as individual units
may not do as well when integrated. Integration tests are done as each module
is added one by one.
o When all the modules have been incorporated a complete package is created.
This package needs to be tested as well. The development team will now test
the system as if they are the actual users putting it through its paces. They will
use real live data and will also put several users on at the same time to simulate
live conditions. This is called system testing.

Desk checks

Unit tests

Integration tests

System test

Fig. 1 - Types of tests done by the software development team

[176]
C-A. Jardette

 User/User Representative Testing


o Alpha testing is testing carried out internally to an organisation but done by a
set of potential users or an independent test team. The feedback from alpha
testing is very important as frequently people who are too near to a project or
who have their professional reputations at stake on a project, will fail to see the
flaws in the system. Independent testers are less concerned about hurting
people’s feelings and so are better able to find and point out errors.
o At this point though the user needs to see the system and verify that it does
exactly what he wants before he accepts it as complete and correct. The testing
done by the team of user representatives is called acceptance testing.
Acceptance testing is the formal testing with respect to users’ needs,
requirements, and business processes, conducted to determine whether or not a
system satisfies the acceptance criteria and to enable the user or designated
representative to decide whether or not to accept the system as offered.
o When the user verifies that the system does what they require it to do, how
they want it to do it, the team may still choose to do another set of test – the
stress test. In a stress test the system is employed at its maximum, with the
maximum number of concurrent users carrying out the most difficult and
processor intensive functions all the same time. This helps to determine how
hardy the system is / how it will stand up under the pressures of day to day
operations.
o Where a system was not commissioned by a particular user but was designed
to be marketed to the general public, instead of acceptance testing that software
houses may choose to conduct beta testing at this stage. Beta testing is
operational testing by potential or existing customers at an external site not
associated with the developers to determine whether or not the system satisfies
customers’ needs. This is a form of external acceptance testing for off-the-shelf
software to get feedback from the marketplace.

Alpha testing

Acceptance testing Beta testing

Stress test

Fig. 2 - User testing

[177]
Computer Science Unit 1 Module 2

16.4 Some Testing Techniques

 White box testing


o Also called glass-box testing, logic-driven testing or design-based testing.
o Based on specific knowledge and attention to the structure of the software under test.
The intention is to exhaust all aspects of the software by executing each line of code at
least once (statement coverage), traversing every branch statements (branch coverage),
and covering all the possible combinations of true and false condition predicates.
o Test cases are carefully selected based on the criterion that all the nodes or paths must
be covered or traversed at least once. By doing so we may discover unnecessary "dead"
code -- code that is of no use, or never get executed at all, which can not be discovered
by functional (black box) testing.
o Generally carried out by programmers and other development staff.

Code
Input Expected
prompts
data output
output statements
selection statements
loops

Fig. 3 - White Box Testing

 Black box testing


o A testing method in which test data are derived from the specified functional
requirements without regard to the program structure.
o Also termed data-driven, input/output driven, or requirements-based testing.
o Only the functionality of the software module is of concern, this testing method
emphasizes executing the functions and examination of their input and output data.
o The tester treats the software being tested as a black box -- only the inputs, outputs and
specification are visible, and the functionality is determined by observing the outputs
to corresponding inputs.
o In testing, various inputs are exercised and the outputs are compared against
specification to validate the correctness. All test cases are derived from the
specification.
o No implementation details of the code are considered.
o Generally carried out by users and potential users

input Expected
data output

Fig. 4 - Black Box Testing

[178]
C-A. Jardette

16.5
A Trace Table is a rectangular array of rows and columns in which the columns represent the
variables in an algorithm and each row reflects the state of the variables. The state of an
algorithm refers to the contents of the variable at any point in time. Trace Tables allow
developers to test their algorithms in a dry run, to make sure that they contain no logic errors
before they go to the trouble of coding something that does not work.
In a dry run appropriate test data is used to execute the algorithm line by line until it
terminates. At that point the results are compared to what is known to be correct results. If
there is a discrepancy, the algorithm is fixed and tested again.

Example 1 - Imagine that we have the following algorithm and we would like to know how it
handles the following input data: 2, 9, 5.

Example 1 - Algorithm
1 SET Secret TO 5
2 DISPLAY “Type your guess”
3 READ guess
4 WHILE Guess <> Secret DO
5 IF Guess < Secret THEN
6 DISPLAY "Too low"
7 ELSE
8 DISPLAY "Too High"
9 ENDIF
10 DISPLAY “Guess again”
11 READ guess
12 ENDWHILE
13 DISPLAY "You guessed it"

Trace Table
Within the trace table, each variable, conditional test and output should be listed. It is not
necessary to include prompts, however. In this case, the variables secret and guess are listed,
as well, the results of the conditions Guess <> Secret and Guess < Secret are determined.

Line # Secret Guess Guess <> Secret Guess < Secret Output

1 5

3 2

4 True

5 True

6 Too Low

11 9

[179]
Computer Science Unit 1 Module 2

Line # Secret Guess Guess <> Secret Guess < Secret Output

4 True

5 False

8 Too High

11 5

4 False

13 You guessed it

Example 2 - Create the Trace Table for the following algorithm


1 initalize x to 0, y to 5, z to 25
2 while x <= 4 do the following
2a set y to z - y,
2b set a to x + 1,
2c and then increment x by 1
2d if (a > 1) then
2e set z to z – 5
2f let a equal a * a,
2g and then set b to z – y
2h endif
2i endwhile
3 display a, b, x, y, z

Trace Table

Line # a b x y z x <= 4 a>1 Output

1 0 5 25
2 True
2a 20
2b 1
2c 1
2d False
2 True
2a 5
2b 2
2c 2
2d True
2e 20
2f 4
2g 20
2 True
2a 15
2b 3

[180]
C-A. Jardette

2c 3
2d True
2e 15
2f 9
2g 0
2 True
2a 0
2b 4
2c 4
2d True
2e 10
2f 16
2g 10
2 True
2a 10
2b 5
2c 5
2d True
2e 5
2f 25
2g -5
2 False
3 25 -5 5 10 5

PRACTICE EXERCISE 13

Determine the output of the following algorithm when a contains the value 0.

1 enter a
2 while a <= 3 do the following
2a increment a by 0.1
2b if a <> 0.3 then
2bi set S and X to 0
2bii set T to 1
2biii while T <= 6 do
2biii(a) add 2 to X
2biii(b) increment T by 2
2biv endwhile
2c else
2ci set T to 0, X to 1 and S =33 * S
2cii while T <= 5 do the following
2cii(a) increment T by 1
2cii(b) set X = X * T
2d endif
2e endwhile
3 display a, S, X

[181]
Computer Science Unit 1 Module 2

Trace Table

[182]
C-A. Jardette

[183]
Computer Science Unit 1 Module 2

1. What is the output of the following if the input is Miss Brown, 25, Mr Clarke, 22, Mrs
Jones, 28,
Mr Williams, 19

Most  0
For Teacher  1 to 4 do
Print "Enter the teacher’s name"
Input Tname
Print "Enter the number of students for said teacher"
Input Tamt
If Tamt > Most then
Most  Tamt
Teachername  Tname
Endif
endfor
Print "The teacher with the most students is", Teachername
Print "The teacher has”, Most, “ students"

Trace Table

[184]
C-A. Jardette

WORKSHEET 6 - TRACE TABLES

1. Construct a trace table for the following algorithm; use x = 4 for testing

Read X
For M  1 to X do
Y  X - M
Z  5 * Y - M
Endfor
Print Z

2. Construct a trace table for the following;

X  5
K  10
SUM  45
While SUM < 75 do
SUM  SUM + K
Print K
KK+X
Endwhile
Print Sum

3. What is printed by the following snippet of algorithm when n =5?

if (n=1) or (n=20) then


H1
else
f1
g1
for j = 1 to n -2 do
hf+g
f g
gh
print h
endfor
endif
print f, g

4. What is printed by the following algorithm?

count  1
x2
while count < 25
xx+2
print count, x
count  count + 5
endwhile

[185]
Computer Science Unit 1 Module 2

5. Create a trace table for the following and also state what is printed by the algorithm

set a to 3
set b to5
set sum to 1
while (a <= 5) do
let a equal a + b
let b equal b + a
let sum equal sum + b
endwhile
print sum

6. Use s = 4 and t =4, 6, 3 and 5 to complete a trace table for the following:

tot  0
read s
for p  1 to 5 do
read t
if (t > 5) then
Qp*t
else
if (t <= 5) and (t > 3) then
Qp*t+2
else
Qp*4
endif
endif
tot  tot + t
endfor

7. Trace the following algorithm using the number 5

PRINT “Enter a number “


READ number
triangular_value  0
FOR value FROM 1 TO number DO
triangular_value  triangular_value + value
ENDFOR
PRINT triangular_value

8. Trace the following algorithm below using 6, 5, 2, 1, 89

Numcount  0
Sum  0
Largest  0
Read Number
While Number not equal to 0 do
Sum  Sum + Number

[186]
C-A. Jardette

Numcount  Numcount + 1
If Number > Largest
Largest  Number
Endif
Read Number
Endwhile
Average  Sum/Numcount
Print Average, Largest

9. Trace the following using 7, 0, 0, 1, 20, 12, 0, 15

Input N
COUNT  0
NONCOUNT  0
ZEROCOUNT  0
Repeat
Input Number
if Number = 0 then
ZEROCOUNT  ZEROCOUNT + 1
endif
if Number <> 0 then
NONCOUNT  NONCOUNT + 1
endif
COUNT  COUNT + 1
Until COUNT = N
Print ZEROCOUNT, NONCOUNT

10. Oldage  0
For j  1 to 10 do
Read Name, Age
If Age > Oldage then
Oldage  Age
Oldperson  Name
Endif
Endfor
print "The oldest person is". Oldperson

What is the output of the above if the input is Joan, 12, Peter, 6, Karen, 34?

[187]
Computer Science Unit 1 Module 2

16.6 Testing Glossary

ADDITIONAL
TERM MEANING REMARKS

Acceptance A set of conditions that a system needs to meet in order to


criteria be accepted by end users.

Acceptance Testing conducted to enable a user/customer to determine


Testing whether to accept a software product. Normally performed
to validate that the software meets a set of criteria which
were agreed at the beginning of the project.
Accuracy The capability of a software product to provide agreed and
correct output with the required degree of precision.
Actual result The behaviour or response of a software application that
you observe when you execute the steps in a test case.
Alpha test The initial trial run of a new program, system or hardware
within the organisation that developed it.
Beta test - The first public test of a new program, system or
hardware, under controlled conditions with selected users.
- Testing of a pre-release of a software product by
prospective customers.
Black box Testing which takes an external perspective of the test
testing object to derive test cases. The test designer selects valid
and invalid inputs and determines the correct output.
There is no knowledge of the program’s internal structure.
Branch Testing Testing in which all branches in the program source code
must be traversed/tested at least once.
Bug A fault in a program which causes the program to perform
in an unintended or unanticipated manner.
Component The smallest software item that can be tested in isolation
Component Testing of pieces of code which are separable; Also called
testing module or unit testing.
Debugging The process of finding, analyzing, and removing causes of
failure in a software product.
Desk check A formal testing technique where the algorithm/source Also called code
code is traced by a group with a small set of test cases, walkthrough
while the state of program variables is manually
monitored, to analyze the programmer's logic and
assumptions.
Dry run To do a desk check.
Exhaustive All possible combinations of input values and
testing preconditions are tested.

[188]
C-A. Jardette

Failure Deviation of a software system from its expected delivery,


services, or results.
Integration Combining components or systems into larger structural
units or subsystems.
Integration The phase in software testing in which individual software It occurs after unit
testing modules are combined and tested as a group. testing and before
system testing.
Semantic error Failure of a program or section of a program to perform as See bug
expected
Stress test Testing conducted to evaluate a system or component at or
beyond the limits of its specified requirements to
determine the load under which it fails and how it fails.
Often this is performance testing using a very high level of
simulated load.
Syntax error An error which prevents a program from compiling
/running and results from the violation of the rules of the
language.
System test Testing conducted on a complete, integrated system to System testing
evaluate the system's compliance with its specified falls uses black
standards/requirements. box testing, and
requires no
knowledge of the
inner design of the
code or logic.
Test case - A commonly used term for a specific test. This is usually
the smallest unit of testing. A Test Case will consist of
information such as requirements testing, test steps,
verification steps, prerequisites, outputs, and the test
environment.
- A set of inputs, execution preconditions, and expected
outcomes developed for a particular objective, such as to
exercise a particular program path or to verify compliance
with a specific requirement.
Test data A set of carefully chosen data developed specifically to test
the adequacy of a computer run or system; the data may be
actual data that has been taken from previous operations,
or artificial data created for this purpose.
Test Plan A document describing the scope, approach, resources, and
schedule of intended testing activities. It identifies test
items, the features to be tested, the testing tasks, who will
do each task, and any risks requiring contingency
planning.

[189]
Computer Science Unit 1 Module 2

Testing - The process of exercising software to verify that it satisfies


specified requirements and to detect errors.
- The process of analyzing a software item to detect the
differences between existing and required conditions (that
is, bugs), and to evaluate the features of the software item
- The process of operating a system or component under
specified conditions, observing or recording the results,
and making an evaluation of some aspect of the system or
component.
Trace table A technique used to test algorithms, in order to make sure Trace tables are
that no logical errors occur whilst the algorithm is being typically used in
processed. The table usually takes the form of a multi- schools and
column, multi-row table; With each column showing a colleges when
variable, and each row showing each value inputted into teaching students
the algorithm and the subsequent values of the variables as how to program,
execution progresses, one row per step. they can be an
essential tool in
They can be useful for debugging applications, using a teaching students
trace table can help a programmer easily detect what error how a certain
is occurring, and why it may be occurring. algorithm works
and the systematic
process that is
occurring when
the algorithm is
executed.

Unit Smallest testable part of a program See component

Unit Test A software verification and validation method in which a


programmer tests if individual units of source code are fit
for use. A unit is the smallest testable part of an
application. In procedural programming a unit may be an
individual function or procedure.
White box Testing based on an analysis of internal workings and Includes
testing structure of a piece of software. techniques such as
Branch Testing
and Path Testing.

[190]
C-A. Jardette

17. DETERMINING OUTPUT

For the most part, when we want to find out what a fragment of code will output we use a
Trace Table to trace the contents of the variables. On occasion though when we examine the
algorithm in question we may find that it does not consists so much of changing variable
states but is instead, output intensive.

Example: Given that lines has the value 7, and display (\newline) means to move the cursor
down to the start of the next line, what is the output of the following pseudocode fragment?

Variables
row, c, lines, temp – data type integer Output

Process *
read lines ***
temp  lines *****
for row  1 to lines do *******
for c  1 to (2 * row - 1) do *********
display “ “ ***********
endfor *************
***************
temp  temp - 1

for c  1 to (2 * row - 1) do
display “*”
endfor

display(\newline)
endfor
STOP

A Trace Table was not necessary here as we are not testing the code for correctness. What is
being asked is for us to determine the objective of the code, and here it is to produce an
isosceles triangle. You will find though that as you work through the algorithm you will need
to keep a check of the value in the variables .

[191]
Computer Science Unit 1 Module 2

Here is another example, note that print \n means go to a new line :

Variables
n, c, k, space, count - data type integer

PROCESS
count = 1
n = space = 4

for c  1 to n do
for k  1 to (space – 1) do
print " "
endfor

for k  1 to c do
print "*"
if (c > 1) and (count < c) then
print "A"
count  count + 1
endif
endfor

print "\n"
space  space -1
count  1
endfor

Output

*
*A*
*A*A*
*A*A*A*

[192]
C-A. Jardette

PROGRAMMING GLOSSARY

Abort : to stop a program abruptly before it has executed to its natural end

Ada : a programming language invented in the early 1980s as part of a US


Government sponsored competition for a new standard language. It was
named after Countess Ada Lovelace, the daughter of the poet Lord Byron.
She designed the first program. Ada is similar to Pascal, for instance
employing begin.. end to mark blocks of code rather than the curly braces { }
used in C, C++ and C#. It is now used mostly in the military and safety-critical
areas such as aviation flight control systems, nuclear power stations and some
medical equipment but has not been a success in other commercial software
sectors.

Algorithm : a set of clear, detailed, ordered and complete steps which describes the
process necessary from start to finish in order to produce the solution to a
problem.

Array : a data structure which holds multiple values of the same data type

Assembly language : a low level programming language using mnemonics to allow readable
instructions of the CPU. On PCs, the assembly language may look like this
MOV ebx, eax
MOV esi, 66
MOV [edx+ebx*4+4], ecx
MOV [ebx], ah

To understand it you need to know that eax, ebx etc are each a 32 bit register
inside the CPU. The MOV instructions just copies the value so the first line
E.G. is pretty much the same as this C code ebx = eax;

To compile this into machine code, you need an assembler. It's just a compiler
for assembly language. Many compilers can output the assembly language
equivalent of code in C or C++.
The problem with assembly language is that it requires a high level of
technical knowledge, and it's slow to write. In the same time that you take to
write ten lines of assembly language- that's ten instructions, you could write
ten lines of C++, perhaps the equivalent of 500 instructions!

Bells and whistles : those fancy features provided by an application. Typically, the term
refers to features that are needed only in special cases or to features that
make the program more visibly attractive. The term can be used either
favorably or negatively.

[193]
Computer Science Unit 1 Module 2

Beta : beta describes the state of an application during its development, when it has
almost full functionality and is still being tested (usually by potential users).

Beta test : the computer system test prior to commercial release. Beta testing is the last
stage of testing, and normally can involve sending the product to beta test
sites outside the company for real-world exposure or offering the product for
a free trial download over the Internet.

Bug : an error, failure, mistake or flaw in a computer program that causes it to not
operate as intended a.k.a. semantic/logic error. Bugs often times result from
poor/insufficient testing. Bugs arise from mistakes and errors, made by
people, in either a program's source code or its design

Bytecode : the compiled code that compilers for Java and C# produce. It isn't true
machine code but a simpler code made up of instructions that are one byte
long.

C : a general-purpose, procedural, imperative computer programming language


developed in the early 1970s by Dennis Ritchie for use on the Unix
operating system which was its very first application. C has since spread to
many other operating systems. Although originally designed as a systems’
programming language, C has proved to be a powerful and flexible language
that can be used for a variety of applications, from business programs to
engineering. C is a particularly popular language for personal computer
programmers because it is relatively small -- it requires less memory than
other languages.

C++ : C++ is a programming language invented by Bjarne Stroustrup in the early


1980s as a way to add Object Oriented Programming to C. It is the main
development language on Win 32 and Unix systems but is starting to be
replaced on .NET by C#.

Casting (a variable) : reassigning the type of a variable. When casting a variable from one type to
another, you tell the computer to use a different type to store the variable.
For example, you declared a variable of type int. In most cases, that would
mean that the largest positive value you could store would be 32,767. But
somewhere in your program, you realize that you're going to have to do a
calculation which could increase the value over this maximum. In this case,
you need to perform casting variable.

Code : noun – program statements


verb – to create program statements

[194]
C-A. Jardette

Compiler : a type of computer program that translates source code into object code stored
in a file. A compiler is likely to perform many or all of the following
operations: preprocessing, lexing, parsing, semantic analysis, code
optimizations, and code generation.

Compile : invoke the compiler for a program

Constant : a value of any type that has the same value throughout a program run and
can not be changed.

Control Statements : elements in source code that control the flow of program execution. The three
main ones are sequencing, selection and iteration. There is also recursion.

Debugger : a computer program that lets you run your program, line by line and examine
the values of variables or look at values passed into functions and let you
figure out why it isn't running the way you expected it to.
Compilers can be configured to produce debug information when you
compile your program. This information is used by the debugger so you can
view the source code not the machine code, as you debug,.

Editor : a program much like a word-processor that you use to edit the source code of
any program you write. It allows entry of plain unformatted text.
Most IDEs come with a built in editor and some will automatically highlight
compile errors in the editor to simplify fixing them.

Execute : to run a program

Function : a routine or sub-module in a program that performs a particular task and


sends back a result

Functional programming : a programming paradigm that conceives computation as the evaluation of


mathematical functions and avoids state and mutable data. It emphasizes the
application of functions, in contrast to imperative programming, which
emphasizes changes in state and the execution of sequential commands.
Often considered important in functional programming are higher-order and
first-class functions, closures, and recursion.

Identifier : a name for a variable, type, type member, template, class, function, etc and is
usually limited to letters, digits and underscores. Certain words are reserved
and cannot be used as identifiers e.g. if.

[195]
Computer Science Unit 1 Module 2

Interpreter : a system program that translates program statements one by one and
executes the statement immediately after translation. An interpreter runs
until the program ends or until it encounters an error while translating

Logic error : when the program compiles as expected, but runs in an unexpected way
or gives an incorrect result. Same as semantic error

Machine language : instructions for a computer processor in some machine language (each type
of processor may have its own machine language).

Also called machine code, it is the name for the Instructions that a CPU can
execute. It's rather difficult to read as it is just numbers in memory. There are
programs that can convert the numbers back into assembly language.
Compilers generate machine code from your C source code.

Object code : the code produced by a compiler/interpreter from the source code, usually
in the form of machine language that a computer can execute directly;
(occasionally in assembly language).

Pass by Reference / Pass by Address


: Pass by Reference passes in a reference to a variable - this is effectively the
address of the variable into the function. This allows the function to change
the variable directly.

Pass by Value / Pass by Copy


: when a variable is used as a parameter to a function this makes a copy of the
variable and sends the copy to the function. The function can not make any
permanent changes to the value of the variable.

Preprocessing : when creating C applications, you can include constants, macros and files.
The preprocessor is a separate stage that happens just before the compilation.
The preprocessor converts and cleans up the code prior to compiling so that
what is actually compiled is a processed version of the source code.

Procedure : a block of code that performs a single task. It is a building block of a


computer program but is a somewhat old fashioned phrase as nowadays
computer languages use functions not procedures.

Program : a set of detailed instructions (written in what is known as a


programming language) intended for a computer to use to accomplish
a task.

[196]
C-A. Jardette

Programming language : an artificial language used to write instructions (for a computer) that can
be then translated into machine language and executed by the computer.

Run-time error : an error in a computer program that is not detected until the program is
executed, at which point it then causes processing to cease or be incorrect.

Scope : refers to identifiers (types, functions, classes and variables) and means that
part of the source code where the particular identifier is visible.

Source code : any series of statements written in some human-readable computer


programming language

Statement : a block of code that does something. An assignment statement for example
puts a value into a variable. A for statement performs a loop.
In C, statements can be grouped together as one statement using curly
brackets forming a block.
{
statement1;
statement2;
}

Syntax : the rules of a programming language

Syntax error : an error in a program that results from violation of the rules of the
language about how statements are to be formed

Translate : to change from human readable form into machine language form so that
the computer can understand it

Virtual Machine : simulation of a computer running within a computer. Although slightly


slower than running pure machine code, this offers greater portability as well
as robustness and reliability.

Void : the value of a function type that means nothing is returned, or o parameters to
be passed.

[197]
Computer Science Unit 1 Module 2

[198]

You might also like