0 ratings0% found this document useful (0 votes) 572 views124 pagesPaper2 Programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Chapter 11 Programming Programming Concepts
Chapter 11
Programming Concepts
170 Cambridge Computer Science 0948 (2021)TABLE OF CONTENTS
INTRODUCTION TO PROGRAMMING
SELECTION STATEMENTS ...sesccssssssseseesesssssnnntieeeeeessnnneneseceeesnnnnteeeeetennnnnntestee
Loop STATEMENTS
ARRAYS sssessssesssecssssssnneeseeeesssnnneteeeesnsnnnnaeceeseesnsnnoetecetensnnnneneteeeeennnnneeeeeetens
TRACING
CODE ERRORS «-sssssesseeseeceeesnsneeeeee
DATABASES seseesecessssvssrerseeseensnnnrecereeerensnnerecees
DEFINITIONS ..ssesscscsssssseesececennenenneee
THEORY QUESTIONS ...-cssssssvereeerereesseeee
24
36
43
1 64
TS
100
. 109Introduction to programming
Definition of a program:
A list of instructions that does a specific task.
Example:
Write a program that reads two numbers from the user and print out their sum,
In other words, we need to write a program to solve the following equation:
Z=A+B
Solution:
To write the program we go through four phases:
1 Analysis
2 Design
3. Implementation
4 Testing
1.1 Analysis
In the analysis phase we try to figure out what are the inputs of the program, processing that it
should do and the outputs it shall produce.
Back to our program:
© Inputs: A, B
© Processing: ZA +B
© Output: Ztion to programming
Operators
Types of operators:
1 Arithmetic operators
2 Logic operators
3. Assignment operator
Arithmetic Operators
The following table shows the various Arithmetic operators and what they do:
Arithmetic operators
Operator symbol Description
‘Mulkiplies the left operand by the right operan
Mukiplication ‘ ultiplies the left operand by the right operand.
Example: x* y
Divides the left operand by the right operand
bivision 1 jes the left operand by the right oper
Example: xly
Subtracts the right operand from the left operand
Subtraction
Example: x-y
‘Adds the left operand to the right operand
Addition +
Example: x+y
Raises the left operand to the power of the right operand
Power
owe Example: x” is written as xy
Logic Operators
The following table shows some Logic operators:
‘Comparison Operators
Operator Symbol
Greater than >
Less than <
Equal =
Greater than or equal to
Less than or equal to
Not equal to °Introduction to programming
Assignment Operator
© This operator assigns a value or an expression to a variable.
+ The symbol used for this operator is an arrow pointing left: €
Examples of assignment operator:
cost « 10
Price « Cost * 2
Tax + Price * 0.14
Service + Price * 0.12
Paidamount — Tax + Service
1.2 Design
After the analysis phase is done, we design the Algorithm
An algorithm is a step-by-step solution to a given problem.
We design algorithm using one of two methods:
© Flowcharts
© Pseudocode
1.2.1. Flowcharts
Definition:
Diagram that designs the steps of a program by using a standard set of symbols joined by
Tines to show the direction of flow.
Flowcharts have some shapes that we use to draw the diagram wi
Shape Name Description
An oval represents a start
Cc > Stertiend ond po
or end point
Aline isa connector that
Arrows shows the relationship
between the shapesIntroduction to programming
Aparallelogram
Zo | trouost | seyesemeoupror apt
Adiamond indicates a
decision
Solving our problem using the flowchart desigIntroduction to programming
1.2.2 Pseudocode
Uses English words and mathematical notations to design the steps of a program.
L J
INPUT Keywords
To allow the user to input a value we use one of two keywords:
* INPUT
© READ
OUTPUT Keywords
To show the user the value of a variable we use one two keywords:
© OUTPUT
© PRINT
Writing the program in pseudocode:
ourpur “Please enter two numbers to add”
INPUT A
INPUT B
ZOA+B
ourpur 2
1.3 Implementation
‘After designing the algorithm, the algorithm is transformed into code using a programming
language.
Examples of programming languages:
° CH
Java
© PythonIntroduction to programming
1.4 Testing
The last phase of the programming, this phase is done after implementation by testing how the
program works, we will discuss this later.
Variables
Det ion:
Avariable is a named memory location that stores a value that can change during the
execution of a program
X )
Rules for naming variables:
© Variable names cannot contain spaces
* Variable names cannot start with numbers
© Variable name should not be a keyword of pseudocode
* Variable names should be meaningful to the value it stores
Examples of valid variable names:
© number
© total
© count
© count
© count_students
© countstudents
Examples of invalid variable names:
© count students
© 1count
© ourpurtion to programming
Constants
' Definition:
A constar stores a value that does not change during the
a named memory location th
execution of a program
c >)
Note that:
Constants have the same naming rules as variables.
Data Types
Computers need to know the data type for every variable, to make the processing on this,
variable as ef
ctive as possible.
The following table shows the data types used in programs:
Data type Definition Examples
Integer | APosttve ornegative whole number be used in
eee mathematical operations 150, 100, 0
Appositive or negative number that has a fractional
Real ms i ;
part that can be used in mathematical operations 100.5, -15.2
char ‘single character from the keyboard H
‘ A oh Hello World,
strin sequence of characters
e ‘a A312_@odq
Boolean Data with two possible values TRUE/FALSEIntroduction to programming
Declaration
When declaring a variable you have to do two things:
© Give your variable a valid name
© Give ita data type
Declaration syntax in pseudocode:
DECLARE [VARIABLE NAME] : [VARAIBLE DATA TYPE]
The complete pseudocode solution:
DECLARE Numl: REAL
DECLARE Num2: REAL
DECLARE Sum: REAL
OUTPUT “Please enter two numbers to add”
INPUT Num1
INPUT Num2
sum € Num1 + Num2
OUTPUT “The number is ”,SumIntroduction to programming
Sequential Exercise
Write a program to input length, width and depth of a pool. The program should
output the volume and price of pool
The price of the pool is dependent on the volume: $1 per 100 cm’.
Write a program that inputs 2 mark and raw score. The program should output the
percentage
Write a program that converts a person’s height in inches to centimeters and their
weight in stones into kilograms [1 inch = 2.54 cm and 1 stone 6.364 kg]
Write a pseudocode that inputs days from the user. The program should output how
many weeks and days. A function INT() should be used.
The function takes a number and returns the whole number.
For example INT(1.5) = 1
Write a program that inputs diameter and depth of a round concrete slab in mm. The
price of one slab is $0.05 per 10000 mm’.
HINT: Volume of a cylinder = m*radius**depthSelection Statements
Part!
IF..THEN..ENDIFConditional Statements
Definition of Sequential statements: »)
Statements are executed one after another according to their order.
Definition of Conditional/Selection statements:
Selective statement(s) are executed depending on meeting certain criteria.
Purpose of Conditional statements:
To allow different paths through a program depending on meeting certain criteria }
\ J
2.1 IF .. THEN ., ELSE ., ENDIF:
(a)
Definition:
A conditional structure with different outcomes for true and false.
Purpose:
It allows for checking complex conditions.
IF [CONDITION] THEN
// What to do if the condition is true
ELSE
// What to do if the condition is false
ENDIF
Example 2.1.1:
Design a program, using pseudo-code and flowchart, which takes a number as input and
‘outputs whether the number is zero or non-zero.
Pseudo-code Soluti
DECLARE num: REAL
OUTPUT “Enter a number”
INPUT num
IF num = 0 THEN
oUrPUT “The number is zero”
ELSE
OUTPUT “The number is non-zero”
ENDIF
10Conditional Statements
Flowchart Solution:
Example 2.1.2:
Design a program, using pseudo-code and flowchart, which takes a number as input and
‘outputs whether the number is positive or negative or zero.
Pseudo-code Solution:
DECLARE num: REAL
ourpur “Enter a number”
INPUT num
IF num > 0 THEN
OUTPUT “The number is positive”
ELSE
IF num < 0 THEN
OUTPUT “The number is negative”
ELSE
OUTPUT “The number is negative”
ENDIF
ENDIF
"Flowchart Solution:
Conditional StatementsValidation
Conditional Statements
Often we need to check that the user has not entered unacceptable data, take the example of
dividing two numbers, you cannot divide by zero. So we have to anticipate mistakes users
might do, this is called Validation.
Example:
Read two numbers and divide them Z = A / B.
Pseudo-code Solutio!
DECLARE Numl,Num2,Resul
: REAL
INPUT Num1,Num2
IF Num2 = 0 THEN
OUTPUT “MATH ERROR”
ELSE
Result € Numl / Num2
ourpur Result
ENDIF
BConditional Statements
Design a program, using pseudocode and flowchart, which inputs from the user length
of a square. The program calculates the perimeter of the square.
AN ERROR MESSAGE SHOULD BE DISPLAYED WHEN NEEDED.
Design a program using pseudocode which inputs a number from the user and outputs
the square root. Use a function called Sqrt, which takes a number and returns the
square root of the number
DONOT FORGET TO VALIDATE THE NUMBER.
Design a program, using pseudocode and flowchart, which takes a number between 1
and 7 and outputs the day name (Day 1= Sunday).
An error message should be displaye
the user enters invalid day number
Design a program, using pseudocode and flowchart, that takes two numbers and the
operation as input and performs a basic operation (+, - or *) as per user requires
An error message should be displayed if the user enters invalid operation
4Conditional Statements
Example 2.1.3:
Design a program, using pseudo-code and flowchart, which takes a number and prints
“In range" if the number is between 1 and 10 inclusive, otherwise the program outputs
“Outside range”.
Pseudo-code Solutio
DECLARE Num: REAL
ourpur “Enter a number”
INPUT Nun
IF Num >= 50 AND Num <= 100 THEN
ourpur “In range”
ELSE
OUTPUT “outside range”
ENDIF
Flowchart Solution:
i = ‘output
"Correct Range"
ourpuT
"Wrong Range/
5Example 2.1.4:
Conditional Statements
Design a program, using pseudocode and flowchart, which takes marks in an exam as input
and outputs the grade according to the following grade boundaries:
Mark Grade
90-100 A
80-89 B
70-79 c
<70 F
Pseudo-code Solution:
DECLARE Mar!
INTEGER
ourpur “Enter the mark”
INPUT Mark
IF Mark >= 90 AND Mark <= 100 THEN
ourpur “a”
ELSE
IF Mark >= 80 AND Mark <= 89 THEN
ourpur “5”
ELSE
IF Mark >= 70 AND Mark <= 79 THEN
ourpur “c”
ELSE
IF Mark >= 0 AND Mark <= 69 THEN
ourpur “Fr”
ELSE
OUTPUT “Invalid mark"
ENDIF
ENDIF
ENDIF
ENDIFFlowchart Solution:
Conditional StatementsConditional Statements
Conditional Exercise 2
1 Write a pseudocode that reads a number and prints “Correct range" in case the
number is between 30 and 50 exclusive. Otherwise the program outputs "Wrong
range”.
2 Extend the above pseudocode so that if the number is in wrong range, a message will
be displayed saying whether the number is above range or below range.
3. Design a program, using pseudocode and flowchart, which takes three numbers from
the user and outputs the minimum,
4 Design a program, using pseudocode and flowchart, that takes the salary of 3 months
(salaries cannot be negative) as inputs and output the financial status according to the
following table:
‘Average salary of 3 months Financial Status
>10,000 Rich
2,000 - 10,000 Moderate
<2,000 Poor
DO NOT VALIDATE THE SALARIES.
5 Design a program, using pseudocode and flowchart, that:
- Takes from the user the number of hours worked this week and their hourly
rate of pay.
= The program should calculate and output the gross pay.
= If the number of hours worked is more than 40, then the extra hours are paid 1.5
times the rate.
The program should stop and display an error message if the number of hours worked is not in
the range of 0 to 60 OR if the user entered a negative hourly rate of pay.Conditional Statements
2.2 CASE .. OF .. OTHERWISE .. ENDCASE:
6
Definition:
A conditional structure that allows selection to be made based on value of a variable.
Purpose:
Used to test for a large number of discrete values.
\ /
CASE [ANY VARIABLE] OF
1: // do something if the variable equals 1
// do something if the variable equals 2
OTHERWISE:
// do something if the variable doesn’t equal any of the cases.
ENDCASE
Example 2.2.1:
Design a program, using pseudocode and flowchart, which takes a course number as input and
outputs the corresponding course name according to this table:
Course Number Course Name
1 ‘Computer Science
2 it
3 Math
4 Biology
Pseudocode Solution:
DECLARE CourseNo: INTEGER
OUTPUT “Enter the course number”
INPUT CourseNo
CASE CourseNo OF
1: OUTPUT “compute Science”
2: OUTPUT “ICT”
3: OUTPUT “Math”
4: OUTPUT “Biology”
OTHERWISE
OUTPUT “Invalid Course number”
ENDCASEFlowchart Solution:
Conditional Statements
20Example 2.2.2:
Conditional Statements
Write pseudocode that takes two numbers as input and performs any of the basic operation
-% as per user requires
Solution:
DECLARE FirstNumber, SecondNumber, Result: INTEGER
DECLARE Operation: CHAR
ourpur “Enter the first number”
INPUT FirstNumber
ourpuT “Enter the second number”
INPUT SecondNumber
ourpur “Enter the operation”
INPUT Operation
CASE Operation OF
‘#1: Result € FirstNumber + SecondNumber
OUTPUT Result
‘-': Result € FirstNumber - SecondNumber
ouTPuT Result
‘*': Result € FirstNumber * SecondNumber
ouTPUT Result
‘/' Result € FirstNumber / SecondNumber
OUTPUT Result
OTHERWISE
OUTPUT “Invalid operation”
ENDCASEConditional Statements
Conditional Exercise 3
1 Write a pseudocode that takes from user: length, width and depth of an object. The
user also inputs the object code from the following table:
Object code Object name
1 Square
2 Rectangle
3 Cylinder
(Output the volume of the object based on the user's choice.
HINT:
Volume of cylinder: rr*depth
2. Design a program, using pseudocode and flowchart, that takes three numbers from the
user and prints the numbers in descending order.
3. Write a pseudocode that takes a number from the user and displays whether it's a
negative or zero (don’t output anything if it's positive).
1 Write a pseudocode that inputs the savings of a bank client without interest rate. The
program outputs the updated amount after applying interest according to the
following criteria
= Isavings exceed 500,000, the interest rate is 10%
— If savings exceed 250,000, the interest rate is 5%
= Ifsavings exceed 50,000, the interest rate is 2.5%
~ Otherwise no interest is added
If the user inputs a negative saving, an error message should be displayed and
the program stops without calculating the updated amount. 61Conditional Statements
4 Write a pseudocode that inputs the income of a worker without taxes. The program
must output the updated amount after applying taxes according to the following
criteria
Salary Tax Rate
>10,000 50%
2,000 ~ 10,000 25%
«2,000 ox
Note that the salary cannot be less than 0 and not more than 50,000
5 Write a pseudocode that reads two integer values (x and y), which should represent the
coordinates of a point in a plane. Next, determine which quadrant the point belongs.
Q2}| Qi
Q3 | Q4
If the point is at the origin print “Origin”
's exactly on the x-axis print "X-Axis”
If it’s exactly on the y-axis print “V-Axis”
Otherwise print the name of the quadrant
23Loop Statements
Part |
FOR..NEXTLoop Statements
C
Definition of Iteration/Repetition:
One or more statements are repeated till a test condition is met or whilst a test condition is TRUE.
x
3.1 FOR ... TO... NEXT
(ao)
Def
A loop structure that iterates a set number of times,
x
FOR variable € [initial value] 70 [final value]
// statement(s) to be repeated
Example 3.1.1:
Design pseudo-code and flowchart that prints the integers from 1 to 10.
Pseudocode solution:
FoR i € 1 70 10
ourpur i
NEXT
Flowchart soluti
C=) beter
24Loop Statements
Example 3.1.2:
Write pseudo-code that prints the integers from 10 to 1
Pseudocode solution:
FOR Count € 10 T0 1 STEP -1
ouTPUT Count
NEXT
Totaling
(Se)
Definition:
Totaling is a process of summing a list of number.
Examples:
Total € Total + 5
sum € Sum + Num
Example 3.1.3:
the sum ofall the numbers between 1
Write pseudocode that reads a number N, and pri
and N.
Pseudocode solution:
DECLARE N,Sum: INTEGER
ourpur “Enter
he number”
INPUT N
sum € 0
FOR i € 1 70N
sum € sum + i
NEXT
OUTPUT “The summation is: “, Sum
25Loop Statements
ition:
Counting is the process of finding how many numbers/items are in a list.
Qn)
Examples:
count € count + 1
count € count + 5
count € count — 1
X
Example 3.1.4:
Write pseudocode that inputs 50 numbers and counts the numbers that are greater than 100
Pseudocode solution:
DECLARE Num,Count: INTEGER
count € 0
FoR i € 1 70 100
ourpur “Enter the number”
INPUT Num
IF Num > 100 THEN
count € Count +1
ENDIF
NEXT
OUTPUT “The count of numbers greater than 100 is: ”,Count
26Example 3.1.5:
Write pseudocode that reads 100 numbers and prints out their minimum.
Pseudocode solution 1:
DECLARE Min, Num: INTEGER
Min € 99999
FOR Counter € 1 TO 100
ourpur “Enter number”
INPUT Num
IF Num < Min THEN
Min € Num
ENDIF
NEXT
OUTPUT “Minimum number entered is: “,Min
Pseudocode solution 2 (better solution):
DECLARE Min, Num: INTEGER
ourpur “Enter number”
INPUT Num
Min © Num
FOR Counter € 1 To 99
ourpur “Enter number
INPUT Num
IF Num < Min THEN
Min € Num
ENDIF
NEXT
OUTPUT “Minimum number entered is: “,Min
7
Loop StatementsExample 3.1.6:
Write pseudocode that reads 100 numbers and prints out their maximum.
Pseudocode solution 1:
DECLARE Max, Num: INTEGER
Max € -99999
FOR Counter € 1 TO 100
ourpur “Enter number”
INPUT Num
IF Num > Max THEN
Max € Num
ENDIF
NEXT
OUTPUT “Maximum number entered is: “,Max
Pseudocode solution 2 (better solution):
DECLARE Max, Num: INTEGER
ourpur “Enter number”
INPUT Num
Max € Num
FOR Counter € 1 To 99
ourpur “Enter number
INPUT Num
IF Num > Max THEN
Max € Num
ENDIF
NEXT
OUTPUT “Maximum number entered is: “,Max
28
Loop StatementsLoop Statements
Loop Exercise 1
Write a pseudocode that prompts the user to enter a short message and the number of
times it is to be displayed and then displays the message the required number of times
Write a pesudocode that reads 100 numbers from the user. Then it counts the numbers
that in the range -100 to 35 inclusive.
Write a pseudocode that takes 5 numbers from the user and outputs the maximum.
Write a pseudocode to input 250 numbers. Count how many numbers are positive, how
many are negative and how many are zeros. Then output the results
Write a pseudocode that inputs 500 numbers and outputs how many of these numbers
were whole numbers (integers).
HINT: You may use INT(x) in your answer. For example, INT(3.8) gives the value 3
Write a pseudocode that reads a number and prints out its factorial. The factorial of a
number is calculated by multiplying all the integers smaller than or equal to it until 1
BESSx4x3x2x1
FACTORIAL CANNOT BE DONE ON A NEGATIVE NUMBER!
29Loop Statements
3.2 WHILE ... DO ... ENDWHILE
Zr
Definition:
‘+ Aloop that iterates whilst a specified condition exists
© Criteria is pre-tested (It has criteria check at the start)
= Itmay never run
WHILE (CONDITION) DO
// Code to repeat in here.
ENDWHILE,
Example 3.2.1:
Write pseudocode that reads set of numbers from the user until the user enters a non-positive
number (Less than or equal to zero). The program calculates and displays the total of these
numbers.
Pseudocode solution:
DECLARE Num: REAL
DECLARE Sum: REAL
sum € 0
OUTPUT “Input a number”
INPUT Num
WHILE Num >= 0 Do
sum € Sum + Num
OUTPUT “Input another number”
INPUT Nun
ENDWHILE
OUTPUT “The sum of numbers entered is: “,Sum
30Example 3.2.2:
Rewrite the pseudocode given below by using WHILE...DO...ENDWHILE loop
DECLARE Num, Total : INTEGER
INPUT N
Total € 0
FoR i € 1 TON
Total € Total + i
NEXT
ourpur Total
Pseudocode solution:
DECLARE Num, Total, i : INTEGER
INPUT Num
Total € 0
i€1
WHILE i <= Num Do
Total € Total + i
i € itt
ENDWHILE
ourpur Total
Loop StatementsLoop Statements
3.3 REPEAT ... UNTIL
6
Definition:
© A loop that iterates until a condition is met
* Criteria is post-tested (It has criteria check at the end)
© Ititerates at least once
REPEAT
/1 code to repeat
UNTIL (STOPPING CONDITION)
ifferences between REPEAT ... UNTIL and WHILE ... DO ... ENDWHILE: \
+ In WHILE the criteria is pre-tested but in REPEAT..UNTIL the criteria is post-
tested
‘© WHILE may never run while REPEAT UNTIL runs at least once
© WHILE iterates whilst a condition is TRUE but REPEAT UNTIL iterates
condition is TRUE
Example 3.3.1:
Design pseudocode that inputs set of until the user enters 0. Calculate and display the total.
Pseudocode solution:
DECLARE Sum: REAL
DECLARE num: REAL
sum € 0
REPEAT
ourpur “Enter a number to add”
INPUT num
sum € Sum + num
UNTIL num = 0
OUTPUT “The total of the numbers entered: “,Sum
32Loop Statements
Example 3.3.2:
Write a pseudocode that will take anything as input and will display it as output until “Stop” or
“End” is pressed
Pseudocode solution:
REPEAT
ourpur “Enter a number, value, character or symbol to display”
INPUT anyvalue
ourpur anyvalue
UNTIL anyvalue = “End” OR anyvalue = “Stop”
Example 3.3.3:
Rewrite the pseudocode given below by using REPEAT .. UNTIL loop.
DECLARE Num, Total : INTEGER
INPUT N
Total € 0
FOR i € 1 70 N
Total € Total + i
NEXT
ourPuT Total
Pseudocode solution:
DECLARE Num, Total, i : INTEGER
INPUT Num
Total € 0
i€1
REPEAT
Total € Total + i
a € an
UNTIL i >
ourpuT Total
3BLoop Statements
Co >
IMPORTANT:
Both REPEAT..UNTIL and WHILE..DO..ENDWHILE loops are called Condition Controlled Loops
6 >
Purpose of Iteration/Repetition statements:
To repeat same or similar code a number of times, which allows for shorter code.
Loop Exercise 2
1 Write a pseudocode using that asks the user to enter an age between 1 and 99
inclusive and will validate the input. It should repeatedly ask the user for the age until
the user enters a valid age. The age is then displayed.
DO THIS QUESTION ONCE WITH WHILE AND ONCE WITH REPREAT UNTIL.
2 Write a pseudocode that asks the user to input N weights from the user. The program
then prints the average of those weights.
VALIDATE THE WEIGHTS (CANNOT BE NEGATIVE OR MORE THAN 250)
DON'T FORGET TO VALIDATE N
3 Write a pseudocode that:
+ Inputs numbers tll the user inputs -1
+ Totals the numbers that are between 40 and 80 (inclusive)
4 Suppose you have designed a game that only allows people to play it if they are over
12 years of age.
Write a pseudocode that reads ages of players until the user enters zero, and prints out
the number of players who can play the game, and the number of players who cannot.
34Loop Statements
5 Rewrite the following pseudocode using WHILE .. DO .. ENDWHILE and REPEAT...
UNTIL loop:
INPUT Num
Max € Num
FOR Counter — 1 To 49
INPUT Num
IF Num > Max THEN
Max € Num
ENDIF
NEXT
OUTPUT “The maximum number is :”,Max
6 Write a pseudocode that multiplies two numbers entered by the user without using the
multiplication operator.
7 Write a pseudocode that inputs username and password of an account on a social
network website. In order to return the password for an account, a function called
GetPassword(username) is used. This function takes a username as a parameter and
returns the corresponding password.
- The program displays "Success" if the password of the account is correct,
Ifthe password is incorrect, the program prompts the user to re-enter the
password but only for 3 attempts
ASSUME THAT THE USERNAME ENTERED EXISTS IN THE SYSTEM
35Arrays
4.1 Arrays
Consider the following example:
Example 4.1:
Write a pseudocode that reads 5 numbers from the user and prints them in reverse order.
Pseudocode solution:
DECLARE Numl,Num2,Num3,Num4,Num5: INTEGER
INPUT Num1
INPUT Num2
INPUT Num3
INPUT Num4
INPUT Num5
OUTPUT NumS
OUTPUT Num4
ourpuT Num3
ourpur Num2
ourPuT Num1
This would be okay if you want to reverse few integers, but if you want to reverse 100 integers,
maybe a 1000. We have to use something called an Array.
Array Definition:
A data structure that holds a number of elements of the same data type.
Pseudocode declarat
DECLARE Numbers[1:N] : INTEGER
Nis the number of elements in the array
36Accessing an element in an array:
Arrays
In order to access an element of the array, the index should be specified
For example:
OUTPUT Numbers[1]
This statement will output the value stored in the first place in the array Numbers
Example 4.2:
Write pseudocode that reads 1000 numbers from the user and prints them in reverse order.
Pseudocode solution:
DECLARE Numbers[1: 1000] :
FOR Counter €1 To 1000
INPUT Numbers[ Counter]
NEXT
FOR Counter € 1000 TO 1 STEP -1
ourpur Numbers [Counter]
NEXT
-
Purpose of using arrays:
INTEGER
© To store multiple values under the same identifier making the code shorter
* Allows for simpler programming
37Arrays
Example 4.3:
Write pseudocode that reads the ages of a 100 student from the user and stores them. Then
use the stored values to find the count of students who are older than 18 years.
Pseudocode solution:
DECLARE Ages[1:100]: INTEGER
DECLARE Count: INTEGER
FoR i € 1 70 100
INPUT Ages[i}
NEXT
count € 0
FOR i € 1 70 100
IF Ages[i] > 18 THEN
count € count +1
ENDIF
NEXT
OUTPUT “Count of students older than 18 is: ",Count
38Arrays
4.1 Associative Arrays
Sometimes you might need to store two values about @ certain thing, for example, the name
and age of all students. In this case we'd need to have two arrays, one array for storing the
names, and one for storing the ages.
Example 4.4:
the names and marks of 50 students, stores them and then
Write pseudocode that read:
output the name of the student who scored the highest grade. Marks are out of 100.
Pseudocode solution:
DECLARE Names[1:50]: STRING
DECLARE Marks[1:50]: INTEGER
DECLARE MaximumIndex, MaximumMark: INTEGER
MaximumMark € -1
FoR i € 1 70 50
ourpur “Enter the name of the student ”
INPUT Names[i]
REPEAT
ourpur “Enter the mark of the student ”
INPUT Marks[i}
UNTIL Marks[i]>=0 and Marks[i]<=100
NEXT
FoR i € 1 70 50
IF Marks{i] > MaximumMark THEN
MaximumMark € Marks[i]
MaximumIndex € i
ENDIF
NEXT
OUTPUT “Student with highest mark is : ",Names[MaximumIndex]
OUTPUT “The highest mark is: ”,MaximumMark
39Arrays
Arrays Exercise
1 Write a pseudocode that inputs and stores one temperature per day for a year (365
days),
Display:
+ The maximum temperature in the first 20 days
+ The maximum temperature in the last 20 days
2. Write pseudocode that will take 10 student names and 10 student ages and print #
name of the student with the maximum age.
3. Adata logger records the temperature on a roof of a school twice @ day, at midday and
midnight.
Task 1:
+ Input and store the temperatures recorded for 30 days.
© You must store the temperatures
two arrays, one for midday
ight temperatures.
temperatures and one for mi
* All temperatures should be validated and the user should repeatedly re-enter
the temperatures if they are invalid
o Assume that a valid temperature is between -20 and 100 (5)
Task 2:
+ Calculate and output the average temperature for midday
+ Calculate and output the average temperature for midnight i]
Task 3:
+ Select the day with the highest midday temperature
+ Select the day with the lowest midnight temperature (5)
Don't forget to display appropriate messages for input and output.
40Arrays
4 TASK1
Input and store the names of 500 employees in a company. Also, input and store their
genders and salaries.
+ Gender is either "Male" or “Female”
+ Minimum salary is $1000 and maximum salary is $40,000
TASK 2
The program should display the name and salary of the top paid male worker and the
top paid female worker.
TASK 3.
Determine and output who has higher average salary, male or female workers.
5. The height of buildings and number of floors in buildings were being analyzed.
Task 1
+ Inputs the heights and number of floors of 200 buildings
© Heights should not be negative
co Number of floors cannot be less than 1 or more than 50
Task 2:
* Calculate and output the average height of all the buildings
+ Calculate and output the number of buildings with more than 50 floors
Task 3:
The user inputs number of floors and the program searches for buildings that
has the number of floors specified by the user and outputs the height of the
tallest one from those buildings.
(Note that: not all buildings will be considered when calculating the maximum)
4Arrays
6 Set up a voting system that chooses between 4 candidates. 50 students will vote.
Task 1:
+ Input and store the names of the 4 candidates
+ Output the candidate names with a number (1,2,3 or 4) beside each name
+ Set up another array for voting and set its value to zero
Task 2:
+ Each student inputs a choice between 1,2,3 or 4
+ Update the vote of the appropriate candidate
+ Output the name of the candidate voted for or output ‘invalid vote’ if a vote is
rejected
Task 3:
+ Display the name of the winner and the number of votes.
2Tracing1 The flowchart inputs the size of a number of car engines; a value of ~1 stops the input.
This information is output: average engine size and number of engines with size > 1.5
4B‘Complete the trace table for the input data.
18, 2.0,
1.0, 1.3,
1.0, 25, 20, 1.3,
18, 1.3, -1
Program Tracing
Engine
Count
Number
Average
OUTPUT
44Program Tracing
2 The flowchart below inputs the height of children who want to ride on a rollercoaster. Children
under 1.2 metres are rejected. The ride starts when eight children have been accepted.
Riders +0
Reject — 0
INPUT
Height
Reject + Reject +1
Riders + Riders + 1
ourpuT
"Ready to go
+ Reject
45Complete the trace table for the input data:
14,13, 1.1, 13, 1.0, 15, 1.2, 13,14, 1.3, 09, 1.5, 16, 1.0
Program Tracing
Riders
Reject
Height
ouTPUT
46
(4)Progr
3. The flowchart below inputs the weight of a number of parcels in kilograms, Parcels weighing more
than 25 kilograms are rojectod, A value of —1 stops the input
“The following information is output: the total weight of the parcels accepted and number of parcels
rejected.
Reject
Reject
Total ~ Total + Neight
47‘Complete the trace table for the input data:
1.8, 26.0, 7.0, 11.3, 10.0, 25, 25.2, 5.0, 19.8, 29.3, -1
Program Tracing
Total Reject Weight
‘ourpur
48
(5)Program Tracing
4 This flowchart inputs the weight in kilograms of a passenger stepping into a lift. The lift can take a
maximum of eight passengers or a maximum weight of 640 kilograms.
totalWeight «0
totalNumber +0
totalWeight «totalWeight + Weight
totalNumber «totalNumber + 1
Is
totalNumber
> 8?
49Program Tracing
Complete the trace table for the passenger input data:
50, 70, 65, 100, 95, 50, 55, 85, 70, 75
Weight — totalWeight | totalNumber OUTPUT
(4)
505
Program Tracing
The flowchart below calculates the number of tins of paint required to paint walls. The flowchart
Inputs the height and width of a wall in metres, the number of doors and the number of windows.
‘A value of ~1 for the height stops the input.
START
Area 0
Tins —0
INPUT Height,
Width, Doors,
Windows
‘Tins < INT(Area/10 + 0.5)
ourpUT Tins
Area (Area + Height * Width
= Doors * 1.5 — Windows
Complete the trace table for the input data:
3,5, 1,0, 3, 7,0,0,3,5,0, 3,3, 7,1, 1,-1,0,0,0
‘Area Tins Height Width Doors Windows
4)
51‘Study the flowchart.
‘Complete the trace table for the input values 4, 3, ~1:
A B c OUTPUT
(4)
52Progr
7 This flowchart inputs the type of passenger for a survey: S for Senior, A for Adult, C for Child. All
other values are ignored, apart from Z which ends the process.
Senior «0
Adult + 0
Child + 0
Senior © Senior +1
Adult < Adult +
Child « chita+1 [J
OUTPUT “Seniors ", Senior
T "Adults ", Adult
OUTPUT "Children “, Cl
53Complete the trace table for the passenger input data:
S,8,S,A,C,C,C,A,A,A,A,W, SS, D,C,Z,D,S
Program Tracing
Senior | Adult | Child | Type
OUTPUT
54
6)Program Tracing
8 The flowchart below inputs an integer. The predefined function 0: gives the value othe division,
for example Z— 11 DIV 2 ves the value 2 ~ 2. The predefined function 100 gives the value
tthe mainder, fr example 2 =- 11 cD 2 gives the value 2 = 2.
Fes
Rex DIV
Bex MoD 8
ourpur x
Complete a trace table for each of the two input values 33 and 75.
‘Trace table for input value 33
x A B ‘ourPuT
‘Trace table for input value 75
x A B ‘ouTPUT
(4)
559
Progr ing
(a) The flowchart below inputs six single digit numbers. The predefined function Mop gives the
value of the remainder, for example, ¥ = 10 MOD 3 givesthe value ¥ = 1
Total — Arl+ Bt2+ C#3+ Dd + EFS
Check = Total MoD 11
Ze check >>¥es oureur
P? ‘Accept *
fo
oureur
‘Reject!
56Program Tracing
Complete a trace table for each of the two sets of input data.
Set 5,2,4,3,1,5
Set2 3,2,1,0,7,3
Trace table set 15, 2, 4,3, 1,5
A 8 c > E F | Tota | check | Output
Trace table set 2.3, 2, 1,0,7,
a 8 c > E F | Total | Check | Output
i)
(b) State the purpose of the flowchart in part (a).
1]
(c)_ Identity a problem with this flowchart and explain how to correct it.
Problem
Solution
{3}
3710 (a) The flowchart inputs an integer. The predefined function DIV gives the integer result of the
division, e.g. < 10 DIV 3 gives the value Y
value of the rem
Posne 1
New +0
/ INPUT x /
Tl-xD
T2
‘Tencents
> 0?
OUTPUT “One 5
cent coin"
60Complete the trace table for the input data: 6.29
Program Tracing
Price | Change Dollars | TenCents
OUTPUT
6
(5)12
Jatinder uses Internet banking.
This pseudocode checks her PIN.
INPUT PIN
x — PIN
REPEAT
x/10
PRINT
ELSE
PRINT “PIN OK”
ENDIF
“error in PIN entered”
(a) What value of c and what message would be output if the following PINs were entered?
51020 Value of «:
Message:
5120 Value of c:
Message etn senenen eos 2
613
Program Tracing
This pseudocode inputs the weight of items in kilograms to be loaded on a trailer. Any item over
25 kilograms is rejected. The trailer can take up to 100 kilograms,
TotalWeight € 0
Reject € 0
REPEAT
INPUT Weight
IF Weight > 25 THEN
Reject € Reject + 1
ELSE
Totalweight € TotalWeight + Weight
ENDIF
UNTIL TotalWeight > 100
TotalWeight € Totalweight — Weight
OUTPUT “Weight of items ", TotalWeight ," Number of items rejected *, Reject
Complete the trace table for the input data:
13, 17, 26, 25,5, 10, 15, 85, 20, 15
Weight | Reject | TotalWeight OUTPUT
(5)
63Code ErrorsCode Errors
Read this section of program code that should input 50 numbers and then output the average.
2 For Counter = 1 TO $0
3) INPUT Num
4 Total = Total +2
5 Counter = Counter + 1
6 Average = Total/Counter
NEXT Counter
8 PRINT Average
There are four errors in this code.
Locate these errors and suggest code corrections to remove each error.
1
[4]
64Code Errors
Read this section of program code that inputs twenty (20) numbers and then outputs the largest
number input.
1 h=o0
2 e=0
3. REPEAT
4 READ x
5 IF ¥>h THEN x = h
6 eset.
7 PRINT h
8 UNTIL c < 20
There are three errors in this code,
Locate these errors and suggest a corrected piece of code.
i}
65Code Errors
3 Read this section of program code that should input 30 positive numbers and then output the
largest number input.
1
2
8
9
Large = 9999
counter = 0
WHILE Counter > 30
Do
INPUT Num
IF Num < Large THEN Large = Num
counter = Counter - 1
ENDWHILE
PRINT Large
There are four errors in this code.
Locate these errors and suggest a corrected piece of code for each error.
66
[4]Code Errors
4 Read this section of program code that should input 10 positive numbers and then output the
smallest number input.
1 small = 0
2 Counter = 0
3. REPEAT
4 INPUT Num
5 IF Num < Small THEN Num = Small
6 Counter = Counter +1
7 PRINT Small
8 UNTIL Counter < 10
There are four errors in this code.
Locate these errors and suggest a corrected piece of code for each error.
1
67
[4]Code Errors
Read this section of program code that inputs 10 positive numbers and then outputs the smallest
number input.
Small = 1000
Counter = 0
REPEAT
INPUT Num
IF Num < Small THEN Small = Num
Counter = Counter + 1
UNTIL Counter = 10
PRINT Small
(i) Identity three changes you would need to make to find the largest number input instead
of the smallest number.
3]
(ii) Rewrite the program code with your changes.
[3]
68Code Errors
Read this section of code that inputs the ages of people entering an event. The input sequence is
‘ended by inputting a negative value for age. The code outputs the number of people at the event
over the age of 18.
01 = Numig = 0
02 UT Age
03 WHILE Age
04 IF Age >= 18 THEN
05, Numl8 = Numlé + Age
06 ENDIF
07° ENDWHILE
08 PRINT Numi8 ~
There are four errors in this code.
Locate these errors and suggest code correction to remove each error.
Error 1...
Correction...
Error 2...
Correction.
Error 3
Correction.
Error 4
Correction.
[4]
69Code Errors
7 Read this section of program code that inputs 10 positive numbers and then outputs the total.
Total = 0
Counter = 0
REPEAT
INPUT Num
PRINT Total
Counter + 1
1
2
3
4
5 Total = Total + Num
6
7 counter
8
UNTIL Counter = 10
This code works, but it
(i) Suggest three improvements that could be made.
inefficient,
Tacs
{3]
(li) Rewrite the program code with your improvements.
(3)
70Code Errors
‘There are four errors in this code.
Locate these errors and suggest @ correction to remove each error
Error 1 ..
Correction ..
Error2 ..
Correction ..
Errors ..
Correction ............-.-
Error4 ..
Correction ..
nCode Errors
9 Read this section of program code that:
* inputs 10 numbers
* checks whether each number is within a specified range
totals the numbers within the range and outside the range
1 InRange = 0
2 OutRange 1000
3. FOR Count = 1 70 10
4 INPUT Num
5 IF Num > 10 AND Num < 20 THEN InRange = InRange + 1
6 ELSE OutRange = OutRange - 1
7 Count = Count +1
8 NEXT x
9 PRINT InRange, OutRange
(a) There are four errors in this code.
Locate these errors and suggest a correction to remove each error.
Error
Correction
Error 2.
Correction ..
Error 3,
Correction
Error 4.
Correction ...
[4]
RCode Errors
(©) Decide, with reasons, whether the numbers 10 and 20 are within or outside the range.
within | Outside
Number | jaye) | renge (2) Reason
10
20
(4)
BCode Errors
10 (a) An algorithm has been written in pseudocode to input 50 numbers and total only the positive
numbers.
count — 1
Total —
REPEAT
INPUT Number
IF Nunber <> 0
THEN
Total # Total + Count
ENDIF
Count Count + 1
UNTIL Count < 50
PRINT Total
Find the four errors in the pseudocode and suggest a correction for each error.
unt
Error 1 ..
Correction
Error 2
Correction...
Error 3
Correction ..
Error 4 ..
Correction
[4]
(b) Show how you would change the corrected algorithm to only total numbers greater than 0
and less than 20.
e]
74Databases1. Data types used in database
Data Type Examples
Number 12, 45, 1274, 653.12, -35.86
Currency £12.45, -£0.01, €999.00, $5500
Text DOG, ABC123, enquiries@bbc.co.uk
Boolean TRUE/FALSE and YES/NO
Date 25/10/2007, 12 Mar 2008, 10-06-08
2. Selecting Data Types
When we input data to a database, we must analyse it and select appropriate data types for
each field:
Student Name: [Bensmith «| Text
Student Number: fiz34S~S~*d™:sCNu ber
Date of Birth: 10 duly 1998 Date
Year Group: é Number
Special Diet: [Yes | Boolean
Height: [1.67 | Number
Fees Paid: $1500 Currency
3. Definition of Database
A structured collection of related data that allows people to extract information in a
way that meets their needs.
Databases are very useful in preventing data problems occurring because:
* Data is only stored once - no data duplication
‘= Ifany changes are made it only has to be done once - the data is consistent
‘+ Same data is used by everyone
754. The structure of a database
Inside a database, data is stored in tables, which consists of many fields and records.
| Table
| Record 1 | Field 1 Field 2 Field 3 | Field 4
| Record 2 | Field 1 Field 2 Field3 | Field 4
| Record 3 | Field 1 Field2 _| Field3 _| Field 4
| Record 4 | Field 1 Field 2 | Field 3 | Field 4
Record 5 _| Field 1 Field 2 Field 3 | Field 4
Record6 | Field 1 Field2 | Field3 _| Field 4
The following table shows some database elements and their defi
Term Definition Examples
Table/File A collection of related records Table of students
For a student the fields
could include:
«Student name
Feld A.column that contains one specific piece of + Student ID
information and has one data type * Age
+ Address
* Gender
Field Name _| Title given to each field and is always placed at
the top row of table
A row within a table that contains data about a | Details (all information) of
Record
single item, person or event
one student
Primary Key/
Key Field
A field that contains unique data and can’t be
repeated for more than one once
Student ID field
76Databases
Arowis the table ‘The FIELD NAMES are
isa RECORD the column headings
/ SI
/ Student Yeor Special Exom Fees
Nome Number | Date of sith Group Telephone _—Diet_Score Height Paid
| |
susan anmao|] 1423 |] 5* mayi99s | 7 | (0334) 4537564! NO 67% 154 | $1500
iaueoau || o377_|[2s"aumesti996 _¢ (0332) 343 7543 | yes 55% 2.60 _ $1600
ween worms || 1103 {| rsanuary 1956 | a | (oraz)aseseas | NO 9% | 143 | $500
| 1
sensu || ozs || ror swiviges | 6 | oxsayracssra| ves | rex 67 | s1s00
KEY FIELD
column
y \
Note that:
Primary keys are used to:
* Tobe sure that each record can be found easily
* To prevent duplication of records
7Databases
5. Query By Example
In order to select data with some specific criteria from a database, we use queries.
Let’s consider the following example:
‘A database, PROPERTY, was set up to show the prices of properties for sale and the features of
each property. Part of the database is shown below.
Property Type | OU" | Bedrooms | Batroomes | Garden | Garage ‘ine?
Bungalow By) O7]”SCtdYStét« Yes Yes | 750,000
Apartment ‘A08 2 1 No No | 100,000
House Hi0 4 2 Yes | No | 450,000
House His 3 2 Yes | No | 399,000
Apartment 01 2 2 No | Yes | 95,000
Apartment Ae 1 1 No No | 160,000
House wa | 3) | 4 No Yes _| 250,000 |
House HAG 2 1 Yes | Yes | 175,000
The following is a query-by-example grid:
Here, we enter the name of fields
‘that are involved in our search
We write the table name of each
field. In our case i's PROPERTY We tick the fields that we need to
show
Here, we write our
search criteria
2BThe following query-by-example grid selects and shows the Prices and Brochure numbers of all
houses with more than 1 bathroom and more than 2 bedrooms in ascending order of Price.
Field: Property Type |Number of Numbetet Price in$ | Brochure No
Table: PROPERTY [PROPERTY [PROPERTY __|PROPERTY [PROPERTY
sont Ascending
Show: oO O { vi
pe 5
The results shown are:
399,000 H13,
450,000 H10
6. Validation
The automated checking by a program that data to be entered is sen:
Examples of validation checks:
+ Type
+ Presence
© Range
* Length
© Character
= Format
+ Check digit
79
ible.5.1 Type Check
Definition:
Checks that the data entered has the appropriate data type.
Example:
A person's age should be a number not text.
5.2 Presence Check
Definition:
Checks that some data has been entered and the value has not been left blank
Example:
‘An email address must be given for an online transaction
Breoeer Lo
("= Required)
Emait
5.3 Range Check
Defi
It checks that only numbers within a specified range are accepted
ion:
Example:
Exam marks between 0 and 100 inclusive.
5.4 Length Check
Defi
It checks that data contains an exact number of characters
ion
Example:
A password with exactly 8 characters in length. If the password has fewer or more than 8
characters, it will be rejected
805.6 Character Check
Definition:
It checks that a string of characters does not contain any invalid characters or symbols.
Examples:
+ Aname would not contain characters such as %
* Atelephone number would only contain digits.
5.7 Format Check
Definition:
It checks that the characters entered conform to a pre-defined pattern
Example:
‘A company with IDs that start with MS then three numbers would have a format of MS#iit
5.8 Check Digit
Defi
A digit that it is calculated from all the other digits and appended to the number.
jon:
They can usually detect the following types of error:
© Anincorrect digit entered
o For example 5327 entered instead of 5307
* Transposition errors where two numbers have changed order
o For example 5037 instead of 5307
© Removing a digit
© For example 537 instead of 5307
Putting an extra digit
© For example: or 53107 instead of 530
81Example:
ISBN 978-0-340-98382-9
7803409838291
Figure 9.8 ISBN 13 code with check digit
‘An example ofa check digit calculation is ISBN 13, where the 13th digit of the ISBN
code is calculated using the following algorithm.
1 Add all the odd numbered digits together, excluding the check digit.
2.Add all the even numbered digits together and multiply the result by 3.
3 Add the results from 1 and 2 together and divide by 10.
4 Take the remainder, ifit is zero use this value, otherwise subtract the remainder
from 10 to find the check digit.
Odd digits
“IN
9780340983826
See
Even digits
Figure 9.9 ISBN
Using the ISBN above 9 7 8 0 3 4.09 8 3 8 2 without its check dij
19+8+3+0+8+8=36
23(7+0444943+2)=75
3 (36+ 75/10 = 11 remainder 1
4101 =9 the check digit.
To check that an ISBN 13 digit code is correct a similar process is followed.
1 Add all the odd numbered digits together, including the check digit.
2 Add all the even number of digits together and multiply the result by 3.
3 Add the results from 1 and 2 together and divide by 10.
4 The number is correct if the remainder is zero.
Using the ISBN above 9 7 8 03 4.098 3 8 2 9 with its check digit:
19+8+3+0+8+8+9=45
23(7+0+44+94+3+2)=75
3 (45 + 75)/10 = 12 remainder 0
4 Remainder is 0 therefore number is correct.
827. Data Verification
Def
Checking that the data has not changed during input to a computer or during transfer
ion:
between computers.
Purpose:
To ensure the accuracy of transcription.
Verification methods include:
* Screen/Visual check
+ Double entry
Screen/Visual Check
Det
jon:
«Data is compared visually with the source document by a user
«The user is asked to confirm that the data entered is same as original
+ Ifuser finds a difference, the data is re-entered
Double Data Entry
Definition:
«Data is entered twice (sometimes by two different people)
© Acomputer checks that both entries are equal
«If they are not equal, an error message requesting to re-enter the data is displayed
Customer information
Emali: john@rome.net
Confirm email; John@neme.net
Password
Confirm password:
Caneel Submit
( Note tha
Double data entry is different from Proofreading!
Proofreading is reading through the document, without referring to the original
source document, to identify grammatical and spelling mistakes
838. Testing Data
Definition:
Data used to check that a computer program responds correctly to correct and incorrect
data.
Definition
Examples
Normal
Data
Correct data that should be accepted
The month can be any whole
number in the range of 1 to 12
Abnormal
Data
Data outside the limits of acceptability,
or wrong type of data, and should be
rejected
All the following values are not
allowed as inputs for the month
+ Negative numbers
‘+ Any value greater than 12
+ Letters or non-numeric data
+ Non-integer values
(e.g.,3.5,10.75, ete.)
Extreme
Data
Data
t the limits of acceptability and it
should be accepted
The extreme values of month can
be either 1 or 12
Boundary
Rejected
Data
The rejected data on the boundaries
Boundary rejected values of month
can be either 0 or 13,
84Databases
Database Exercise
A database was set up to show the properties of certain chemical elements. Part of the database
is shown below.
Name of | Element | Atomic | Atomic | Melting | Boiling | State at
element | symbol | number | weight | point (C) | point (Cc) | room temp
oxygen ° 8 16 -218 -183 gas
iron Fe 26 56 1538 2861 solid
mercury Hg 80 201 38 356 liquid
bromine Br 35 80 7 59 liquid
osmium Os 76 190 3033 5012 solid
caesium Cs 55 133 28 671 solid
galium | Ga 3 70 30 2204 solid
argon | Ar 18 40 -189 -186 gas
silver Ag a7 108 961 2162 solid
(a) How many fields are in each record?
(b) The following search condition was entered:
(Melting point (C) < 40) AND (Atomic weight > 100)
Using Element symbol only, which records would be output?
(c) Which field would be best suited as primary key?
85Databases
2 Adatabase table, DEVICE, has been set up to record the electronic equipment used in a sma
business.
Device ID | Device Type | User Purchase | Purchase | Portable
Date Price (S)
3 | Desktop ‘Alan Swales | 14/02/2017 | 1350.00) NN
4 | Laptop ‘Chantel Law | ovoz2016 | 1460.00|
5 | Tablet Abdula Saud | 31/12/2016 | 1000.00) Y
6 Desktop Abdula Saud | 14/03/2017 1000.00 N
7 — | Laptop ‘Alan Swales | 15/03/2016 | 1700.00| Y
8 | Tablet Taona Jaji | 16/12/2016 | 470.00|
(a) The query-by-example grid below selects certain records.
Field: User
Table: DEVICE
Sort: | Ascending
‘Show: 4
Criteria:
or:
Portable
DEVICE
Purchase Price (S)
DEVICE
>1000
‘Show what would be the output from the query-by-example.
2)
(b) Complete the query-by-example grid below to select all Desktop devices that were either
purchased before 31/12/2016 or cost under $1000. Only show the Device ID and Device
Type.
Field:
Table:
Sort:
Show:
Criteria:
or:
86
(4)Databases
3 A database, MARKS, was set up to record the test results for a class of students. Part of the
database is shown below.
Student Name | Class ID | Maths | English | Science | History | Geography
Paul Smith 0017 70 55 | 6S 62 59
Ravi Gupta 0009 23 34 | 38 at 44
Chin Hwee 0010 43 47 | 50 45 52
John Jones | 0013 37 ey | at 28 35
Diana Abur 0001 92 885 89 78
Rosanna King | 0016 at 13 | W 27 15,
(a) Give the number of fields that are in each record,
(b) State which field you would choose for the primary key.
Give a reason for choosing this field.
(2)
(c) The query-by-example grid below selects all students with more than 60 marks in History or
more than 60 marks in Geography.
Field: | Student Name History Geography
Table: | MARKS MARKS MARKS
Sort: | Ascending
Show: iv
Criteria 360
or 360
Show what would be output.
87Databases
(4) Complete the query-by-example grid below to select and show the student names only of all
students with less than 40 marks in both Maths and English.
Field: |
Table |
Sort: |
|
|
|
Show:
Criteria:
or:
(3)
4 Adatabase, PROPERTY, was set up to show the prices of properties for sale and the features of
each property. Part of the database is shown below.
PropertyType | P°No' | Beareome | Batroome | Carden | Garage |
Bungalow B17 7 4 Yes Yes | 750,000
Apartment ‘A09 2 1 No No | 100,000
House H10 4 2 Yes No _ | 450,000
House H13 3 2 Yes No | 399,000
Apartment Adt 2 2 No Yes | 95,000
Apartment AI6 1 1 No No | 150,000
House H23 3 1 No Yes | 250,000
House H46 2 1 Yes Yes | 175,000
(@) Give the number of fields that are in each record.
(b)_ State which field you would choose for the primary key.
Give a reason for choosing this field.
(2)
88©)
State the data type you would choose for each of the following fields.
Garage
Number of Bedrooms ...
Priceins ..
[3]
(@) The query-by-example grid below selects all houses with more than 1 bathroom and more
than 2 bedrooms.
Prony pe umber! Mumbercl——Pveeing—_[RrachureNo
:| PROPERTY PROPERTY PROPERTY |PROPERTY PROPERTY
| Ascending
[ wv vj
22 >I |
‘Show what would be output.
(21
(@) Complete the query-by-example grid below to select and show the brochure number, property
Field:
Table:
Sort
Show:|
Criteria:
a
type and price of all properties with a garage below $200,000.
89
iaDatabases
5 A database table, JEWEL, is used to keep a record of jewellery for sale in a shop. Each item of
jewellery can be made of silver, platinum or gold metal. The shop stocks rings, bracelets and
necklaces. The number in stock and the price is also stored.
(a) Identify the four fields required for the database. Give each field a suitable name and data
type. Explain why you chose the data type for each field.
Field 1 Name .. . Data type
Explanation .
Field 2 Name Data type
Explanation ..
Field 3 Name ..
cove Data tYP@ snr
Explanation ..
Field 4 Name .....
. Data type
Explanation ...
(b) Explain why none of these fields could be used as a primary key.
(1]
(©) Using the query-by-example grid below, write a query to identify the silver bracelets. Only
display the number in stock and the price.
Field:
Table:
Sort:
Show: oO oO Oo oO
Criteria:
or:
3)
906 Apicture
Databases
gallery owner has decided to set up a database to keep information about the pictures
he has for sale. The database table, PICTURE, will contain the following fields:
Title; Artist; Description; Catalogue Number; Size (area in square centimetres); Price; Arrived (date
picture arrived at gallery); Sold (whether picture is already sold)
@ @
i
(b)
(©)
Table:
Sort:
Show:
Criteria:
or:
State what data type you would choose for each field.
Title
Artist .
Description ..
Catalogue Number
Size
Price ..
Arrived snc oe
Sold [4]
2 z (1)
Give a validation check that you can perform on each of these fields. Each validation check
must be different.
Catalogue NUMBEF ....cncisnnmnninnne
Size
PRICE aeeneeenne svtenneneee
Arrived .. (4)
Complete the query-by-example grid below to select and show the Catalogue Number, Title
and Price of all unsold pictures by the artist Twister’.
(5)
91Databases
7 A database, STAFFPHONE, was set up to show the telephone extension numbers for members of
staff working in a department store.
Name Department | Extension number
Jane Smith Toys 129
‘Sue Wong Books 124
David Chow Toys 129
‘Amy Tang Household 123
Joe Higgs Books 124
Jane Smith Shoes 125
‘Adel Abur ‘Shoes 125
Pater Patel Toys 129
(@) Explain why none of the fields in the database can be used as a primary key.
(b) State a field that could be added as a primary key.
Give a reason for choosing this fiald.
2)
(©) Uso the query-by-example grid below to provide a list of all members of staff, in alphabetical
order, grouped by department.
Field:
Table:
Sort:
Show: Oo
Criteria:
or:
5)
928 A database, SOFASELECT, was set up to show the prices of suites, sofas and chairs for sale from
an online furniture warehouse. Part of the database is shown below.
Renee eo aes Cour | Price ins
sola sv | 21 | tae | Red | 0
Sol sae [81 | wit | Bak | h000
sat cu [4 |e | whet | areon | 1.500
ait aus [88 | tether | Bim | 80
Reoliner chair RCO1 1 1 Leather Cream 600
Cher cis [| 1) 1] vim | Red | ato
Recliner sofa AS23 4 1 Leather Cream 1,200
Char cio [1 | vent [rea |e
(a) How many fields are in each record?
(b) State which field you would choose for the primary key.
93Databases
(d)_ The query-by-example grid below selects all the furniture in cream leather.
Field: Description | Material Colour Price in § Brochure Number
Table: SOFASELECT |SOFASELECT |SOFASELECT |SOFASELECT |SOFASELECT
Sort Descending
‘Show: iv v| |
Criteria: = ‘Leather = ‘Cream’
or:
‘Show the output from the query-by-example.
[3]
(e) Complete the query-by-example grid below to select and show the brochure number, material,
colour and price of all the furniture with 3 or more seats.
Field; |
Table;
Sort:
Show: oO [iy | oO
Criteria:
or:
6)
(©) State the data type you would choose for each of the follawing fields.
Number of Seats ..
Price in $
949 A database, THEATRETOURS, was set up to show the tour dates, towns, number of seats and
prices in local currency for a Shakespeare play.
Town Tour Date | Number of Seats | Price Local Currency
Wigan 18/08/2016 120 15.00
Dumtries 20/08/2016 160 12.50
Turin 25/08/2016 200 17.00
Macon 27/08/2016 75 18.00
Bordeaux 29/08/2016 170 20.00.
Algiers 01/09/2016 125 1350.00
Windhoek 05/09/2016 65 90.00
Windhoek 06/09/2016 65 90.00
Port Elizabeth 10/09/2016 200 110.00
(a) Explain why none of the fields in the database can be used as a primary key.
AZ]
(b) State a ficld that could be added as a primary key.
Give a reason for choosing this field
(2
(c) Use the query-by-example grid below to provide a list of tour dates and seat prices in
alphabetical order of town.
Field:
Table:
Sort:
Show oO o Oo U
Criteria:
or:
(41
95Databases
10 A database, PLAYPRODUCTION, was set up to show the performance dates, prices and number
of seats available at a theatre specialising in Shakespeare productions.
vo Meco ee "ee nat ancy
Stalls Circle
As You Like It 01/07/2016 120 90 20.00 30.00
As You Like It 02/07/2016 8s 45 30.00 40.00
As You Like It 09/07/2016 31 4 30.00 40.00
Macbeth 14/07/2016 101 56 25.00 35.00
Macbeth 15/07/2016 50 34 25.00 35.00
Macbeth 16/07/2016 12 5 35.00 50.00
Julius Caesar 22/07/2016 67 wm 20.00 20.00
Julius Caesar 23/07/2016 21 24 15.00 15.00
AComedy of Errors 30/07/2016 45 36 35.00 45.00
(a) Give the number of fields that are in each record.
1)
(b) State the data type you would choose for each of the following fields.
Play
Number Seats Stalls ..
Price Stalls Seats §
- [3]
(©) The query-by-example grid below selects all the productions with more than 100 seats left in
either the stalls or the circle.
Field: | Play Performance Date | Number Seats Stalls | Number Seats Circle
Table: | PLAYPRODUCTION | PLAYPRODUCTION | PLAYPRODUCTION | PLAYPRODUCTION
Sort: | Ascending
‘Show: v v
Criteria: > 100
or: > 100
‘Show what would be output from the query-by-example.
3
96(4) Complete the query-by-example grid below to select all the productions with at least six seats
left in the circle and show the Play, Performance Date and Price Circle Seats $ in Performance
Date order.
Field
Table:
Sort:
Show: oO L LI ul
Criteria:
or:
15]
711 Adatabase table, BIKETYRES, is used to keep a record of tyres for sale in a cycle shop.
‘Tyres are categorised by width and diameter in millimetres, whether they have an inner tube and
the type of terrain for which they are designed.
Databases
‘Tyre Code Width Diameter Tube Stock Level
Sut 23 700 YES 18
MLNT 24 700 NO 23
LLUNT 28 700 NO 19
sL™ 23 700 YES 22
MLTM 24 700 YES 14
uT™ 28 700 YES 12
‘SLTH 23 700 YES 10
MLTH 24 700 YES 5
LLNH 28 700 NO 7
‘SLNM 23 700 NO 12
MLNM 24 700 NO Mixed 22
LLNM 28 700 NO Mixed 18
‘SSNT 23 650 NO Asphalt 10
MSNT 24 650 Xe) Asphalt 8
SSTM 23 650 YES Mixed 5
MSNM 24 650 NO Mixed 4
‘The query-by-example grid below displays the tyre code and the stock level of all 28mm width
tyres suitable for mixed terrain.
Field: Tyre Code
Sort:
‘Show:
Stock Level ‘Width Terrain
Table: BIKETYRES BIKETYRES BIKETYRES BIKETYRES
oO oO
=28 = Mixed’
Criteria: |
or:
Alter the query to show the tyre code and stock level in ascending order of stock level for all
24mm asphatt terrain tyres. Write the new query in the following query-by-example grid.
Field:
Table:
Sort:
Show:
Criteria:
or:
98
[4]Databases
12 Adatabase table, PORTRAIT, is used to keep a record of the portraits available from a photographic
studio. Each portrait has a unique reference number PICnnn, where nis a single digit, for example
PIC123. The studio keeps a record of the size (for example 20 x 15), the type (black and white or
colour), and the price in dollars.
(a) Complete the table to show the most appropriate data type for each of the fields.
Field Data type
Reference Number
Size
Type
Price in $
(4)
(b) The results from the query-by-example grid should show the reference number, price, type
and size of all portraits under $50. Identify the three errors in the query-by-example grid.
Field: | Reference No —_Price in $ ‘Type Size
Table: | PORTRAIT PORTRAIT PORTRAIT PORTRAIT
Sort:
Show: 7] Z ] 7
Criteria:
or:
Error 1 ..
Error 2 .....
Error 3 ...
G]
99DefinitionsDefinitions
4. Program
Definition:
© A\list of instructions that does a specific task
+ It can be written in High Level language or Low Level Language
2. Pseudocode
Definition:
Method that uses English words and mathemat
program
al notations to design the steps of a
3. Flowcharts
Definition:
Diagram that designs the steps of a program by using a standard set of symbols joined by
lis
to show the direction of flow.
4, Trace Table
Definition:
+ Table that can be used to record the results from each step in an algorithm
© Itis used to record the value of a variable each time it changes
5. Variable
Definition:
A named data store that contains a value that ean change during the execution of a program.
6. Constant
Definition:
‘A named data store that contains a value that does not change during the execution of a
program.
100Definitions
7. Program data types:
Data type Definition Examples
A positive or negative whole number be used in 150
Integer
mathematical operations -100
A positive or negative number that has a
100.5
Real | fractional part that can be used in mathematical 152
operations
Char ‘A single character from the keyboard H
Hello World
String ‘A sequence of characters ,
A312_@odq
Boolean Data with two possible values TRUE/FALSE
8. Sequential statements
Definition:
Statements are executed one after another according to their order.
ional/Selection statements
Selective statements) are executed depending on meeting certain criteria
Purpose:
To allow different paths through a program depending on meeting certain criteria
410. IF .. THEN .. ELSE .. ENDIF
Definition:
A conditional structure with different outcomes for true and false.
Purpose:
It allows for checking complex conditions.
101Definitions
11. CASE .. OF .. OTHERWISE .. ENDCASE
Definitio
A. conditional structure that allows selection to be made based on value of a variable.
Purpose:
Used to test for a large number of discrete values.
12. Iterative/Repetition statements.
Definiti
One or more statements are repeated till a test condition is met or whilst a test condition is,
TRUE.
Purpose:
To repeat same or similar code a number of times, which allows for shorter code.
43. FOR .. TO .. NEXT
Definition
A loop structure that iterates a set number of times.
14, WHILE .. DO .. ENDWHILE
Definition:
© Aloop that iterates whilst a specified condition exists
* Criteria is pre-tested (It has criteria check at the start)
© Itmay never run
45, REPEAT .. UNTIL
Definition:
+ Aloop that iterates until a condition is met
© Criteria is posttested (It has criteria check at the end)
© Ititerates at least once
Differences between REPEAT ... UNTIL and WHILE ... DO ... ENDWHILI
© In WHILE the criteria is pre-tested but in REPEAT..UNTIL the criteria is post-tested
© WHILE may never run while REPEAT... UNTIL runs at least once
© WHILE iterates whilst a condition is TRUE but REPEAT UNTIL iterates till a condition is
TRUE
102Definitions
16. Totaling
Definition:
The process of summing a list of number.
Example:
sum € Sum + Num
17. Counting
Definition:
The process of finding how many items are in a list.
Example:
count € count + 1
18. Array
Definiti
A data structure that holds a number of elements of the same data type
Purpose:
* To store multiple values under the same identifier making the code shorter
* Allows for simpler programming
19. Top-Down design
Definiti
The breaking down of a computer system into set of sub systems and then breaking each
subsystem into set of smaller ones until each sub system performs a single action
18. Structure Chart
Definit
Diagram that shows the design of a computer system in a hierarchal way, with each level
giving a more detailed breakdown of the system
103,Definitions
19. Library rou
Definition:
It is a list of programming instructions that is:
© Given aname
© Already available for use
© Pre-tested
Advantages of using library routines:
+ Library routines make writing programs easier and faster as the code is already written
© They make testing the program easier as the code has already been tested and
debugged
20. Subroutine
Definition:
+ Set of programming statements for a given task and given a name
© Subroutine is written in High Level Language
* Can be procedure or function
21. Function
Definition:
A subroutine that always returns a value
22. Procedure
Definition:
A subroutine that doesn’t return a value,
23. Database
Definition:
A structured collection of related data that allows people to extract information in a way that
meets their needs.
10424. Database terms:
Definitions
Term Definition Examples
Table/File A collection of related records Table of students
Fora student the fields
could include:
* Student name
Field A column that contains one specific piece of © Student ID
information and has one data type + Age
© Address
* Gender
Field Name Title given to each field
A row within a table that contains data about a | Details (all information) of
Record
single item, person or event one student
Primary Key/ | A field that contains unique data and can’t be
Student ID field
Key Field repeated for more than one once
105,25. Validation
Definition:
Definitions
The automated checking by a program that data to be entered is sensible.
26. Examples of validation checks:
Validation
Definition Examples
check
h the data enter .
Type Cheek Checks that the data entered has the | person's age should be
appropriate data type a number not text
‘An email
Presence | Checks that some data has been entered ermal across me be
Check and the value has not been left blank given fora Onin’
transaction
Range Check It checks that only numbers within a
specified range are accepted
Exam marks between 0
and 100 inclusive
It checks that data contains an exac
Length Check | thet data conte *
number of characters
A password with exactly 8
characters in length
Character | it checks that a string of characters does not|
Check contain any invalid characters or symbols,
Aname would not contain
characters such as %
It checks that the characters entert
Format Check It checks that the characters entered
conform to a pre-defined pattern
A company with IDs that
start with MS then three
numbers would have a
format of MS###
JA digit that itis calculated from all the other
digits and appended to the number
Used in barcodes
106Definitions
26. Verification
Definition:
Checking that the data has not changed during input to a computer or during transfer between
computers.
Purpose:
To ensure the accuracy of transcription.
Types:
* Screen/Visual Check
* Double Data Entry
27. Screen/Visual Check
Definiti
+ Data is compared visually with the source document by a user
* The users asked to confirm that the data entered is same as original
© fuser finds a difference, the data is re-entered
28. Double Data Entry
Definition:
+ Data is entered twice (sometimes by two different people)
+ Acomputer checks that both entries are equal
© If they are not equal, an error message requesting to re-enter the data is displayed
10729. Testing data
Definition:
Definitions
Data used to check that a computer program responds correctly to correct and incorrect data
30. Types of test data:
Type Definition Examples
Normal} Correct data that should be accepted | the month can be any whole
Data number in the range of 1 to 12
All the following values are not
allowed as inputs for the month
Data outside the limits of acceptability,
‘Abnormal | 0" wrong type of data, and should be | ‘Negative numbers
© Any value greater than 12
Data rejected
© Letters or non-numeric data
+ Non-integer values
(e.g.,3.5,10.75, etc.)
Data at the limits of acceptability and it |The extreme values of month can
Extreme should be accepted be either 1 or 12
Data
Boundan
Y - Boundary rejected values of month
Rejected | The rejected data on the boundaries
Dot can be either 0 or 13,
108Theoretical Questions‘Theory Questions
Theory Questions
A satellite navigation system works using destination details entered by the user, either a new
destination or chosen from previously saved destinations. The satelite navigation system will then
‘output directions to the destination in the form of either a visual map or a list of directions.
satelite navigation system is an example of a computer system that is made up of sub-systems
‘This structure diagram shows some of its sub-systems.
Complete the diagram by filling in the empty boxes.
Satellite navigation system
Input destination
ic)
109‘Theory Questions
2 Four programming concepts and four examples of programming code are shown below.
Draw a line to link each programming concept to the correct example of programming code.
Programming
Snoept Example of programming code
‘Counting Sum = Sum + Value(n}
Repetition IF Value = 10 THEN PRINT ‘x
Selection FOR Counter = 1 70 10
Totalling Amount = Amount + 1
Sum = Numl + Num2
3 Four validation checks and four descriptions are shown below.
Draw a line to link each validation check to the correct description.
Validation check
Presence check
Range check
Type check
Length check
Description
(4
Numbers between two
given values are accepted
Data is of a particular
specified type
Data contains an exact
‘number of characters.
Ensures that some data
have been entered
0
(31‘Theory Questions
4 Four statement types and four examples are shown below.
Draw a line to connect each statement type to the correct example.
Statement type Example
Assignment FOR x <1 70 10
Iteration READ X
Input PRINT X
Output xeyvez
3)
5 Explain the difference between a variable and a constant in a program.
f2)
6 Identify three different loop structures that you can use when writing pseudocode.
Vee
[3]
™‘Theory Questions
7 IF ... THEN ... ELSE ... ENDIF andCASE ... OF ... OTHERWISE ... ENDCASE
are two different conditional statements that you can use when writing pseudocode.
Explain, using examples, why you would choose to use each conditional statement.
Example 1
Reason for choice
Example 2
Reason for choice .....
(6)
mm‘Theory Questions
8 REPEAT ... UNTTL is one type of loop structure.
Identity and describe two other types of loop structure that you could use when writing
pseudocode.
Loop structure 1
Description. -
Loop structure 2.
Description.
[4]
9 Aprogrammer writes a program to store a patient's temperature every hour for a day.
10
"
State the data structure that would be most suitable to use and give the reason for your choice.
Data structure ...
Reason.
(2)
Identity two different selection statements that you can use when writing pseudocode.
(2)
‘A routine checks the weight of melons to be sold in a supermarket. Melons weighing under
(5 kilograms are rejected and melons weighing over 2 kilograms are also rejected.
Give an example of each type of test data for this routine.
Normal
Extreme
‘Abnormal...
(3)
13‘Theory Questions
12 REPEAT .. 1 and WHILE .
structures you can use when writing pseudocode.
ENDWHILE are two different loop
Explain, using examples, why you would choose to use each type of loop.
Example 1...
Reason for choice
Example 2
Reason for choice
14‘Theory Questions
13 A program will be written to store information about members of a swimming club.
The following membership details will be recorded:
+ Name
+ Gender
+ Status:
© Senior
© Junior
Fee
‘Team member (Yes or No)
(Choose a suitable data type for each of the membership details to be recorded.
Membership detail Data type
Name
Gender
Status
Fee
‘Team member
6)
(ii) The swimming club has 50 members.
State the data structure that would be most suitable to use and give a reason for your
choice.
Data structure..
Reason...
15