2021 Computer Science Problem-Solving Module Coursebook Student
2021 Computer Science Problem-Solving Module Coursebook Student
Jardette
MODULE OBJECTIVES
[1]
Computer Science Unit 1 Module 2
CONTENTS
Section/Topic Page
1. Introduction ...................................................................................................................... 4
7. Flowcharts ........................................................................................................................ 34
8. Simple Algorithms........................................................................................................... 36
If ....................................................................................................................................... 51
Case ................................................................................................................................. 66
[2]
C-A. Jardette
Worksheets
5. Arrays................................................................................................................................ 143
[3]
Computer Science Unit 1 Module 2
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?
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
[5]
Computer Science Unit 1 Module 2
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.
[6]
C-A. Jardette
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.
[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.
Interviews
Surveys/questionnaires
Observation
Examining documentation and policies
[8]
C-A. Jardette
[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.
[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
[12]
C-A. Jardette
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
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.
[14]
C-A. Jardette
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.
[15]
Computer Science Unit 1 Module 2
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
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
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.
[17]
Computer Science Unit 1 Module 2
NOTES
[18]
C-A. Jardette
PS. Not all problems have algorithms, as not all problems have a solution
[19]
Computer Science Unit 1 Module 2
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.
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.
[20]
C-A. Jardette
[21]
Computer Science Unit 1 Module 2
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
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.
[23]
Computer Science Unit 1 Module 2
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.
[24]
C-A. Jardette
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.
[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,
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.
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:
repeat
statements to be repeated
until (conditional expression)
[31]
Computer Science Unit 1 Module 2
PRACTICE EXERCISE 2
[32]
C-A. Jardette
6. Distinguish between the usage and operation of while loops and repeat until loops.
[33]
Computer Science Unit 1 Module 2
7. FLOWCHARTS
[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.
[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
DECLARATIONS START
Variables
prod, sum, num1, num2, num3 – data type real
Note:
read num3
// indicates an inline comment
is the assignment symbol, read
it as ‘is assigned the value’ sum num1 + num2 + num3
[36]
C-A. Jardette
8.2 Design a program that finds the area of a triangle given its base.
Solution
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
// show result
display “The area of that triangle is ”, area
read height
STOP
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
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
STOP
[38]
C-A. Jardette
8.4 Design a program that acts as a robot having a simple conversation with the user.
Solution
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
read age
dif age - 5
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
Flowchart : PhoneBill
START
[40]
C-A. Jardette
read localmins
read farmins
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
Flowchart : SwitchValues
START
[42]
C-A. Jardette
temp val1
val1 val2
val2 temp
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 commission
comision total * crate
//display results
display ‘The coach is due to get $”, commission
STOP
Flowchart : Athlete
START
read first
read second
[44]
C-A. Jardette
read third
STOP
[45]
Computer Science Unit 1 Module 2
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:
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
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
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
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
read choice
Y (choice = ‘C’) or N
A B
(choice = ‘c’) ?
[52]
C-A. Jardette
A B
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
[53]
Computer Science Unit 1 Module 2
Flowchart : Interest
START
read balance
newbalance balance
STOP
[54]
C-A. Jardette
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
Flowchart: Greaterthan
START
[55]
Computer Science Unit 1 Module 2
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
[57]
Computer Science Unit 1 Module 2
Flowchart : TaxAndPay
START
read status
read numkids
read money
[58]
C-A. Jardette
depend > 2?
N Y
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
Flowchart : TollToll
START
[60]
C-A. Jardette
read cartype
N cartype = ‘C’ ? Y
cartype = ‘S’ ?
N
display “Toll : $300.00”
Y
cartype = ‘B’ ?
B Y N
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
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.
CASE expression OF
condition 1 - sequence 1
condition 2 - sequence 2
...
condition n - sequence n
OTHERWISE - default sequence // this is optional
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
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
Flowchart: ParishCaps
START
Display “Kingston –1
St. Andrew –2
St. Thomas –3
St. Ann –4
Hanover – 5”
[68]
C-A. Jardette
read parishnum
parishnum?
=1 =2 =3 =4 =5 otherwise
display “Half-Way- A
A
Tree”
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
read monthum
monthnum?
STOP
[70]
C-A. Jardette
PRACTICE EXERCISE 6
[71]
Computer Science Unit 1 Module 2
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.
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
Solution
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
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
Flowchart: GuessingGame
START
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
Flowchart: PassorFail
START
read mark
[76]
C-A. Jardette
mark > 0 ?
N
Y
N Y
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
Flowchart : Accumulating
START
total 0
read numb
numb = 9999 ?
Y
N
A
total total + numb
read numb
[78]
C-A. Jardette
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
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
read number
number = 0 ?
Y
N
number > 0 ?
N Y
read number
STOP
[80]
C-A. Jardette
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’
Flowchart : Purchases
START
totalcost 0.00
response ‘Y’
A response = ‘Y’ ?
N
[81]
Computer Science Unit 1 Module 2
read itemcost
read itemquantity
read response C
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
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.
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.
[87]
Computer Science Unit 1 Module 2
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)
Flowchart : GuessingGame
START
read guess
guess = 21 ? N
display “‘congrats”
[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 “Goodbye”
STOP
Pseudocode : KeepAdding
START
[89]
Computer Science Unit 1 Module 2
read continue
continue = ‘Y’? B
Y
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
Flowchart : Tollagain
START
read vehicletype
vehicletype = ‘C’ ?
N Y
A B C
[91]
Computer Science Unit 1 Module 2
vehicletype = ‘T’
N Y
display “Unrecognizable
vehicle”
B
E
E C
read answer
answer = ‘Y’? D
Y
[92]
C-A. Jardette
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
read limit
count 1
display count
count count + 1
[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
read option
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
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
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.
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.
[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.
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
[101]
Computer Science Unit 1 Module 2
Flowchart : GreetAll
START
read max
count 1
read name
count count + 1
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 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
read limit
count 1
read num
count count + 1
total total + num
N
num > largest?
highest num
[104]
C-A. Jardette
limit = 0?
Y
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
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
Flowchart : MarkForm
START
sum 0
count 1
read mark
[106]
C-A. Jardette
mark?
display “Fail”
display “A” display “C”
C
C C
N Y
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
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
Flowchart : WeeklyWages
START
set totalwages to 0 A
[108]
C-A. Jardette
i1
weekwage 0
j1
jj+1
read hours
ii+1
j < 5
display weekwages
i < numemployees?
[109]
Computer Science Unit 1 Module 2
PRACTICE EXERCISE 9
[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
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.
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
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.
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
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
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
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.
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 –
[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
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
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
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
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
[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.
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
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
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
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.
The FOR LOOP is usually the best choice for accessing all the elements of an array.
[132]
C-A. Jardette
PRACTICE EXERCISE 11
2. To store the marks received by each girl in this class for Computer Science for the
Christmas term
[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
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
62
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
[135]
Computer Science Unit 1 Module 2
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
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
[136]
C-A. Jardette
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
// 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
[137]
Computer Science Unit 1 Module 2
endfor
for j 0 to 4 step 1 do
display listtwo[j], “ ”
endfor
PRACTICE EXERCISE 12
[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.
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
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
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
[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
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
[146]
C-A. Jardette
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
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
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
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
[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
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.
[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.
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
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
// 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
Close studentfile
STOP
[156]
C-A. Jardette
PRACTICE EXERCISE 15
[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
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
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)
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
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
Here is a ‘pawdna’ scheme management program. It uses records and files, and displays the
use of a menu and functions.
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
// 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
// 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.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
Desk checks
Unit tests
Integration tests
System test
[176]
C-A. Jardette
Alpha testing
Stress test
[177]
Computer Science Unit 1 Module 2
Code
Input Expected
prompts
data output
output statements
selection statements
loops
input Expected
data output
[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
Trace Table
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
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
X 5
K 10
SUM 45
While SUM < 75 do
SUM SUM + K
Print K
KK+X
Endwhile
Print Sum
count 1
x2
while count < 25
xx+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
Qp*t
else
if (t <= 5) and (t > 3) then
Qp*t+2
else
Qp*4
endif
endif
tot tot + t
endfor
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
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
ADDITIONAL
TERM MEANING REMARKS
[188]
C-A. Jardette
[189]
Computer Science Unit 1 Module 2
[190]
C-A. Jardette
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
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
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.
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.
[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.
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.
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).
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.
[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.
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 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
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]