Professional Documents
Culture Documents
Notes Paper 2
Notes Paper 2
Compiled by:
Farhan Rahmat
Index
- Structure Diagram
- Algorithm
- Flowchart
o Common flow chart symbols
algorithms and flowcharts
Introduction to pseudocode
- Command/Statement for use and
declaration of:
o Variable and constant
pseudocode
Programming Concepts
o Role of Assemblers
o Role of Compiler
o Role of Interpreter
Unit-8 - Structure of a computer programs
o Data types and their declaration
o Iteration, selection, counting and
totaling
o Use of predefined procedures and
functions
- Arrays
o Declaration of array
o Index of array
o Reading values into array
Past paper questions
Introduction to databases
- Ranges of databases
- Data types
- Record structure
Databases
Top-down design is when a problem is split into smaller sub-problems, which themselves are
split into even smaller sub-problems until each is just one element of the final program.
Structure diagrams
Stepwise refinement
Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 2|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat
2.1 (e) produce algorithms to solve problems using both a program flowchart and
pseudocode
2.1 (f) understand algorithms presented in the form of program flowcharts and
pseudocode
Algorithm
Program flowchart
Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 3|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat
Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 4|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat
Pseudo-code
BEGIN
INPUT CardNumber
REPEAT
INPUT PIN
END IF
INPUT Amount
Dispense Cash
ELSE
END IF
END
• Efficiency
• Correctness
• Appropriateness
Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 5|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat
Efficiency
Correctness
Although an algorithm is expected to produce the correct outputs, correctness can still be
measured
in terms of:
• accuracy – how many decimal places Produce output with greater accuracy – e.g.
more decimal places;
• range – will the algorithm work with the complete range of inputs, or can it only deal
with positive numbers, whole numbers, numbers below 1 million, etc.
• reliability – will the algorithm always produce correct output within the range that it is
designed to work, or are there values which it will not accept (zero, for example).
Appropriateness
• length – if the problem is simple then a short algorithm would normally be expected;
• speed – if the output needs to be generated quickly, then the algorithm must be
able to complete quickly;
• memory requirements – an algorithm controlling a washing machine must not have
the need for a lot of memory!
Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 6|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat
Flow Charts
Introduction
This section covers the use of flow diagrams (charts) in the production of algorithms.
Systems flowcharts are different and these are covered in a different section (Systems
analysis).
Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 7|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat
Assignment
An assignment is an instruction in a program that places a value into a specified variable.
Some typical assignments are:
TheLength 20.5
TheUsersName$ “Charlie”
TheAreaTheWidth * TheLength
TotalCostLabelledCost + 15
Counter Counter + 1
Note that the last example is a common method used to increment the value of a
variable. It could be read as:
Powers
Division
A result of a division such as 17 ÷ 4 can be expressed either as a real (4.25) or as two
integers(4 remainder 1).
The integer method, in most programming languages, uses the operators DIV and MOD.
Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 8|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat
Relational operators are used in the format: [Expression] [Operator] [Expression] and will
always return a Boolean (True or False) value.
Relational operators are typically used with the IF selection and also within conditional
loops
(REPEAT-UNTIL or WHILE-WEND).
In the following table, the variables a and name$ have the following assignments:
a3+5
name$ “JAMES”
Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 9|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat
AND and OR
The AND and OR operators always return a Boolean result and are used in the format:
The following „truth‟ table summarises the result of the Boolean operations:
Values Results
NOT
The NOT operator reverses the result of the Boolean expression and is used in the format:
NOT [Boolean]
Validation
Presence check
Code can be added to check that a particular control has not been left empty or un-
checked:
Is
No Yes You have not
Username = “”
entered a
?
Username”)
Range check
Code can be added to check that a particular control has a value between an allowed
maximum and minimum:
Length check
Code can be added to check that a particular control has a value between an allowed
maximum and minimum:
The password
Is
No Yes that you have
Len(Password)> 12
entered is too
?
long
2.1 Example 1
A town contains 5000 houses. Each house owner must pay tax based on the value of the
house. Houses over $200 000 pay 2% of their value in tax, houses over $100 000 pay 1.5% of
their value in tax and houses over $50 000 pay 1% of their value in tax. All others pay no tax.
Write an algorithm to solve this problem in the form of a flowchart.
2.2 Example 2
The following formula is used to calculate n: n = (x * x)/(1 – x). The value x = 0 is used to stop
the algorithm. The calculation is repeated using values of x until the value x = 0 is input.
There is also a need to check for error conditions. The values of n and x should be output.
Write an algorithm to show this repeated calculation in the form of a flowchart.
2.3 Example 3
Write an algorithm in the form of a flowchart which takes temperatures input over a 100
day period (once per day) and outputs the number of days when the temperature was
below 20C and the number of days when the temperature was 20C and above.
2.4 Example 4
Write an algorithm in the form of a flowchart which:
2.5 Example 5
A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code.
All books have a code starting with 1, all maps have a code starting with 2 and all
magazines have a code starting with 3. The code 9999 is used to end the algorithm.
Write an algorithm in the form of a flowchart which inputs the codes for all items in stock
and outputs the number of books, number of maps and the number of magazines in stock.
Include any validation checks needed.
• determine the output for a known set of data to check it carries out the task
correctly
• check on the logic of the algorithm
• determine the function of the algorithm
• When dry running a flowchart it is advisable to draw up a trace table showing how
variables change their values at each stage in the algorithm. The advantages of
doing this are:
• if you make a mistake, it is easier to back track to where the error occurred rather
than starting from the beginning again
• there is less chance of an error being made
• encourages a more logical approach
The following three examples show all stages in the dry running for the given set of input
data:
3.1 Example 1
This algorithm inputs 3 numbers, each number goes through successive division by 10 until its
value is less than 1. An output is produced which contains the number input and a value
generated by the flowchart processing.
3.2 Example 2
This algorithm inputs 5 values and outputs how many input numbers were negative and
how many were positive.
3.3 Example 3
This algorithm inputs the number of hours of sunshine recorded each day for a week (7
days). The output is the highest value for hours of sunshine and the average (mean) value
for the numbers of hours of sunshine per day.
Data to be used: hours = 9.0, 7.8, 1.2, 4.5, 10.0, 6.4, 3.1
Questions:
Questions 1 to 7 are problems which require an algorithm to be written in the form of a
flowchart. Questions 8 to 10 require a trace table to be written and find the expected
output for the given set of data. The answers to these questions can be found in booklet 6.
1. Regis lives in Brazil and often travels to USA, Europe and Japan. He wants to be able to
convert Brazilian Reais into US dollars, European euros and Japanese yen. The
conversion formula is:
For example, if Regis is going to USA and wants to take 1000 Reais (and the exchange
rate is 0.48) then he would input USA, 1000 and 0.48 and the output would be: 480 US
dollars.
Write an algorithm, using a flowchart, which inputs the country he is visiting, the
exchange rate and the amount in Brazilian Reais he is taking. The output will be value in
foreign currency and the name of the currency.
2. As part of an experiment, a school measured the heights (in metres) of all its 500
students.
Write an algorithm, using a flowchart, which inputs the heights of all 500 students and
outputs the height of the tallest person and the shortest person in the school.
3. A geography class decide to measure daily temperatures and hours of sunshine per
day over a 12 month period (365 days)
Write an algorithm, using a flowchart, which inputs the temperatures and hours of
sunshine for all 365 days, and finally outputs the average (mean) temperature for the
year and the average (mean) number of hours per day over the year.
4. A small shop sells 280 different items. Each item is identified by a 3 – digit code. All items
that start with a zero (0) are cards, all items that start with a one (1) are sweets, all items
that start with a two (2) are stationery and all items that start with a three (3) are toys.
Write an algorithm, using a flowchart, which inputs the 3 – digit code for all 280 items
and outputs the number of cards, sweets, stationery and toys.
5. A company are carrying out a survey by observing traffic at a road junction. Each time
a car, bus or lorry passed by the road junction it was noted down.
10 000 vehicles were counted during the survey.
Write an algorithm, using an algorithm, which:
inputs all 10000 responses outputs the number of cars, buses and lorries that passed by
the junction during the survey outputs the number of vehicles that weren‟t cars, buses or
lorries during the survey.
6. Speed cameras read the time a vehicle passes a point (A) on the road and then
reads the time it passes a second point (B) on the same road (points A and B are
100 metres apart). The speed of the vehicle is calculated using:
The maximum allowed speed is 100 kilometres per hour. 500 vehicles were
monitored using these cameras over a 1 hour period.
Write an algorithm, using a flowchart, which:
• inputs the start time and end time for the 500 vehicles that were monitored
• calculate the speed for each vehicle using the formula above
• outputs the speed for each vehicle and also a message if the speed
exceeded 100 km/hour
• output the highest speed of all the 500 vehicles monitored
8. Draw the trace table and determine the output from the following flowchart using
the following data:
9. Draw the trace table and determine the output from the following flowchart using
the following data (NOTE: input of the word “end” stops the program and outputs
results of the survey):
vehicle = car, car, lorry, bus, van, van, car, car, bus, car, end
10. Draw the trace table and determine the output from the following flowchart using
the following data:
(b) A program is to be written which will update the records in a sequential file
and then produce a backup copy.
Describe, using a diagram, the way that this problem can be split into modules to
prepare it for coding. [5]
(a) Complete the structure diagram to show the modules that will be needed.
[3]
(b) The printout will be different for those staff who receive
cash and those who have theirearnings paid directly to a
bank account. Add the next level to the print module.
[1]
(c) SalesReport is made up of two modules, MonthlySalesReport and
AnnualSalesReport.
Add them to the structure diagram in (b). [2]
1 Soni works for a software house which has been asked to design software for a cycle
hirecompany, Super Bikes.
Soni decides on the main tasks:
• collecting the information about new bikes
• entering details of repairs
• entering details of hirer
• entering details of payment
(a) Complete the structure diagram showing these tasks.
[2]
(b) The collection of information about repairs has three subtasks:
• input the repair needed
• input the parts list
• input the cost of the repair
Add these to the structure diagram in part (a). [1]
(c) State two reasons for dividing the main task into smaller tasks. [2]
Flow Charts:
May/June 2006
9
Trace the flow chart using the numbers 2 and 3. Write down each of the values of N in the
orderthat they are printed out.
(a) 2 [1]
(b) 3 [2]
14 (b)
(b) Select words from the list below to complete the systems flowchart for electricity
billpayments.
Oct/Nov 2006
17 The following flowchart shows how the bar code written on an item is used to find the
price,do stock control and produce an itemised bill. Select statements from the list below
tocomplete the flowchart.
May/June 2007
2 Describe, with examples, two types of test data which could be used to test a system. [4]
(a) Complete the following table showing the expected output from the flowchart for
thethree sets of input data:
Oct/Nov 2007
11Majid lives in Cairo but often travels to Tokyo, Mumbai and Washington. A flow chart
hasbeen written so he can work out the local time in these three places.
May/June 2008
9 The following flowchart inputs two numbers, carries out a calculation and then outputs
theresult.
(a)Complete the following table for the three sets of input data.
Oct/Nov 2008
17 The following flowchart shows how sensors (which can be analogue or digital) and a
computer are used to control the temperature of a greenhouse for plants. Complete the
flowchart using the items from the list below.
May/June 2009
14 Study the flowchart very carefully.
(a) Complete the table to show what outputs you would expect for the two inputs.
16 The following flowchart shows what happens when a customer uses a credit card to pay
forgoods at a supermarket. Ten of the boxes are blank.
Using the items from the list, insert the ten missing statements using the appropriatenumber
only. Each statement may be used once only.
The flowchart below shows the log on procedure. Several boxes have been left blank.
Complete the flowchart using items from the list.
Complete the trace table for the following two sets of data:
(i) a = 5, b = 4, c = 1, d = 9
(ii) a = 5, b = 9, c = 4, d = 1
15 A library uses barcodes to identify borrowers and books. A borrower has a card
containinga barcode with an equivalent numerical code. Each book also has a
barcode with anequivalent numerical code.
The flowchart on the facing page shows what happens when book(s) are taken out
by aborrower. However, several stages are missing.
Using item numbers only, complete the flowchart by selecting stages from the item
listbelow.
13 A heating system is being controlled by sensors and a computer. The temperature must
be keptbetween 15°C and 25°C. If 30°C is exceeded a warning message is generated and
the systemshuts down.
A flowchart of the process is shown below. Some of the items are missing.
Complete the flowchart, using item number only, from the list of items given.
Complete the trace table for the flowchart using the following data:
0, 3, 5, 6, -4, -1, 0, 0, -4, 10
13 An algorithm has been written to check that code numbers are valid on input. They must
be in therange 1000 to 9999.
Five hundred codes are being entered and the percentage of entered codes which are
incorrectis output.
There is a flowchart on the opposite page. It has some statements missing.
Complete the flowchart. Use statement numbers only, chosen from the list below.
10 (a) The flowchart on the next page shows how barcodes are used in a supermarket to
find product information and to produce orders for new stock automatically. Several
statements are missing from the flowchart.
Complete the flowchart, using item numbers only from the list below.
11 An algorithm has been written to input six temperatures for every day of the year
(365 days). The
outputs are:
• the average daily temperature for each day
• the highest recorded temperature for the whole year
The algorithm is in the form of a flowchart on the next page. However, several of the
statements are missing.
Using instruction number only, complete the flowchart using the following list of
instructions:
(b) This flowchart does not give correct answers for certain sets of test data.
Suggest a data set that would give an incorrect answer.
Give a reason for your choice.
data set .....................................................................................................................................
...................................................................................................................................................
reason .......................................................................................................................................
...................................................................................................................................................
............................................................................................................................................... [2]
Variable
Constant
A constant is a value that is set when the program initialises and does not change during
the program‟s execution.
Declaration
A declaration ensures that sufficient memory is reserved in which to store the values and
also states the variables‟ data type. Reserved words/keywords cannot be used as identifier
names as this generates a compiler error and comes under the category of syntax error.
Scope
Scope indicates whether a variable can be used by all parts of a program or only within
limited sections of the program – for example, within a subroutine.
Global variable
A global variable is one that is declared at the start of the main program and is visible
(useable) everywhere in the program and exists for the lifetime of the program.
Note that if one procedure changes the value of a global variable, then the next
procedure that uses the variable will be given this changed value – this is a common cause
of errors.
Local variable
A local variable is one that is only visible inside the procedure or function in which it is
declared.
Note that a local variable cannot be referenced from outside the procedure. In fact a
local variable does not exist until the procedure starts executing and it disappears when
the procedure stops executing. Thus any value that is held by a local variable is only stored
temporarily.
The lifetime of a local variable is the lifetime of the procedure in which the local variable is
declared.
The advantage of using local variables rather than global variables is that the same
variable names can be used in several different procedures without any chance of values
being confused.
Constants will be declared at the start of the main program. The following shows the
declaration of constants for Pi and the VAT rate
CONST Pi = 3.142
Declaring constants at the start of a program means that maintenance is made easier for
two reasons:
• if the value of a constant changes, it only has to be changed in the one part of the
program where it has been declared, rather than in each part of the program in
which it is used;
• the code is easier to interpret:
Total=0.175*CostPrice
Intrinsic data types are the data types that are defined within a particular programming
language.
There are numerous different data types. They are used to make the storage and
processing of data easier and more efficient. Different databases and programming
systems have their own set of intrinsic data types, but the main ones are:
• Integer;
• Real;
• Boolean;
• String;
• Character;
Integer
An integer is a positive or negative number that does not contain a fractional part. Integers
are held in pure binary for processing and storage. Note that some programming
languages differentiate between short and long integers (more bytes being used to store
long integers).
Real
A real is a number that contains a decimal point. In many systems, real numbers are
referred to as singles and doubles, depending upon the number of bytes in which they are
stored.
Boolean
A Boolean is a data-type that can store one of only two values – usually these values are
True or False. Booleans are stored in one byte – True being stored as 11111111 and False as
00000000.
String
Character
A character is any letter, number, punctuation mark or space, which takes up a single unit
of storage (usually a byte).
Define and use arrays (one- and two-dimensional) for solving simple problems (this should
include initialising arrays, reading data into arrays and performing a simple serial search on
a one-dimensional array)
A data structure is a collection of different data items that are stored together in a clearly
defined way. Two common data structures are arrays and records.
Array
An array is a data structure, which allows a set of items of identical data type to be stored
together using the same identifier name.
Arrays are declared in a similar way to standard variables, except that the array size and
dimensions are included. For example, the following declares an array that reserves five
locations in memory and labels these as „Names‟:
The five individual locations are Names(0), Names(1), Names(2), Names(3), Names(4).
Each data item is called an element of the array. To reference a particular element a
programmermust use the appropriate index. For example, the following statement assigns
data to the 5thelement:
Names(4) = “Johal”
Arrays simplify the processing of similar data. An algorithm for getting five names from the
user and storing them in the array Names is shown below:
A one-dimensional array is a data structure in which the array is declared using a single
index and can be visually represented as a list.
The following diagram shows the visual representation of the array Names(4):
Pseudocode
Introduction
This section covers the use of pseudocode in the production of algorithms. Students should
use standard computing text books to find out information on the features of programming
languages (high level and low level), interpreters, compilers, assemblers, user
documentation and technical documentation.
Definition
An algorithm is a procedure for solving a problem in terms of the actions to be executed
and the order in which those actions are to be executed. An algorithm is merely the
sequence of steps taken to solve a problem. The steps are normally "sequence," "selection,
" "iteration," and a case-type statement.
The "selection" is the " if ….. then ….. else ….. endif" statement, and the iteration is satisfied
by a number of statements, such as the " for … to … next, while … endwhileand repeat …
until " while the case-type statement is satisfied by the " case of ….. otherwise …... endcase"
statement.
1.1 counting
Counting in 1s is quite simple; use of the statement count count + 1 will enable counting
to be done (e.g. in controlling a repeat loop). The statement literally means: the (new)
count =the (old) count + 1
It is possible to count in any increments just by altering the numerical value in the statement
(e.g. count count – 1 counts backwards)
1.2 totalling
To add up a series numbers the following type of statement should be used:
1.3 input/output
Input and output indicated by the use of the terms READ number, PRINT total, PRINT “result
is” x and so on.
1.4 branching
There are two common ways of branching:
case of ….. otherwise …... endcase
if ….. then ….. else ….. endif
case of if … then
casenumber of if number = 1 then x x + 1
1: x x + 1 else if number = 2 then y y + 1
2: y y + 1 else print “error”
otherwise print “error” endif
endcase endif
1.5 loops
There are three common ways of performing a looping function:
The following example input 100 numbers and finds the total of the 100 numbers and
outputs this total. All three looping techniques are shown:
Assignment
An assignment is an instruction in a program that places a value into a specified variable.
Some typical assignments are:
TheLength 20.5
TheUsersName$ “Charlie”
TheAreaTheWidth * TheLength
TotalCostLabelledCost + 15
Counter Counter + 1
Note that the last example is a common method used to increment the value of a
variable. It could be read as:
Division
Relational operators are used in the format: [Expression] [Operator] [Expression] and will
always return a Boolean (True or False) value.
Relational operators are typically used with the IF selection and also within conditional
loops
(REPEAT-UNTIL or WHILE-WEND).
In the following table, the variables a and name$ have the following assignments:
a3+5
name$ “JAMES”
The following „truth‟ table summarises the result of the Boolean operations:
Values Results
NOT
The NOT operator reverses the result of the Boolean expression and is used in the format:
NOT [Boolean]
Validation
The drop-down lists, check-boxes and option buttons are extremely useful in that they
provide an automatic means of validation – the user can only input pre-determined values.
Other validation needs to be programmed into the system and is often added to the
submit button.
Presence check
Code can be added to check that a particular control has not been left empty or un-
checked:
If Username = “” Then
End
Range check
Code can be added to check that a particular control has a value between an allowed
maximum and minimum:
Print (“The age that you have netered is not within the_
permitted range”)
End
Length check
Code can be added to check that a particular control has a value between an allowed
maximum and minimum:
End
2.1 Example 1
A town contains 5000 houses. Each house owner must pay tax based on the value of the
house. Houses over $200 000 pay 2% of their value in tax, houses over $100 000 pay 1.5% of
their value in tax and houses over $50 000 pay 1% of their value in tax. All others pay no tax.
Write an algorithm to solve the problem using pseudocode.
forcount 1 to 5000
inputhouse
ifhouse > 50 000 then tax house * 0.01
else if house > 100 000 then tax house * 0.015
else if house > 200 000 then tax house * 0.02
elsetax 0
printtax
next
Notes:
(1) awhile loop or a repeat loop would have worked just as well
(2) the use of endifisn‟t essential in the pseudocode
For example,
count 0
whilecount < 5001
inputhouse
ifhouse > 50000 then tax house * 0.01
else if house > 100 000 then tax house * 0.015
else if house > 200 000 then tax house * 0.02
elsetax 0
endif
endif
endif
printtax
count count + 1
endwhile
EXERCISE: Re-write the above algorithm using a repeat loop and modify the if … then …
else statements to include both parts of the house price range.
(e.g. if house > 50000 and house <= 100000 then tax = house * 0.01)
2.2 Example 2
The following formula is used to calculate n: n = x * x/(1 – x)
The value x = 0 is used to stop the algorithm. The calculation is repeated using values of x
until the value x = 0 is input. There is also a need to check for error conditions. The values of
n and x should be output.
NOTE: It is much easier in this example to input x first and then loop round doing the
calculation until eventually x = 0. Because of this, it would be necessary to input x twice (i.e.
inside the loop and outside the loop). If input x occurred only once it would lead to a more
complicated algorithm.
A while loop is used here, but a repeat loop would work just as well.
inputx
whilex <> 0 do
ifx = 1 then print “error”
elsen (x * x)/(1 – x)
printn, x
endif
inputx
endwhile
2.3 Example 3
Write an algorithm using pseudocode which takes temperatures input over a 100 day
period (once per day) and output the number of days when the temperature was below
20C and the number of days when the temperature was 20C or above.
(NOTE: since the number of inputs is known, a for … to loop can be used. However, a while
loop or a repeat loop would work just as well).
total1 0: total2 0
fordays 1 to 100
inputtemperature
iftemperature < 20 then total1 total1 + 1
elsetotal2 total2 + 1
endif
next
printtotal1, total2
This is a good example of an algorithm that could be written using the case construct
rather than if … then … else. The following section of code replaces the statements if
temperature < 20 then …… endif:
casetemperature of
1: total1 = total1 + 1
2: total2 = total2 + 1
endcase
2.4 Example 4
Write an algorithm using pseudocode which:
(NOTE: Again since the actual number of data items to be input is known any one of the
three loop structures could be used. It is necessary to set values for the fastest (usually set at
zero) and the slowest (usually set at an unusually high value) so that each input can be
compared. Every time a value is input which > the value stored in fastest then this input
value replaces the existing value in fastest; and similarly for slowest).
fastest 0: count 0
slowest 1000
repeat
inputtop_speed
total total + top_speed
iftop_speed> fastest then fastest top_speed
iftop_speed< slowest then slowest top_speed
endif
endif
count count + 1
untilcount = 5000
average total * 100/5000
printfastest, slowest, average
2.5 Example 5
A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code.
All books have a code starting with a 1, all maps have a code starting with a 2 and all
magazines have a code beginning with a 3. The code 9999 is used to end the program.
Write an algorithm using pseudocode which input the codes for all items in stock and
outputs the number of books, maps and magazine in stock. Include any validation checks
necessary.
(NOTE: A 4-digit code implies all books have a code lying between 1000 and 1999, all maps
have a code lying between 2000 and 2999 and all magazines a code lying between 3000
and 3999. Anything outside this range is an error)
(NOTE: A function called INT(X) is useful in questions like this. This returns the integer (whole
number) part of X e.g. if X = 1.657 then INT(X) = 1; if X = 6.014 then INT(X) = 6 etc. Using this
function allows us to use the case statement to answer this question:
(this is probably a more elegant but more complex solution to the problem)
Example:
Line 1 Max0
Line 2 Min0
Line 3 FOR Count25 to 1
Line 4 REPEAT
Line 5 OUTPUT “Please enter a Mark between 0 and 100”
Line 6 INPUT Mark
Line 7 UNTIL Mark >=0 AND Mark<=50
Line 8 IF Mark > Max THEN Max Mark
Line 9 IF Mark < Min THEN Min Mark
Line 10 Count Count+1
Line 11 TotalTotal+Mark
Line 12 AvgTotal/25
Line 13 OUTPUT “Maximum Mark: “, Max
Line 14 OUTPUT “Minimum Mark: “, Min
Line 15 OUTPUT “Mean Mark: “, Avg
Oct/Nov 2006
9 A computer program is required which inputs 10 numbers, multiplies them together and
finally outputs the answer (the product). The following algorithm has been written to do this.
1 count = 0
2 product = 0
3 while count <= 10 do
4 input number
5 product = product * number
6 count = count + 1
7 print product
8 endwhile
(a) There are three errors in the algorithm. Locate and describe these errors. [3]
(b) A while … do loop has been used in the algorithm. State another type of loop that
could have been used. [1]
1 negative = 1
2 positive = 1
3 for count = 1 to 20 do
4 input number
5 if number < 0 then negative = negative + 1
6 if number > 0 then positive = positive + 1
7 count = count + 1
8 print negative, positive
9 next count
8 A piece of pseudocode was written to input 1000 positive numbers and then output
thehighest and lowest numbers.
10 highest = 0
20 lowest = 0
30 for count = 1 to 100
40 input number
50 if number > highest then number = highest
60 if number < lowest then number = lowest
70 count = count + 1
80 next count
90 print highest, lowest
correction ..................................................................................................................................
............................................................................................................................................... [5]
(b) The corrected algorithm was converted to a computer program and run. However,
after several numbers were input, the program stopped and an error message was
generated, showing that there was a further error at line 40 (k = x / number).
State what could cause this error to occur.
...................................................................................................................................................
...................................................................................................................................................
Suggest a change to line 40 to overcome this problem.
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................... [2]
Array
Question 01: Input and store the names and marks for 30 students who have sat three
computer science tests.Test 1 is out of 20 marks, Test 2 is out of 25 marks, Test 3 is out of 35
marks. You must store thenames in a one-dimensional array and the marks and total score
for each student in one-dimensionalarrays. All the marks must be validated on entry and
any invalid marks rejected. You may assumethat the students‟ names are unique.
Question 02: Calculate and store the total score for each student and calculate the
average score for the wholeclass. Output each student‟s name followed by their total
score, then output the average score for theclass.
Question 03: Select the student with the highest score and output their name and score.
Your program must include appropriate prompts for the entry of data. Error messages and
otheroutput need to be set out clearly and understandably. All variables, constants and
other identifiersmust have meaningful names. Each task must be fully tested.
Question 04: Write a pseudocode using array, asks user to input 10 numbers, then
calculates the average of those numbers. Loop is used in this problem.
Question 05: Write a pseudocode to swap first and last element of an integer 1-d array.
Question 06: Write a pseudocode to find the largest and smallest element of an array.
Practice Questions:
Questions 1 to 3 contain sections of pseudocode which contain errors. Locate the errors
and suggest the correct coding. Questions 4 to 10 are problems which require an algorithm
to be written in pseudocode – there is “no right answer” here; as long as the pseudocode
works then the solution is acceptable.
(1) The following section of pseudocode inputs 1000 numbers and then outputs how many
were negative, how many were positive and how many were zero.
Locate the 3 errors and suggest a corrected piece of code.
1 negative 1: positive 1
2 for x 0 to 1000
3 input number
4 if number < 0 then negative negative + 1
5 if number > 0 then positive positive + 1
6 endif
7 endif
8 next
9 print negative, positive
(2) The following section of pseudocode inputs rainfall (in cm) for 500 days and outputs the
average rainfall and the highest rainfall input.
Locate the 3 errors and suggest a corrected piece of code.
1 highest 1000
2 days 1
3 while days > 0
4 input rainfall
5 if rainfall > highest then highest rainfall
6 endif
7 total total + rainfall
8 days days + 1
9 average total/500
10 endwhile
11 print average, highest
1 input n
2 for mult 1 to n
3 sum 0
4 sum sum * mult
5 result n/sum
6 next
7 print result
(4) Regis lives in Brazil and often travels to USA, Europe and Japan. He wants to be able to
convert Brazilian Reais into US dollars, European euros and Japanese yen. The conversion
formula is:
Write an algorithm, using pseudocode, which inputs the country he is visiting, the exchange
rate and the amount in Brazilian Reais he is taking. The output will be value in foreign
currency and the name of the currency.
(5) As part of an experiment, a school measured the heights (in metres) of all its 500
students.
Write an algorithm, using pseudocode, which inputs the heights of all 500 students and
outputs the height of the tallest person and the shortest person in the school.
(6) A geography class decide to measure daily temperatures and hours of sunshine per
day over a 12 month period (365 days)
Write an algorithm, using pseudocode, which inputs the temperatures and hours of
sunshine for all 365 days, and finally outputs the average (mean) temperature for the year
and the average (mean) number of hours per day over the year.
(7) A small shop sells 280 different items. Each item is identified by a 3 – digit code. All items
that start with a zero (0) are cards, all items that start with a one (1) are sweets, all items
that start with a two (2) are stationery and all items that start with a three (3) are toys.
Write an algorithm, using pseudocode, which inputs the 3 – digit code for all 280 items and
outputs the number of cards, sweets, stationery and toys.
(8) A company are carrying out a survey by observing traffic at a road junction. Each time
a car, bus, lorry or other vehicle passed by the road junction it was noted down.
10 000 vehicles were counted during the survey.
Write an algorithm, using pseudocode, which:
inputs all 10000 responses
outputs the number of cars, buses and lorries that passed by the junction during the
survey
outputs the number of vehicles that weren’t cars, buses or lorries during the survey
(9) Speed cameras read the time a vehicle passes a point (A) on the road and then reads
the time it passes a second point (B) on the same road (points A and B are 100 metres
apart). The speed of the vehicle is calculated using:
The maximum allowed speed is 100 kilometres per hour. 500 vehicles were monitored using
these cameras over a 1 hour period.
Write an algorithm, using pseudocode, which:
inputs the start time and end time for the 500 vehicles that were monitored
calculate the speed for each vehicle using the formula above
outputs the speed for each vehicle and also a message if the speed exceeded 100
km/hour
output the highest speed of all the 500 vehicles monitored
(10) There are ten stations on a railway line:
The train travels in both directions (i.e. from 1 to 10 and then from 10 to 1). The fare
between each station is $2.
A passenger inputs the number of the station at the start of his journey and the number of
the destination station and the fare is calculated (e.g if a passenger gets on a station 3 and
his destination is station 9 his fare will be $12). The calculation must take into account the
direction of the train (e.g. a passenger getting on at station 7 and getting off at station 1
will also pay $12 and not a negative value!!).
100
𝑠𝑝𝑒𝑒𝑑 = (𝑚𝑒𝑡𝑒𝑟𝑠/𝑠𝑒𝑐𝑜𝑛𝑑)
(time at point B – time at point A)
The maximum allowed speed is 100 kilometres per hour. 500 vehicles were monitored using
these cameras over a 1 hour period.
The train travels in both directions (i.e. from 1 to 10 and then from 10 to 1). The fare
between each station is $2.
A passenger inputs the number of the station at the start of his journey and the number of
the destination station and the fare is calculated (e.g if a passenger gets on a station 3 and
his destination is station 9 his fare will be $12). The calculation must take into account the
direction of the train (e.g. a passenger getting on at station 7 and getting off at station 1
will also pay $12 and not a negative value!!).
Calculate the BMI for a person whose weight is 80kg and height is 2 metres. [1]
(b) Using pseudocode or otherwise, write an algorithm that will input the ID, weight (kg)
and height (m) of 30 students, calculate their body mass index (BMI) and output their ID,
BMI and a comment as follows:
A BMI greater than 25 will get the comment „OVER WEIGHT‟, a BMI between 25 and 19
(inclusive) will get „NORMAL‟ and a BMI less than 19 will get „UNDER WEIGHT‟. [6]
20 Temperatures (°C) are being collected in an experiment every hour over a 200 hour
period. Write an algorithm, using pseudocode or otherwise, which inputs each temperature
and outputs
• how many of the temperatures were above 20°C
• how many of the temperatures were below 10°C
• the lowest temperature that was input [5]
May/June 2007
19 A company has 5000 CDs, DVDs, videos and books in stock. Each item has a unique5-
digit code with the first digit identifying the type of item, i.e.
1 = CD
2 = DVD
3 = video
4 = book
For example, for the code 15642 the 1 identifies that it is a CD, and for the code 30055 the3
identifies that it is a video.
Write an algorithm, using pseudocode or otherwise, that
• Inputs the codes for all 5000 items
• Validates the input code
• Calculates how many CDs, DVDs, videos and books are in stock
• Outputs the four totals. [5]
Oct/Nov 2007
16 (a) Fuel economy for a car is found using the formula:
What would be the Fuel Economy of a car travelling 40 km on 10 litres of fuel? [1]
(b) The Fuel Economy for 1000 cars is to be calculated using the formula in Question 16(a).
Write an algorithm, using pseudocode or otherwise, which inputs the Distance Travelled
(km) and the Fuel Used (litres) for 1000 cars. The Fuel Economy for each car is then
calculated and the following outputs produced:
• Fuel Economy for each car
• average (mean) Fuel Economy for all of the cars input
• the best Fuel Economy (i.e. highest value)
• the worst Fuel Economy (i.e. lowest value) [6]
May/June 2008
12 Algorithms and programs use loops to control the number of times a particular
procedure isused.
Two methods are repeat … until and for … to.
(a) Write a procedure using both these loop methods to input 20 numbers into a
variablecalled x.
(i) repeat … until [2]
(ii) for … to [2]
(b) Name another loop structure. [1]
Oct/Nov 2008
19 The manufacturing cost of producing an item depends on its complexity. A company
manufactures three different types of item, with costs based on the following calculations:
May/June 2009
18 A small airport handles 400 flights per day from three airlines:
FASTAIR (code FA)
SWIFTJET (code SJ)
KNIGHTAIR (code KA)
Each flight is identified by the airline code and 3 digits. For example FA 156.
Write an algorithm, using pseudocode or otherwise, which monitors the 400 flights into and
out of the airport each day. The following inputs, processing and outputs are all part of the
monitoring process:
• input flight identification
• calculate number of flights per day for each of the three airlines
• output the percentage of the total flights per day by each airline
• any validation checks must be included [5]
What is the final speed of a car if it takes 2 hours to get from A to B? [1]
(b) Write an algorithm, using pseudocode or otherwise, which inputs the times for 500 cars,
calculates the final speed of each car using the formula in part (a), and then outputs:
• the final speed for ALL 500 cars
• the slowest (lowest) final speed
• the fastest (highest) final speed
• the average final speed for all the cars. [6]
(b) Describe, with examples, two sets of test data you would use to test your algorithm.
[2]
(b) Describe, with examples, TWO sets of test data you would use to test your algorithm.
[2]
16 A small shop uses barcodes which represent 5 digits. The last digit is used as a check
digit.
For example:
abcde
01234
The check digit (e) is found by:
• multiplying the first and third digits (i.e. a and c) by 3
• multiplying the second and fourth digits (i.e. b and d) by 2
• adding these four results together to give a total
• dividing this total by 10
• remainder is check digit (e)
Write an algorithm, using pseudocode or flowchart only, which
• inputs 100 five-digit barcodes in the form a, b, c, d, e
• re-calculates the check digit for each number and checks whether the input check
digit(e) is correct
• outputs the number of barcodes which were entered correctly [5]
17 A country has four mobile phone network operators. Each mobile phone number has
eightdigits. The first three digits identify the network operator:
444 Yodafone
555 N2 network
666 Kofee mobile
777 Satsuma mobile
Write an algorithm, using pseudocode or flowchart only, which reads 50 000 eight-
digitmobile phone calls made during the day and outputs the number of calls made on
each ofthe four networks. [6]
15 5000 numbers are being input which should have either 1 digit (e.g. 5), 2 digits (e.g. 36),
3digits (e.g. 149) or 4 digits (e.g. 8567).
Write an algorithm, using pseudocode or flowchart only, which
• inputs 5000 numbers
• outputs how many numbers had 1 digit, 2 digits, 3 digits and 4 digits
• outputs the % of numbers input which were outside the range [6]
15 A survey is being carried out which involves reading and recording sound levels near a
busy roadjunction. Once all the data are collected, they are input manually into a
computer. A sound levelof 0 decibels (0 dB) is input to indicate the end of the data.
Write an algorithm, using pseudocode or a flowchart, which:
• inputs all the sound levels
• after a sound level of 0 is input, outputs the following:
o average sound level
o highest recorded sound level.
18 A school has 1500 students. It is conducting a survey on their music preferences. Each
studentuses a computer and inputs their name and then chooses one of 5 options:
• rock (input value 1)
• soul (input value 2)
• pop (input value 3)
• jazz (input value 4)
• classical (input value 5)
Write an algorithm, using pseudocode or a flowchart, which:
• inputs the choice of all 1500 students (values 1 to 5)
• outputs all the names of the students who chose classical music
• outputs the percentage who chose each option.
16 A customer wants to compare prices of 1000 items sold in two supermarkets (price1 and
price2).
Write an algorithm, using pseudocode or a flowchart, which:
• inputs the two prices for all 1000 items
• outputs how many items were more expensive in supermarket 1
• outputs how many items were more expensive in supermarket 2
• outputs the largest price difference
Programming Language:
Computers can do such a wide variety of things because they can be programmed. This
means that computers are not designed to do just one job, but to do any job that their
programs tell them to do. A program is a set of instructions that a computer follows to
perform a task.
Programming languages can be used to create programs that control the behavior of a
computer and serve any purpose. Computer languages have some form of written
specification of their Syntax (Rules) and Semantic (Words, phrase & sentences). To write a
well-structured program, a programmer requires a programming language to support the
following „program construct‟:
Sequence: Execution of the program usually following the order in which the steps are
written.
Selection: a decision between alternative routes through the program that involves at least
one condition.
Computer programming languages can be divided into two types: low-level, closer to
machine language and high-level, closer to human language such English..
Machine language:
Machine language has the lowest level of language, because the long string of zeros and
ones in machine code is so difficult for a programmer to read or write. Each complete
machine language instruction consists of an operand code (known as „opcode‟).
Following is the example of opcode:
110000
Some opcodes require one or more operands, which are numerical values or memory
addresses upon which they operate. The operand follows the opcode in the program, for
example:
110000 01011010
Assembly Language:
Computers can only execute programs that are written in machine language. A program
can have thousands or even millions of binary instructions, and writing such a program
would be very tedious and time consuming. Programming in machine language would
also be very difficult because putting a 0 or a 1 in the wrong place will cause an error.
Assembly language programs cannot be executed by the CPU. The CPU onlyunderstands
machine language, so a special program known as an assembler is used totranslate an
assembly language program to a machine language program. This process isshown in
Figure 1-18. The assembly code input to the assembler is known as source code. The
machine language program that is created by the assembler can then be executed by
the CPU is known as object code.
Advantages:
In Python you would display the message Hello world with the following instruction:
print 'Hello world'
Doing the same thing in assembly language would require several instructions, and an
intimateknowledge of how the CPU interacts with the computer‟s output device. As you
can see from thisexample, high-level languages allow programmers to concentrate on the
tasks they want to performwith their programs rather than the details of how the CPU will
execute those programs.
Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists
severalof the more well-known languages.
High level language use interpreter, compiler or translator to convert human
understandable program to computer readable code (machine code).
Examples:
Many high level languages have appeared since Fortran II the most widely used have
been:
• The main advantage of high-level languages over low-level languages is that they
are easier to read, write and maintain.
• Many real time problems can be easily solved with high level language.
Programs are portable to different types of Programs are not portable to different
computer. types of computer.
Programs are relatively easy to read and Programs are relatively hard to read and
write. write.
Programs are relatively easy to test, debug Programs are relatively hard to test, debug
and maintain. and maintain.
Interpreter
Interpreted languages are read and then executed directly, with no compilation stage.
Compiler
Intermediate Compilation
Intermediate level compiles code in the form of Byte code and saves for later
execution without the need to re-read the source file.
Machine code compiles source code directly into machine code using Virtual
machines that execute code directly into machine code
Assembler
Assembler normally converts assembly language‟s source code into machine language.
An assembler is a program that takes basic computer instructions and converts them into a
pattern of bits ( 0& 1) that the computer runs to produce result.
Translates one source code Translates one source code Executes one source code
instruction to one machine statement to one or more statement as one or more
code instruction. machine code instructions. instructions.
COMPUTER LANGUAGES
In all over the world, language is the source of communication among human beings.
Different countries/regions have different languages. Similarly, in order to communicate
with the computer user also needs to have a language that should be understood by the
computer. For this purpose, different languages are developed for performing different
types of work on the computer. Basically, languages are divided into two categories
according to their interpretation.
Assembly Language
Machine Language: It is the lowest and most elementary level of Programming language
and was the first type of programming language to be developed. Machine Language is
basically the only language which computer can understand. In fact, a manufacturer
designs a computer to obey just one Language, its machine code, which is represented
inside the computer by a String of binary digits (bits) 0 and 1. The symbol 0 stands for the
absence of Electric pulse and 1 for the presence of an electric pulse . Since a computer is
Capable of recognizing electric signals, therefore, it understand machine Language.
ii) It requires no translator to translate the code i.e. directly understood by the computer
iii) It is hard to amend or find errors in a program written in the machine language
iv) These languages are machine dependent i.e. a particular machine language can be
used on only one type of computer
Assembly Language
difficult and needs a lot of practice to master it because very small English support is given
to this language. The language mainly helps in compiler orientations. The instructions of the
Assembly language will also be converted to machine codes by language translator to be
executed by the computer.
ii) Since it is machine dependent therefore programmer should have the knowledge of the
hardware also.
High level computer languages give formats close to English language and the purpose of
developing high level languages is to enable people to write programs easily and in their
own native language environment (English). High-level languages are basically symbolic
languages that use English words and/or mathematical symbols rather than mnemonic
codes. Each instruction in the high level language is translated into many machine
language instructions thus showing one-to-many translation
Many languages have been developed for achieving different variety of tasks, some are
fairly specialized others are quite general purpose.
Examples are
b) String and List Processing: These are used for string manipulation including search for
patterns, inserting and deleting characters. Examples are:
C++
Java
e) Visual programming language: these are designed for building Windows-based
applications Examples are:
Visual Basic
Visual Java
Visual C
User-friendly
Similar to English with vocabulary of words and symbols
Therefore it is easier to learn.
They require less time to write.
They are easier to maintain.
Problem oriented rather than 'machine' based.
Program written in a high-level language can be translated into many machine
language and therefore can run on any computer for which there exists an
appropriate translator.
It is independent of the machine on which it is used i.e. Programs developed in high
level language can be run on any Computer
Language Generations
Computer languages have the same history as the computer itself history.
There are five generations of languages when programming method and techniques
could bedeveloped as far as development in hardware occurred.
First-generation language was machine language or the level of instructions and data that
the processor is actually given to work on binary numbers 0s and 1s.
In the 1940s and 1950s, computers were programmed by scientists sitting before control
panels equipped with switches so that they could input instructions as strings of zeros and
ones.
By the late 1950s, this language had become popular. Assembly language consists of
letters of the alphabet.
This makes programming much easier than trying to program a series of zeros and ones.
Compiler based FORTRAN and COBOL created because it improved the record keeping
and data management ability in many business applications.
In the early 1960s, BASIC language designed and used bynonprofessional programmers.
BASIC remained popular during the 1970s and 1980s.
Programs written in third-generation languages require more memory and run more slowly
than those written in lower level languages.
Many fourth-generation languages use C, C++, Java and SQL that support stand-alone as
well as web applications.
Microsoft, Borland, IBM, and other companies make 5GL visual programming products for
developing applications in Java, J++, Visual Java, Visual Basic, ASP, ASP.NET, VB.NET and
C#.
Visual programming allows you to see object oriented structures and drag icons to
assemble program blocks.
Define and use different data types e.g. integer, real, boolean, character and string
Intrinsic data types are the data types that are defined within a particular programming
language.
There are numerous different data types. They are used to make the storage and
processing of data easier and more efficient. Different databases and programming
systems have their own set of intrinsic data types, but the main ones are:
• Integer;
• Real;
• Boolean;
• String;
• Character;
• Date;
• Container.
Integer
An integer is a positive or negative number (-32,768 to 32,767) that does not contain a
fractional part. Integers are held in pure binary for processing and storage. Note that some
programming languages differentiate between short and long integers (more bytes being
used to store long integers).
Real
A real is a number that contains a decimal point. In many systems, real numbers are
referred to as singles and doubles, depending upon the number of bytes in which they are
stored.
Boolean
A Boolean is a data-type that can store one of only two values – usually these values are
True or False. Booleans are stored in one byte – True being stored as 11111111 and False as
00000000.
String
A string is a series of alphanumeric characters enclosed in quotation marks. A string is
sometimes just referred to as „text‟. Any type of alphabetic or numeric data can be stored
as a string: “Birmingham City”, “3/10/03” and “36.85” are all examples of strings. Each
character within a string will be stored in one byte using its ASCII code; modern systems
might store each character in two bytes using its Unicode. The maximum length of a string is
limited only by the available memory.
Notes:
• if dates or numbers are stored as strings then they will not be sorted correctly; they
will be sorted according to the ASCII codes of the characters – “23” will be placed
before “9”;
• telephone numbers must be stored as strings or the leading zero will be lost.
Character
A character is any letter, number, punctuation mark or space, which takes up a single unit
of storage (usually a byte). In some programming languages it is written as Char.
Dates
In most computer systems dates are stored as a „serial‟ number that equates to the number
of seconds since January 1st, 1904 (thus they also contain the time). Although the serial
numbers are used for processing purposes, the results are usually presented in one of
several „standard‟ date formats – for example, dd/mm/yyyy, or ddMonthName, yyyy.
Dates usually take 8 bytes of storage.
Variables:
Variables are a name that is given to the data. The name must not start with a number or
character that is not a letter. Also, the name of the variable must not be a reserved name
like PRINT, INPUT, LET, ABS, BEEP, etc.
Examples:
Sample Code:
Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean
b = 1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"
If ScriptEngine = "VB" Then
bl = True
Else
bl = False
End If
If bl Then
'the oath taking
Console.Write(c &" and," & s &vbCrLf)
Console.WriteLine("declaring on the day of: {0}", da)
Console.WriteLine("We will learn VB.Net seriously")
Console.WriteLine("Lets see what happens to the floating point variables:")
Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
End If
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces following result:
U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously
Lets see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346
Remember that selecting the right data type for the variable is very important to make the
program run properly.
1.1 counting
Counting in 1s is quite simple; use of the statement count = count + 1 will enable counting
to be done (e.g. in controlling a repeat loop). The statement literally means: the (new)
count = the (old) count + 1
It is possible to count in any increments just by altering the numerical value in the statement
(e.g. count = count – 1 counts backwards)
Public Class Test
Public Shared Sub Main()
DIM Weather as String
DIM Foggy as Integer=0
DIM Cloudy as Integer=0
DIM Rainy as Integer=0
DIM Sunny as Integer=0
Weather=Console.ReadLine()
Select Weather
Case "Foggy"
Foggy=Foggy+1
Case "Cloudy"
Cloudy=Cloudy+1
Case "Rainy"
Rainy=Rainy+1
CaseElse
Sunny=Sunny+1
End Select
Console.WriteLine (Foggy)
Console.WriteLine (Cloudy)
Console.WriteLine (Rainy)
Console.WriteLine (Sunny)
End Sub
End Class
1.2 totalling
To add up a series numbers the following type of statement should be used:
1.3 input/output
Example:
Module Module1
Sub Main()
DimCodeAs Integer=0
Code=Console.ReadLine()
WhileCode<>9999
Console.WriteLine(“Hello World”)
Code=Console.ReadLine()
End While
End Sub
End Module
1.4 branching
Selection
Selection is a control structure in which there is a test to decide if certain instructions are
executed.
IF-THEN-ELSE
This selection method is used if there are two possible outcomes to a test:
The syntax of an If...Then... Else statement in VB.Net is as follows:
If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
EndIf
If the Boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Example:
If count = 0 Then
message = "There are no items."
ElseIf count = 1 Then
message = "There is 1 item."
Else
message = "There are " & count & " items."
End If
SELECT-CASE
This selection method is used if there are more than two possible outcomes to a test:
Creating a Select-Case statement is simple to do. The next program will prompt the user to
select the key A-D and the program will respond by telling the user what key was entered.
We will create a Select-Case statement for the A-D keys entered.
Dim KeyPressedAs String
Console.WriteLine("Please Enter A Key (A,B,C,D): ")
KeyPressed=Console.ReadLine()
Select KeyPressed
Case "A"
Console.WriteLine("A Was Entered")
Case "B"
Console.WriteLine("B Was Entered")
Case "C"
Console.WriteLine("C Was Entered")
Case "D"
Console.WriteLine("D Was Entered")
Case Else
Console.WriteLine("Some Other Key Was Entered")
End Select
1.5 loops
Iteration
Iteration is a control structure in which a group of statements is executed repeatedly –
either a set number of times, or until a specific condition is True.
FOR-NEXT
This is an unconditional loop in which the number of repetitions is set at the beginning.
Sample code:
WHILE-ENDWHILE
While condition
[ statements]
[ ContinueWhile]
[ statements]
[ExitWhile]
[ statements]
EndWhile
Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is logical true. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
Sample code:
Module Module1
Sub Main()
DimCodeAs Integer=0
Code=Console.ReadLine()
WhileCode<>9999
Console.WriteLine(“Hello World”)
Code=Console.ReadLine()
End While
End Sub
End Module
REPEAT-UNTIL
This is a conditional loop, which has a test at the end and repeats until the condition is true:
Do
[ statements]
[ ContinueDo]
[ statements]
[ExitDo]
[ statements]
LoopUntil condition
Sample Code:
Module loops
SubMain()
' local variable definition
Dim a AsInteger=10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a = a +1
LoopUntil(a =20)
Console.ReadLine()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Procedural programs are ones in which instructions are executed in the order defined by
the programmer.
Procedural languages are often referred to as third generation languages and include
FORTRAN, ALGOL, COBOL, BASIC, and PASCAL.
Statement
A statement is a single instruction in a program, which can be converted into machine
code and executed.
In most languages a statement is written on a single line, but some languages allow
multiple lines for single statements.
Subroutine
A subroutine is a self-contained section of program code that performs a specific task, as
part of the main program.
Procedure
A procedure is a subroutine that performs a specific task without returning a value to the
part of the program from which it was called.
Function
A function is a subroutine that performs a specific task and returns a value to the part of the
program from which it was called.
Note that a function is „called‟ by writing it on the right hand side of an assignment
statement.
Parameter
A parameter is a value that is „received‟ in a subroutine (procedure or function).
The subroutine uses the value of the parameter within its execution. The action of the
subroutine will be different depending upon the parameters that it is passed.
Parameters are placed in parenthesis after the subroutine name. For example:
Square(5) „passes the parameter 5 – returns 25
Square(8) „passes the parameter 8 – returns 64
Square(x) „passes the value of the variable x
Understand, create and use subroutines (procedures and functions), including the passing
of parameters and the appropriate use of the return value of functions
Subroutine/sub-program
A subroutine is a self-contained section of program code which performs a specific task
and is referenced by a name.
A subroutine resembles a standard program in that it will contain its own local variables,
data types, labels and constant declarations.
There are two types of subroutine. These are procedures and functions.
• procedures are subroutines that input, output or manipulate data in some way;
• functions are subroutines that return a value to the main program.
A subroutine is executed whenever its name is encountered in the executable part of the
main program. The execution of a subroutine by referencing its name in the main program
is termed „calling‟ the subroutine.
• the same lines of code are re-used whenever they are needed – they do not have
to be repeated in different sections of the program.
• a procedure or function can be tested/improved/rewritten independently of other
procedures or functions.
• it is easy to share procedures and functions with other programs – they can be
incorporated into library files which are then „linked‟ to the main program;
• a programmer can create their own routines that can be called in the same way as
any built-in command.
The Sub statement is used to declare the name, parameter and the body of a
subprocedure. The syntax for the Substatement is:
Where,
Modifiers: specify the access level of the procedure; possible values are: Public,
Private, Protected, Friend,Protected Friend and information regarding overloading,
overriding, sharing, and shadowing.
SubName: indicates the name of the Sub
ParameterList: specifies the list of the parameters
Example
When the above code is compiled and executed, it produces following result:
This is the default mechanism for passing parameters to a method. In this mechanism, when
a method is called, a newstorage location is created for each value parameter. The values
of the actual parameters are copied into them. So, thechanges made to the parameter
inside the method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByValkeyword. The following
example demonstrates the
concept:
When the above code is compiled and executed, it produces following result:
It shows that there is no change in the values though they had been changed inside the
function.
In VB.Net, you declare the reference parameters using the ByRefkeyword. The following
example demonstrates this:
When the above code is compiled and executed, it produces following result:
All executable code must be inside a procedure. Use a Sub procedure when you don't want to
return a value to the calling code. Use a Function procedure when you want to return a value.
Defining a Function
The Function statement is used to declare the name, parameter and the body of a function. The
syntax for the Functionstatement is:
Where,
Tutorial content goes here.....
Modifiers: specifiy the access level of the function; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding,
sharing, and shadowing.
FunctionName: indicates the name of the function
ParameterList: specifies the list of the parameters
ReturnType: specifies the data type of the variable the function returns
Example
Following code snippet shows a function FindMax that takes two integer values and returns the
larger of the two.
In VB.Net a function can return a value to the calling code in two ways:
By using the return statement
By assigning the value to the function name
The following example demonstrates using the FindMax function:
When the above code is compiled and executed, it produces following result:
Define and use arrays (one- and two-dimensional) for solving simple problems (this should
include initialising arrays, reading data into arrays and performing a simple serial search on
a one-dimensional array)
A data structure is a collection of different data items that are stored together in a clearly
defined way. Two common data structures are arrays and records.
Array
An array is a data structure, which allows a set of items of identical data type to be stored
together using the same identifier name.
Arrays are declared in a similar way to standard variables, except that the array size and
dimensions are included. For example, the following declares an array that reserves five
locations in memory and labels these as „Names‟:
The five individual locations are Names(0), Names(1), Names(2), Names(3), Names(4).
Each data item is called an element of the array. To reference a particular element a
programmermust use the appropriate index. For example, the following statement assigns
data to the 5thelement:
Names(4) = “John”
Arrays simplify the processing of similar data. An algorithm for getting five names from the
user and storing them in the array Names is shown below:
One-dimensional arrays
A one-dimensional array is a data structure in which the array is declared using a single
index and can be visually represented as a list.
The following diagram shows the visual representation of the array Names(4):
TASK 2
Calculate and store the total score for each student and calculate the average score for
the wholeclass. Output each student‟s name followed by their total score, then output the
average score for theclass.
TASK 3
Select the student with the highest score and output their name and score.
Your program must include appropriate prompts for the entry of data. Error messages and
otheroutput need to be set out clearly and understandably. All variables, constants and
other identifiersmust have meaningful names. Each task must be fully tested.
Convert following pseudocode into programs using any high level language:
The following five examples use the above pseudocode terms. These are the same
problems discussed in section 3.1 using flow charts – both methods are acceptable ways of
representing an algorithm.
2.1 Example 1
A town contains 5000 houses. Each house owner must pay tax based on the value of the
house. Houses over $200 000 pay 2% of their value in tax, houses over $100 000 pay 1.5% of
their value in tax and houses over $50 000 pay 1% of their value in tax. All others pay no tax.
Write an algorithm to solve the problem using pseudocode.
forcount 1 to 5000
inputhouse
ifhouse > 50 000 then tax house * 0.01
else if house > 100 000 then tax house * 0.015
else if house > 200 000 then tax house * 0.02
elsetax 0
printtax
next
For example,
count 0
whilecount < 5001
inputhouse
ifhouse > 50000 then tax house * 0.01
else if house > 100 000 then tax house * 0.015
else if house > 200 000 then tax house * 0.02
elsetax 0
endif
endif
endif
printtax
count = count + 1
endwhile
EXERCISE: Re-write the above algorithm using a repeat loop and modify the if … then …
else statements to include both parts of the house price range.
(e.g. if house > 50000 and house <= 100000 then tax = house * 0.01)
2.2 Example 2
The following formula is used to calculate n: n = x * x/(1 – x)
The value x = 0 is used to stop the algorithm. The calculation is repeated using values of x
until the value x = 0 is input. There is also a need to check for error conditions. The values of
n and x should be output.
inputx
whilex <> 0 do
ifx = 1 then print “error”
elsen = (x * x)/(1 – x)
printn, x
endif
inputx
endwhile
2.3 Example 3
Write an algorithm using pseudocode which takes temperatures input over a 100 day
period (once per day) and output the number of days when the temperature was below
20C and the number of days when the temperature was 20C or above.
(NOTE: since the number of inputs is known, a for … to loop can be used. However, a while
loop or a repeat loop would work just as well).
total1 = 0: total2 = 0
fordays = 1 to 100
inputtemperature
iftemperature < 20 then total1 = total1 + 1
elsetotal2 = total2 + 1
endif
next
printtotal1, total2
This is a good example of an algorithm that could be written using the case construct
rather than if … then … else. The following section of code replaces the statements if
temperature < 20 then …… endif:
casetemperature of
1: total1 = total1 + 1
2: total2 = total2 + 1
endcase
2.4 Example 4
Write an algorithm using pseudocode which:
(NOTE: Again since the actual number of data items to be input is known any one of the
three loop structures could be used. It is necessary to set values for the fastest (usually set at
zero) and the slowest (usually set at an unusually high value) so that each input can be
compared. Every time a value is input which > the value stored in fastest then this input
value replaces the existing value in fastest; and similarly for slowest).
fastest = 0: count = 0
slowest = 1000
repeat
inputtop_speed
total = total + top_speed
iftop_speed> fastest then fastest = top_speed
iftop_speed< slowest then slowest = top_speed
endif
endif
count + count + 1
untilcount = 5000
average = total * 100/5000
printfastest, slowest, average
2.5 Example 5
A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code.
All books have a code starting with a 1, all maps have a code starting with a 2 and all
magazines have a code beginning with a 3. The code 9999 is used to end the program.
Write an algorithm using pseudocode which input the codes for all items in stock and
outputs the number of books, maps and magazine in stock. Include any validation checks
necessary.
(NOTE: A 4-digit code implies all books have a code lying between 1000 and 1999, all maps
have a code lying between 2000 and 2999 and all magazines a code lying between 3000
and 3999. Anything outside this range is an error)
(NOTE: A function called INT(X) is useful in questions like this. This returns the integer (whole
number) part of X e.g. if X = 1.657 then INT(X) = 1; if X = 6.014 then INT(X) = 6 etc. Using this
function allows us to use the case statement to answer this question:
this is probably a more elegant but more complex solution to the problem)
May/June 2006 P1
a) Give two benefits of using a high-level language for writing programs. [2]
(b) State one type of program that would be written in a low-level language rather than
ahigh-level language and give a reason why. [2]
Oct/Nov 2006 P1
10 A robot arm is to be used to move some objects which are positioned on the grid shown.
Object “X” is located at A7 and is to be moved to F7. Object “Y” is located at C6 and is to
bemoved to G5.
The START position for the robot arm is shown. The robot arm can travel left and right
alongthe top of the grid, and the robot arm can extend (lengthen) and retract (shorten) so
that thegripper at the end of the arm can reach any grid square.
For example, to move block “X” from square A7 to F7 (beginning at START) would require
the following instructions:
Left 8
Down 6
Close
Up 6
Right 5
Down 6
Open
Write a set of instructions to transfer block “Y” from C6 to G5 (beginning at START). [3]
Oct/Nov 2007 P1
Give two differences between high level languages and low level languages.
May/June 2008 P1
Oct/Nov 2008 P1
3 Write a routine using a for … to loop which inputs 100 numbers and outputs how many of
the numbers were negative. [3]
Oct/Nov 2009 P1
Give two advantages of using high level languages when writing new computer
softwarerather than using low level languages
10 (a) Compilers and interpreters translate high-level languages. Give two differences
between compilers and interpreters.
(b) Programs can be written using high-level or low-level languages.
Give one advantage of using each method.
High-level language advantage
Low-level language advantage
(c) What is meant by top-down design when developing new software?
1h=0
2c=0
3 REPEAT
4 READ x
5 IF x > h THEN x = h
6c=c+1
7 PRINT h
8 UNTIL c < 20
The above code is an example of a high-level language.
Complete the set of instructions to draw the shape shown above (in bold lines).
Databases:
A database is a way of storing information in a structured, logical way. Databases are used
to collect and organise information such as customer details for a business, medical
records at a surgery and stock items in a warehouse.
Database content is easy to manage. Information can be accessed and updated quickly
and efficiently. A database can store and handle vast amounts of data. A user can sort
and search a database to find any requested data.
Most databases have the following properties:
Tables
Data is stored in rows and columns (much like a spreadsheet – the main difference is how
the data is organised). Each row in a table is called a record which is made up of a
number of fields (columns in the table). The data type in the fields is usually either text,
numeric or date/time. Most databases contain a number of tables which are usually linked
together in some way.
Record
A record is a collection of fields that contains data about a single item or person – it is a
row within a table.
Field
A field is a single category of data within a database, which appears in all the records of a
table – it is a column within a table.
Key fields
A key field is used to identify the records within a database. There are two types of keys:
• primary key;
• secondary key.
Primary key
The Primary key is a unique field that identifies a single record. This prevents any records
from having the same value.
Some „natural‟ primary keys are:
• CarRegistrationNumber;
• ISBN – a 10-digit code that uniquely identifies a book;
• MAC number – a 6-part number that uniquely identifies a network card
• NationalInsuranceNumber – can uniquely identify employees of a company (not
usable for under 16s or for non-British nationalists!)
Secondary key
A Secondary key is a non-unique field, used in a search, that does not always produce
only one matching record.
Some typical secondary keys are:
• LastName;
• PostCode;
• DateOfBirth
Record structure
Before setting up a database, the record structure must be decided to make best use of
the memory and backing store, and to make searching and report creation easier.
For example, a car showroom wants to record details of the cars it sells. Before setting up
the database, the following attributes need to be decided:
Field Name, Field type, Field size, Format, Input Mask, Validation Rule
Record structure
...
When designing a database it is important to choose the correct field type. This ensures
that the data stored is usable and it makes validation easier. For example, if the price paid
for goods was stored in a text field, then the database wouldn‟t be able to add each
individual figure to produce a total.
Validation
Validation checks ensure that data entered into the computer is sensible. Data is checked
in accordance with a set of rules. The computer's software can validate data while it is
being entered into the computer. The main purpose of data validation is to spot an error.
This can be done quickly and easily as the process is automated.
1. Range check. A mathematics exam is out of 100. A simple validation rule that the
computer can apply to any data that is input is that the mark must be between 0 and 100
inclusive. Consequently, a mark of 101 would be rejected by this check as being outside
the acceptable range.
2. Character check. A person‟s name will consist of letters of the alphabet and sometimes
a hyphen or apostrophe. This rule can be applied to input of a person‟s name so that
dav2d will immediately be rejected as unacceptable.
4. Length check. A NI number has 9 characters, if more or fewer than 9 characters are
keyed in then the data cannot be accurate.
5. Existence check. A bar code is read at a supermarket check out till. The code is sent to
the main computer which will search for that code on the stock file. As the stock file
contains details of all items held in stock, if it is not there then the item cannot exist, which it
obviously does, therefore the code must have been wrongly read.
Coding of data:
Any system will need to have data collected, entered and stored.
One method of storing data is to assign codes to it. This usually means shortening the
original data in an agreed manner. The agreement is between the users of the system. This
coding scheme could be part of the training of how to use the system, and it could also be
documented within the system for new users.
If the coding is completely obvious then there is no such need for formaldocumentation.
For example if a field called 'Gender' has only two values 'M' and 'F'. It should be obvious
from the field name that this refers to Male and Female.
Example 1
Example 2
Validation can further improve accuracy Value judgements are difficult to code
Estimate the size of a file from its structure and the number of records
If we consider a file with 200 records, which stores the details of an organisation‟s
customers:
Note that to determine the maximum field length, an extreme case was considered and
several bytes added to play safe.
We have discussed the structure of a database as consisting of one or more tables, each
of which contain records and fields of various data types.
The next requirement is to have a system in place that can act upon that data as well as
creating and maintaining the database itself.
This is the role of the 'database management system' usually referred to as a DBMS.
The DBMS will have a command language. This includes command statements for:
There are many database management systems that are either commercial products or
free open source applications.
Examples include
Name Comment
Queries
Queries most commonly allow information to be retrieved from tables. Since the
information is often spread across several tables, queries allow it to be viewed as one single
datasheet. They also allow filtering so only the records required are seen. Queries can be
either results seen directly on the screen or the output to another form or report. Example of
a query: (house > 200 000) OR (no_of_rooms< 4).
Points to note: (1) there are 10 records in this section of the database
(2) each record has 4 fields
(3) sample queries:
(Smallest size (microns) < 1) OR (Toxic = “yes”)
would output records 4, 7, 8 and 9
(Largest size (microns) > 99) AND (Toxic = “no”)
Would output records 1, 2, 3, 6 and 10
The query should match up with the field titles to ensure a correct search is carried out.
Search engines on the Internet work in a similar way; the clever part is how the information
is stored on the databases so that the time to do the search (based on key words) and the
effectiveness of the search itself results in a very powerful and very useful tool.
SELECT STATEMENT
SELECT SYNTAX
SELECT expressions
FROM tables
WHERE conditions;
tables are the tables that you wish to retrieve records from. There must be at least one
table listed in the FROM clause.
conditions are conditions that must be met for the records to be selected.
Let's look at how to use a SQL SELECT query to select all fields from a table.
SELECT *
FROM suppliers
WHERE city = 'Newark'
ORDER BY city DESC;
In this SQL SELECT statement example, we've used * to signify that we wish to view all fields from
the suppliers table where the supplier resides in Newark. The result set is sorted by city in
descending order.
You can also use the SQL SELECT statement to select individual fields from the table, as opposed
to all fields from the table.
For example:
SELECT supplier_name, city, state
FROM suppliers
WHERE supplier_id> 1000
ORDER BY name ASC, city DESC;
This SQL SELECT example would return only the supplier_name, city, and state fields from
the suppliers table where the supplier_id value is greater than 1000. The results are sorted by
supplier_name in ascending order and then city in descending order.
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
Example
SELECT CustomerName,City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
The WHERE clause is used to extract only those records that fulfill a specified criterion.
The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
SQL requires single quotes around text values (most database systems will also allow double
quotes).
<> Not equal. Note: In some versions of SQL this operator may be written as !=
The AND operator displays a record if both the first condition AND the second condition are
true.
The OR operator displays a record if either the first condition OR the second condition is
true.
Combining AND & OR
You can also combine AND and OR (use parenthesis to form complex expressions).
The following SQL statement selects all customers from the country "Germany" AND the city
must be equal to "Berlin" OR "München", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');
Database:
May/June 2007:
1 Explain, using examples where appropriate, the meaning of these computer terms.
(b) relational database [2]
Oct/Nov 2006:
A car dealer uses a database to keep details of cars in stock. Part of the stock file is shown
below.
(a) (i) State the fieldname that should be used as the key field.
(ii) Explain the purpose of a key field.
(b) The following search condition is input:
(Price($) < 5000) AND (Model = Golf)
Write down the records that match the above search condition using only RegNo.
(c) Write down a search condition to find cars with an Engine greater than 1400cc or which
have less than 5 Doors.
(d) When a car is sold, the sale needs to be linked to a customer file. Suggest a new field
which could be used to link the stock file to the customer file.
May/June 2007:
A hospital has decided to computerise its administration system.
(a) Give three ways this could affect the hospital workers.
The hospital will be using a database which holds confidential personal data.
(b) State two precautions that the hospital should take to prevent unauthorised access to
the data.
(c) Describe how the database could be recovered if it became corrupted.
(d) Give one example, in each case, of when it would be necessary to amend data,
delete data and insert data into the patient database.
Oct/Nov 2007:
A school Science department is going to use a database to record details about its
equipment.
(a) Give two advantages of using a computer system rather than a manual filing system.
(b) Part of the database is shown below:
(i) As data is entered it needs to be verified. Describe one way this could be done.
(ii) Data also needs to be validated. Using fields from the database as examples, describe
two different validation checks which could be performed on the data.
Oct/Nov 2008:
To gain access to a database, a user must first type in a user ID and then a password which
needs to be verified.
(a) How is a password usually verified?
(b) In spite of these safeguards, unauthorised access to the database is still possible.
What could be done:
(i) to prevent data being used by unauthorised people?
(ii) to prevent loss of data once the database has been illegally accessed?
(c) Personal data is protected to some extent by a Data Protection Act. Give two
requirements of a Data Protection Act.
Oct/Nov 2008:
Oct/Nov 2009:
A radio station keeps a database of all its music CDs. Here is part of this database:
May/June 2009:
Explain, using examples where appropriate, the meaning of these computer terms.
(b) relational database
May/June 2009:
(a) How many records are shown in the Customer Details table?
(b) (i) Which field connects the New Car Sales table with the Customer Details table?
(ii) Which field connects the New Car Sales table with the Car Manufacturer table?
(c) Give two reasons why List of Extras in the Car Manufacturer table is stored in code form.
(d) A customer goes into the showroom and the salesperson keys in 162154. What fields
and information would be shown on the output screen?
(e) Give one advantage to the car sales company of holding customer information on a
database.
A database has been set up to bring together information about the world‟s tallest
buildings.
A section of the database is shown below.
(a) How many records are in the section of the database shown?
(b) (b) Using Ref No. only, which records would be output if the following search
condition was entered:
(Year < 1990) AND (Height (m) > 375)?
(c) Write down a search condition to find out how many buildings are in China or how
many buildings have more than 80 floors.
(d) For each of the following fields give a different validation check.
Year
Ref No.
(e) The database was sorted in descending order of Year. Using Ref No. only, write down
the results of the sort:
(a) Using Car ref only, write down which cars would be output if the following search
condition was used:
(No of doors = 4) AND (Fuel used (km/litre) > 15)
(b) Write down a search condition to find out which cars have engines larger than 1.8 litres
OR have CO2 emissions higher than 150 g/km.
(c) The database is sorted in ascending order on Fuel used (km/litre). Using Car ref only,
write down the results of the sort.
Oct/Nov 2010:
10 A database has been set up to store information about aircraft. A section is shown
below.
(i) The branch and country are coded. Give a reason for this. [1]
(ii) One of the six fields is not appropriate.
Name this field and give a reason for your choice. Suggest an improved field.
Name of field
Reason for choice
Improved field choice [3]
May/June 2011:
A database showing the population of world cities has been produced. A section of the
database is shown below.
Oct/Nov 2011:
An airport has a number of hotels nearby. A database has been set up to give customers
information to allow them to select a hotel.
Oct/Nov 2011:
A database has been set up to show details about countries. Part of the database is shown
below.
May/June 2012:
A database was set up to show the properties of certain chemical elements. Part of the
database is shown below.
Oct/Nov 2012:
A database was set up showing the largest ocean-going liners. Part of the database is
shown below.
May/June 2013:
A database was set up to compare oil companies. A section of the database is shown
below:
May/June 2013:
A survey of motorways was carried out and a database was produced. A section of the
database is shown below.
(a) How many fields and how many records are shown?
(i) number of fields
(ii) number of records
(b) Using Motorway ID only, what would be output if the following search condition was
used?
(Length (km) > 100) AND (Number of lanes > 3)
(c) What search condition is needed to find the motorways where the number of cars per
day exceeds 50 000 or the toll charge per kilometre is greater than $0.50?
(c) A customer wanted to know the possible combinations for a car with leather seats and
either silver or grey paint colour.
What search condition would need to be input? [2]
(d) A customer decided to buy a green car. He wanted to know which seat colours and
seat materials were not a possible combination with green paint.
What search condition would he need to enter? [1]
(e) Give one advantage of using the codes Y and N in the database rather than using Yes
and No. [1]
9 A database was set up to keep track of goods in a shop. A section of the database is
shown below.
(a) How many records are shown in this section of database? [1]
(b) (i) Using Item code only, what would be output if the following search was carried
out:
(Number in stock <Re-order level) AND (Items ordered = “No”) [2]
(ii) What useful information does this search produce? [1]
(c) Write a search condition to locate items costing more than $2.00 or have a stock value
exceeding $300.00. [2]
3 A hospital holds records of its patients in a database. Four of the fields are:
• date of visit (dd/mm/yyyy)
• patient‟s height (m)
• 8-digit patient ID
• contact telephone number
The presence check is one possible type of validation check on the data. For each field,
give another validation check that can be performed. Give an example of data which
would fail your named validation check.
A different validation check needs to be given for each field.
14 A database was set up showing statistics for some states in the USA. Part of the
database is shown below.
(a) (i) How many records are in this section of the database? [1]
(ii) How many fields are in each record? [1]
(b) The following search condition was entered:
(Population (millions) < 4.0) OR (Number of houses (millions) < 4.0)
Using Ref only, write down which records will be found. [2]
(c) Write down the search condition to find out which states have an area over 100 000
square miles and where it takes less than 25 minutes to get to work. [2]
(d) (i) What should be the key field in this database? [1]
(ii) Give a reason for your choice.