OL P2 Quick Revision

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Page | 1

Page | 2
Page | 3
7.1 Computational Thinking Skills
Q 1) What is meant by computational thinking?
Computational Thinking - is used to study a problem and formulate an effective solution that can
be provided using a computer. There are several techniques used in computational thinking,
including abstraction, decomposition, and pattern recognition.

Q 2) Define Abstraction, Decomposition and pattern recognition.


Abstraction – the process of extracting information that is essential, while ignoring what is not
relevant, for the provision of a solution.
Decomposition – the process of breaking a complex problem into smaller parts.
Pattern recognition – the identification of parts of a problem that are similar and could use the
same solution.

Q 3a) Give reason/benefits for decomposition (breaking down a problem).


Program code is easier to implement.
Different people can be assigned to work on different modules
Program code is easier to test and debug.
Modules are re-usable.

Q 3b) Describe need for and benefits of using abstraction, Describe the purpose of abstraction.
Abstraction involves filtering out information that is not necessary to solve a problem.
Abstraction gives us the power to deal with complexity.
The benefits of abstraction:
• the time required to develop the program is reduced so the program can be delivered to the
customer more quickly
• the program is smaller in size so takes up less space in memory and download times are
shortened
• customer satisfaction is greater as their requirements are met without any extraneous features.

Q 3c) Stepwise refinement is often used in the development of an algorithm.


Describe stepwise refinement.
Stepwise refinement – is the practice of subdividing each part of a larger problem into a series of
smaller parts, and so on, as required.
Benefits of Stepwise refinement:
Increases the level of detail of the algorithm
Page | 4
Make steps easier to solve
to be directly translated into lines of code
7.1 Program Development Life Cycle
The program development life cycle is a process for planning, creating, testing, and deploying
an information system. The systems development life cycle concept applies to a range of hardware and
software configurations, as a system can be composed of hardware only, software only, or a combination
of both.
The purpose of a program development lifecycle
 To develop a successful program.
 To perform a specific task or solve a given problem.
 To make development well ordered.
 To document clearly.
 To make it understandable, and useful for other developers.
Stages of System Development Life Cycle

1. Analysis:
 Diagnosis of problem.
 Identification of problem.
 Abstraction.
 Decomposition.
Page | 5
 Identification of requirements.
A series of steps followed by the developer include:
 Collection of facts: Obtain end user requirements through documentation, client interviews,
observation, and questionnaires.
 Scrutiny of the existing system: Identify pros and cons of the current system in-place, so as to carry
forward the pros and avoid the cons in the new system.
 Analysis of the proposed system: Find solutions to the shortcomings described in step two and
prepare the specifications using any specific user proposals.

2. Design
 Identifier table is developed, variables, constants, arrays and other data structures are
decided.
 Algorithm flowchart and/or pseudo code is designed.
 Structure chart and state-transition diagrams are also designed.
Methods to design and construct a solution
 Structure Chart
 Flowchart
 Pseudo code

3. Coding
 Writing program code
 performing iterative testing.

4. Testing
 Testing program code using test data.
 The program is run many times with different sets of test data, to test that it
does everything it is supposed to do in the way set out in the program design.

Q) What is iterative testing


Iterative testing is carried out while a program is being developed. The programmer writes a
section of code (module) then tests it. The module may work fine, but more likely the
programmer will amend or fix the code, and test it again. The process repeats (iterates) until the
module works as intended.
Page | 6

Q1) 2b s23 P22-Q1) System Development Life Cycle


1 Tick (✓) one box to identify the first stage of the program development life cycle. [1]

A Analysis ✓

B Coding

C Design

D Testing

Q2) 2b s23 P22-Q3) Design of Solution


3 Identify three different ways that the design of a solution to a problem can be presented.
1 Flowchart
2 Pseudo code
3 Structure Diagram .[3]

Page | 7
Q 3) 2a S23 P21- Q1) System Development Life Cycle
1 (a) Four descriptions of stages in the program development life cycle are shown.
Draw one line to link each description to its most appropriate program development life cycle stage.
Not all program development life cycle stages will be used. [4]

Program development life cycle description life cycle stage

Analysis

develop an algorithm to solve the problem by using structure diagrams,


flowcharts or pseudocode

Coding

detect and fix the errors in the program

Design

identify the problem and its requirements

Evaluation

write and implement the instructions to solve the problem

testing

Q 4) (a) Design and coding are stages of the program development cycle.
State two activities from each of these stages.
Design stage
Activity 1
Activity 2
Coding stage
Activity 1
Activity 2 [4]
Page | 8
Q5) (a) The following table lists some activities from the program development life cycle.
Complete the table by writing the life cycle stage for each activity. [4]

Activity Life cycle stage

An identifier table is produced.

Syntax errors can occur.

The developer discusses the program requirements with the customer.

A trace table is produced.

(c) An identifier table includes the names of identifiers used.


State two other pieces of information that the identifier table should contain.
1
2 [2]
(a) Design, Coding, Analysis, Testing
(b) Data Type, Description of identifier

8.1.8 Creating Maintainable Program


A program should be created in a way, it becomes easier to understand and maintain by using:
• meaningful identifiers for variables, constants, arrays, procedures and functions.
• making use of the inbuilt commenting feature of the chosen programming language to include
relevant and appropriate comments.
• procedures and/or functions where necessary.
• White space, blank lines between each block of code.
• Indentation, 3 spaces at the start of statement, inside a loop or selection.
• Capitalization of keywords like DECLARE, INPUT, OUTPUT, FOR etc.
• PascalCase of identifiers like Name, Count, CountPos, MaxMarks.
• Use of comments
Q1) 2a S23 P21- Q6) Maintainable Program
6 State two features that should be included to create a maintainable program.
Give a reason why each feature should be used.
1) meaningful identifier, easy to understand for the programmer.
2) Comments: used to explain what is happening the block of code [4]
Page | 9
7.2 Computer System
Q 4) What is system and sub-system?
A system is a set of rules, an arrangement of things, or a group of related things that work
together to perform a function.
A system is made up of a number of subsystems. Each subsystem can be further divided into
subsystems and so on until each sub-system just performs a single action.
Computer system is often divided up into sub-systems. This division can be shown using top-
down design to produce structure diagrams that demonstrate the modular construction of the
system.

Q 5) Define System and Sub-system.


System is a set of principles or procedures according to which something is done; an organized
scheme or method.
A system is a set of rules, an arrangement of things, or a group of related things that work
together to perform a function.
A system is made up of a number of subsystems. Each subsystem can be further divided into
subsystems and so on until each sub-system just performs a single action.

Q 6) What is meant by computer system?


A COMPUTER SYSTEM is made up of hardware, software & data, communications and people;
each computer system can be divided up into a set of sub-systems. Each subsystem can be
further divided into sub-systems and so on until each sub-system just performs a single action.

Q 7) Define Top-Down Design


Top-down design is the breaking down of a computer system into a set of subsystems, then
breaking each sub-system down into a set of smaller sub-systems, until each sub-system just
performs a single action.

Q 8) What is transferable skills? Explain how it helps in work on not familiar programming
language.
Transferable skills, are the abilities programmer can transfer from one language to another.
Programmer should be able to recognise / understand in another language:
• Declaration, assignment, sequence, selection, repetition (iteration)
Subroutines, Parameters passed between modules
Page | 10
program structure, Input and Output

Q 8) Describe Structure Diagrams


The STRUCTURE DIAGRAM shows the design of a computer system in a hierarchical way, with
each level giving a more detailed breakdown of the system into sub-systems.

Q 9) A structure chart is often used in modular program design.


State four features of structure diagram:
Feature 1: Sequence of operation
Feature 2: Selection of modules
Feature 3: Repetition
Feature 4: Parameters

Q 10) Define Library routines


A LIBRARY ROUTINE is a set of programming instructions for a given task that is already
available for use. It is pre-tested and usually performs a task that is frequently required.

Q 11) Define Sub-routines


A SUB-ROUTINE is a set of programming instructions for a given task that forms a subsystem, not
the whole system. Sub-routines written in high-level programming languages are called
‘procedures’ or ‘functions’ depending on how they are used.

Q 11b) State three advantages of using built-in functions.


Saves development time, no need to write it again.
Pre-compiled and well tested, more reliable, less chance of error
Page | 11
Available to all programs

Q 12) What is meant by Function?


A Function is a sub-routine that always returns a value.

Q 13) What is meant by Procedure?


A Procedure is a sub-routine that doesn’t have to returns a value.

Q 14) Differentiate terms Parameter and Argument.


A parameter is a variable in a method definition. While the arguments are the data that are
passed.

1b fm23 P22-Q 5) Structure Chart


5 A food ordering system is an example of a computer system that is made up of sub-systems.
The food ordering system:
• allows the user to enter the details of the food they want to order and to pay for the order
• displays food available as pictures or as a list.
Complete the structure diagram for the given parts of the food ordering system. [4]
Page | 12
1b fm23 P22-Q10
10 (b) The function Same(A,B) returns TRUE if the value of A is the same as the value of B when B is
rounded to the nearest whole number and FALSE otherwise.
Write pseudocode statements to: [6]
• define the function
• call the function with X and Y and store the return value in Z
Function definition
FUNCTION Same(A,B) RETURNS BOOLEAN
IF A=ROUND(B,0) THEN
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
END FUNCTION
Function call
Z  Same(X,Y)

(c) State the difference between defining and calling a function. [1]
Define a function or a procedure means set-up it, writing code to create it, while CALL means
executing a function or procedure.

0a Specimen P2a Q10) Functions and Procedures - features


10 A function is declared using pseudocode.
FUNCTION ConvertToCm(Inches: REAL) RETURNS REAL
RETURN Inches * 2.4
ENDFUNCTION
Tick (ü ) one box which accurately describes the use of the variable Inches [1]
A Answer
B Call
C Parameter
D Response
Page | 13
0a Specimen P2a Q3) MCQ: Functions and Procedure- Features
3 Tick (ü ) one box to show the named section of a program that performs a specific task. [1]
A File
B Function
C Parameter
D Process

1b fm23 P22 - Q 1) MCQ Scope of Variable


1 Tick (ü ) one box to show which word accurately describes the scope of a variable declared in a
procedure. [1]
A Function
B Global
C Local
D Subroutine

3c W23 P23 – Q7 Functions and Procedures


7 A program uses both local variables and global variables.
Describe two differences between local variables and global variables.
Difference 1: Local variables are declared inside a function or procedure, while global variables are
declared in main module outside a function or procedure.
Difference 2: Local variables are available only in the module, where they are declared, global
variables are available throughout the program. [4]

3b w23 p22- Q8) Why Procedures and Functions?


8 Explain why a programmer would use procedures and parameters when writing a program.

Procedures (or functions) are used to enable the programmer to write a collection of programming
statements under a single identifier .

Procedures (or functions) are used to allow modular programs to be created


Procedures (or functions) are used to allow procedures to be re-used within the program or in other
programs .
Procedures (or functions) are used to make program creation faster because procedures can be re-used.
Page | 14
Procedures (or functions) are used to make programs shorter (than using the repeated code) / using less
duplication of code // to make programs easier to maintain due to being shorter.

Parameters are used to pass values from the main program to a procedure / function
Parameters are used so that they can be used in the procedure / function
Parameters allow the procedure / function to be re-used with different data.

3c W23 P23 –2 MC!- Built-in Functions


2 Tick ( ) one box to show which library routine returns the remainder of a division. [1]
A DIV
B MOD
C RANDOM
D ROUND

7.2 Algorithm
Q 1) Define algorithm.
Algorithm is a step by step design of a solution. Flowchart and pseudo code are two different
representations of algorithm.

Q 2) What is meant by Pseudo code?


PSEUDO CODE is a simple method of showing an algorithm, using English-like words and
mathematical operators that are set out to look like a program.

Q 2) What are data types? Why they are needed?


A data type is a classification of data which tells the compiler or interpreter how the programmer
intends to use the data. Most programming languages support various types of data, including
integer, real, character or string, and Boolean.
Before a variable can be used in a program, the variable’s data type has to be identified.

Q 3) What are atomic data types?


The built in data types are called Atomic Data Types. For example Integer, Real, Boolean, String,
Char, Date etc.
Page | 15
Q 4) What are User-Defined Data Types?
A user-defined data type is a data type for which the programmer has included the definition in
the program. Here user means user of programming language i.e. the programmer.
Once the data type has been defined, variables can be created and associated with the user-
defined data type.

Q 5) Why are User defined data types are needed?


Sometime built-in data types are not fulfilling the requirements of a programmer then needs to
define own data type.

Q 6) Describe different data types with examples.


The following keywords are used to designate atomic data types:
1. INTEGER: A whole number (without fractional part) can be positive or negative and used in
calculations.
For example, COUNT which never requires fractional part and may store 56, 89, 1
2. REAL: A number capable of containing a fractional part can be positive or negative and used
in calculations.
For example, Weight may contain fractional Part like 56.8, 89.0, 1.2
3. CHAR: A single character (may be letter, special character or number but number cannot be
used in calculation).
For example, ‘A’, ‘$’, ‘5’
4. STRING: A sequence of alphanumeric and special characters but number cannot be used in
calculation.
For example, “Inqilab Patel”, “0300-2724734”, “House No 56 Block 2, PECHS Karachi”
5. BOOLEAN: A data type with two possible values
For example, TRUE and FALSE or YES or NO
6. DATE: To store a calendar date
For example, 16/04/2010

Q 7) Differentiate variable and constant.


Variable is memory location where a value can be stored. The values stored in a variable are
changed during execution.
Constant is a memory location that stores values, but values once stored cannot be changed
during program execution.
Page | 16
Q 8) What are identifier, also describe rules for deciding identifiers?
Identifiers are the names given to variables, constants, procedures and functions.
They are in mix case. They can only contain letters (A–Z, a–z), digits (0–9) and underscore (_).
They must start with a letter and not a digit.

Q 9) What are Arithmetic operators?


Standard arithmetic operator symbols are used:
 + : Addition
 - : Subtraction
 * : Multiplication
 / : Division
 MOD : Division to calculate remainder
 DIV : Integer division

Q 10) What are logic operators? What are their operands?


The only logic operators used are AND, OR and NOT. The operands and results of these
operations are always of data type BOOLEAN.
Logic operators
The following symbols are used for logical operators:
Python Algo
Equals to
Less than
Less than or equals to
Greater than
Greater than or equals to
Not equals
The result of these operations is always of data type BOOLEAN.
In complex expressions, it is advisable to use parentheses to make the order of operations explicit.
Page | 17
Q 17) Define flowchart and draw symbols
A flowchart is a graphical representation of algorithm.

Terminator used at START


and END of the flowchart

Process Box: Rectangle

Input / Output Box:


Parallelogram

Decision Box (IF and


CASE Selection, Loops)
Rhombus

Function / Procedure CALL

The following are recognised flowchart symbols:


Q 18) Describe Counting and Totalling.
Counting is used to find how many items are there by incrementing by 1 during each time loop is
executed.
It is sometimes necessary to count how many times something happens.
To count up or increment by 1, we can use statements such as:
Count ← Count + 1
(new) (old)
i.e. INCREMENT (old) Count by 1 to get (new) Count

TOTALLING is used to calculate running total. We can use a variable such as Total or Sum to hold
the running total and assignment statements such as:
Total ← Total + Number
(new) (old)
i.e. ADD Number to (old) Total to obtain (new) Total

Q 19) What is a program?


A program is a sequence of instructions or programming language statements written to make a
Page | 18
computer perform certain tasks.

Q 20) What are basic Control Constructs:


Following are the basic constructs of algorithm and program which controls execution of
statements:
1. Sequence
2. Assignment
3. Selection
4. Iteration

Q 21) Describe what is meant by sequence.


Sequence: One statement is being executed after another in the order they are written.
In following example statement number ‘i’ will be executed at 1st and then ‘ii’ then ‘iii’ and at last
statement number ‘iv’ will be executed:
I. INPUT Num1
II. INPUT Num2
III. Total  Num1 + Num2
IV. PRINT Total

Q 22) Describe Assignment with example statements.


Assignment: Storing values in a variable is known as assignment.
The assignment operator is ←.
Assignments should be made in the following format:
<identifier> ← <value>
For example:
Counter ← 0
Counter ← Counter + 1
TotalToPay ← NumberOfHours * HourlyRate
Q 23) What is meant by Selection/Condition, Explain different types of selection statements?
Selection (Condition) determines program flow path on the basis of given condition.
It also decides which statement(s) are to be executed depending upon the result of a given
condition.
IF and CASE selections are two different types of selection statements
IF statements are used when there are one or two options.
Page | 19
When there is only one option IF statements without an ELSE clause is written as follows:

IF Number>Largest THEN
LargestNumber
ENDIF
When there are two options IF statements with an ELSE clause is written as follows:
IF Marks>=50 THEN
Result  “Pass”
ELSE
Result  “Fail”
ENDIF
CASE statements is a conditional statement to deal with many possible outcomes.
CASE statements allow one out of several branches of code to be executed, depending on the
value of a variable.
In case selection number of statements are reduced so code become more simplified.

CASE statements are written as follows:


CASE Marks OF
>=90: Grade  “A*”
>=80: Grade  “A”
>=70: Grade  “B”
>=60: Grade  “C”
>=50: Grade  “D”
>=40: Grade  “E”
OTHERWISE : : Grade  “U”
ENDCASE

Q 24) What is meant by Loop (Repetition or iteration)?


Iteration (Loop or Repetition) is used to execute a set of instructions multiple times.
There are following three types of loops:
1. Count-controlled loop
2. Pre-condition loop
3. Post-condition loop
Page | 20
Page | 21
Q 25) Describe Count Controlled Loop.
Count-controlled (FOR) loops
Count-controlled loop is used when the number of repetition is already known.
For example to input 5 numbers:
FOR Count  1 TO 5
INPUT Num
NEXT Count

Q 26) What are pre-condition (WHILE) loops?


A loop in which condition is given at the start of loop and which is executed only when the
condition is true, is called pre-condition loop.
The condition is tested before the statements, and the statements will only be executed if the
condition evaluates to TRUE. After the statements have been executed the condition is tested
again. The loop terminates when the condition evaluates to FALSE.
The statements may not be executed even once if, on the first test, the condition evaluates to
FALSE.
Example: To input a series of numbers and calculate total and stops if a –ve number is entered:
The condition is checked at the beginning of the loop. If condition is true loop statements are
executed again and again.
Total0
INPUT Num
WHILE Num>0 DO
Total Total + Num
INPUT Num
END WHILE

Q 27 What are post condition loop?


Post-condition (REPEAT UNTIL) loop is a loop in which condition is given at the end of loop and
which is executed only when the condition is false.
The statements in the loop will be executed at least once. The condition is tested after the
statements are executed and if it evaluates to TRUE the loop terminates, otherwise the statements
are executed again.
Example: To input and validate a number and to reject it if a negative number is entered and ask to
re-enter another number
The condition is checked at the end of the loop. If condition is false, loop statements are executed
again and again.
Page | 22
REPEAT
INPUT Num
UNTIL Num>0

Difference between Loop structures


FOR … TO… NEXT WHILE … ENDWHILE REPEAT … UNTIL

Count-Controlled loop Pre-Condition Loop Post Condition Loop

Number of repetition is already Executed when condition is Executed when condition is


known TRUE FALSE

Executed a set number of May not be executed even Executed at least ONCE
times ONCE

0a Specimen P2a- Q1) Control Constructs


1 Four pseudocode descriptions and five pseudocode statements are shown.
(a) Draw a line to link each pseudocode description to the most appropriate pseudocode
statement.
Some pseudocode statements will not be used.
Pseudocode description Pseudocode statement
A loop that will always iterate at least once FOR … TO …NEXT

A conditional statement to deal with many IF…THEN…ELSE…ENDIF


possible outcomes

A loop that will always iterate a set number of WHILE…DO…ENDWHILE


times

A conditional statement with different CASE…OF…OTHERWISE…ENDCASE


outcomes for true and false

REPEAT…UNTIL
Page | 23
0b Specimen P2b Q2) Programming Concepts
2 Four programming concepts and four descriptions are shown.
Draw one line to connect each programming concept to the most appropriate description. [3]
Programming concept Description
Library routine A subroutine that does not have to return a value.

Structure diagram An overview of a program or subroutine.

PROCEDURE A standard subroutine that is available for immediate use.

FUNCTION A subroutine that always returns a value.

Function
0b Specimen P1b-Q12) Loops – convert loop
12 (a) Rewrite this pseudocode algorithm using a WHILE … DO … ENDWHILE loop. [4]
B ← FALSE
INPUT Num
FOR Counter ← 1 TO 12
IF A[Counter] = Num
THEN
B ← TRUE
ENDIF
NEXT Counter

(b) Identify the purpose of the algorithm in (a). [1]

(c) Explain the difference between a WHILE … DO … ENDWHILE and a REPEAT … UNTIL loop. [3]
Page | 24
1b fm23 P22- Q2) Basic Concepts
2 (a) Four descriptions and five pseudocode statements are shown.
Draw one line to link each description to its most appropriate pseudocode statement. Not all
pseudocode statements will be used. [4]
Description Pseudocode statement
a statement to count FOR Count  1 TO 10

a statement to total Value  Value + NewValue

a statement to start a pre-condition loop While Value > 10 DO

a statement to start a post-condition loop Value  Value + 1

REPEAT

1b fm23 P22-Q4) use of variables and constants


4 Describe how variables and constants are used in programming. [3]

2a S23 P21- Q2) Basic Concepts


2 Tick (ü) one box to show the name of the data structure used to store a collection of data of the
same data type. [1]
A Array
B Constant
C Function
D Variable
Page | 25
3b w23 p22- Q3a) Matching pseudocode statements
3 Four pseudocode statements and five pseudocode uses are shown.
(a) Draw one line to link each pseudocode statement to the most appropriate pseudocode use.
Not all pseudocode uses will be required. [4]
Pseudocode statement Pseudocode use
Counting CALL Colour(NewColour)

Finding an average Value  (A1+A2+A3)/3

Totalling Loop1  Loop1 + 1

Using a conditional statement IF Count > 7 THEN X1 ß 0

Using a procedure

3b w23 p22- Q5) Use of variables and constants in programming


5 Explain how variables and constants should be used when creating and running a program.
[3]

0a Specimen P2a Q1b) Design Algorithm- Output data from arrays


1 (b) Using a single loop, write an algorithm in pseudocode to output 50 names that have been
stored in the array, Name[] [3]
Page | 26
Validation and Verification
Validation and verification are two ways to check that the data entered into a computer is correct.
Data entered incorrectly is of little use.

Q 1) Define Data verification.


Verification is performed to ensure that the data entered exactly matches the original source.
Verification means checking the input data with the original data to make sure that there have
been no transcription errors (transcription means copying the data).
Verification methods include:
At the time of entry At the time of transmission
Double entry Parity check
Screen/visual check Checksum.
ARQ
Echo Check
Write a code for double entry to verify input marks:

DECLARE Marks, MarksCheck: REAL


INPUT "Enter marks : ", Marks
INPUT "Re-enter marks: ", MarksCheck
WHILE Marks < > MarksCheck DO
OUTPUT "Marks not matched try again."
INPUT "Enter marks : ", Marks
INPUT "Re-enter marks: ", MarksCheck
ENDWHILE

Q 2) What is validation?
Validation is an automatic computer check to ensure that the data entered is sensible and
reasonable. It does not check the accuracy of data.

However, this does not guarantee that the number typed in is correct. For example, a student's
age might be 14, but if 11 are entered it will be valid but incorrect.

A validation check is a rule that is built into a database to check that the data entered is:
 Sensible
 Reasonable
 Within acceptable boundaries
 Complete
Page | 27
It does NOT mean that the data is actually correct, that requires verification.
Q 3) Describe different types of validation checks.
There are a number of different validation rules:
1 Type Checks – Checks that the data entered is of a given data type.
For example,to ensure only integer type of data is entered:
DECLARE Value: REAL
INPUT “Enter a value”, Value
WHILE Value <> ROUND(Value,0) DO
OUTPUT “Error! Real numbers are not allowed here, try again”
INPUT “Re-enter a value”, Value
ENDWHILE
string data entered in integer field or variable will be rejected.

2 Range checks - these are used to limit the range of data a user can enter. The 'day' part of a
date must be in the range 1 to 31. An exam grade should be in the range 'A'...'E' or 'U'.
INPUT Marks
WHILE Marks<0 OR Marks>100 DO
PRINT “Error! Re-enter marks”
INPUT Marks
ENDWHILE

3 Limit Check - Similar to Range Check but the rule involves only one limit.
For example, >=0 means reject negative numbers. Date of birth must not be later than a date.
4 Character Check - Checks that when a string of characters is entered it does not contain any
invalid characters or symbols.
For example a name would not contain digit or special character.
5 Format Check - Checks the data is in the right format. Values must conform to a specific
pattern, for example, two letters followed by six digits followed by a single letter.
A candidate number, PK-500-1234 or National Insurance number is in the form LL 99 99 99 L
where L is any letter and 9 is any number. for Date dd/mm/yyyy or mm/dd/yyyy
6 Presence checks - these simply check that an entry has been made in a particular field i.e. a
null value (empty field) is not permitted.
For example to make sure that some data has been stored in the name, it is not left empty:
INPUT "Enter name ", Name
WHILE Name="" DO
PRINT “Error! Enter name ”
INPUT "Enter name again ", Name
ENDWHILE
Page | 28
7 Length Checks - ensures that such data is either an exact length or does not exceed a
specified number of characters.
For example to make sure that password is at least 8 characters long:
INPUT "Enter password, at least 8 characters long: ", Pass
WHILE LENGTH(Pass) < 8 DO
OUTPUT "Error! Try again"
INPUT "Re-enter password, at least 8 characters long: ", Pass
ENDWHILE

8 Lookup - A lookup check takes the value entered and compares it against a list of values in a
separate table.
9 Check digits - The last one in a code are used to check the other digits are correct.
Bar code readers in supermarkets use check digits.
length check – e.g. only 30 characters in name field
character check – e.g. name doesn’t contain numeric chars
range check – e.g. day of month in date is between 1 and 31
format check – e.g. date in the form xx/yy/zz
check digit – e.g. end digit on bar code to check if it is valid
type check – e.g. integer, real
presence check = field is not left blank

Identify validation check


Page | 29

Each of the following algorithms performs data validation.


State the type of validation check that each of the algorithms performs.
(a)
INPUT x
IF x < 0 OR x > 10 THEN
OUTPUT "Invalid"
ENDIF
.................................................................................................................................................... [1]
(b)
INPUT x
IF x = "" THEN
OUTPUT "Invalid"
ENDIF
.................................................................................................................................................... [1]
(c)
INPUT x
IF NOT(x = "Red" OR x = "Yellow" OR x = "Blue") THEN
OUTPUT "Invalid"
ENDIF
.................................................................................................................................................... [1]
Page | 30
Test Data
Test data is the data that is used in testing of a software system.
In order to test a software application, we need to enter some data for testing most of the features.
Any such specifically identified data which is used in tests is known as test data.
There are following three types of test data:
1. Normal Data is the data a computer system should work on. Testing needs to be done to
prove that the solution works correctly.
For example, here is a set of normal test data for an algorithm to record the percentage marks
from 10 end-of-term examinations for a student and find their average mark:
Normal test data: 50, 50, 50, 50, 50, 50, 50, 50, 50, 50
Expected result: 50

2. Abnormal/Erroneous Data is the data that should cause the system to tell the user that
there is a problem with data entered into the system.
This test data should be rejected as the values are not suitable.
This type of test data is called ERRONEOUS or ABNORMAL TESTDATA; it should be rejected
by the solution.
For example to input positive numbers:
Erroneous/abnormal data:–12, eleven
Expected results: these values should be rejected
3. Extreme Data are the largest and smallest values that normal data can take.
Extreme data: 0, 100
Expected results: these values should be accepted
4. Boundary Data is the test data that is established either on the limit of acceptability or just
outside the limit of acceptability.
For example, for percentage marks in the range 0 to 100, the algorithm should be tested with
the following boundary data; at each boundary two values are required, one value is accepted
and the other value is rejected.
Boundary data for 0 is –1, 0 and for 100 is 100, 101
Expected results: –1 and 101 are rejected, 0 and 100 are accepted
Rogue Values A value that stops input is called Rogue Value.
A rogue value lets the computer know that a sequence of input values has come to an end.
Page | 31
10 Data Types and structures
Records, Arrays Files, ADT

Data type – a classification attributed to an item of data, which determines the types of value it
can take and how it can be used.
Identifier – a unique name applied to an item of data.
Record (data type) – a composite data type comprising several related items that may be of
different data types.
Composite data type – a data type constructed using several of the basic data types available in
a particular programming language.
Linear search – a method of searching in which each element of an array is checked in order.
Bubble sort – a method of sorting data in an array into alphabetical or numerical order by
comparing adjacent items and swapping them if they are in the wrong order.
File – a collection of data stored by a computer program to be used again.
Page | 32
Arrays
Arrays are data structure used to store multiple data items of same data type (homogenous)
under one identifier name.
Square brackets are used to indicate the array index.
Each element in the array is identified using its subscript or index number. The largest and
smallest index numbers are called the upper bound and lower bound of the array.
For illustration, let's take array declaration to store marks of 10 students.
Marks[10 Marks[1:10 Marks[0:9
] ] ]
Q 1) Describe The terms associated with Arrays
Name: The identifier of the array is called Array Name. E.g. StudentName[]
Element: Each data item stored in array is called element. Array can store only single types of
elements.
Size: The number elements the array can store. E.g. StudentName[1:30] can store 30 names
while StudentName[30] can store 31 names as by default it is 0 to 30.
Index: The position of each element is referred as Index Number. In the above diagram , ndex of
90 in 1D array is [3], while in 2D is [3,1].
Type: Data type of all elements in a single array have same data types.
Dimension: Dimension is the organisational structure of array. It may be 1D that has single index
or 2D that has two indexes.
Lower Bound – the smallest index number
Upper Bound – the largest index number
Page | 33
Q 2) The following diagram shows four data structures and four descriptions. [3]
Draw a line to connect each data structure to the correct description.
Data structure Description
Constant A collection of related data

Array A value that can change whilst a program is running

Table A value that never changes whilst a program is running

Variable A series of elements of the same data type

Linear Search
Linear Search - is a method in which each element of the array is checked in order, from the lower
bound to the upper bound, until the item is found or the upper bound is reached.
For example, to search marks in an 1D array Marks[1:30], user has to input data to be searched.
Algorithm compares this search data with all elements of the array, starting from lower bound. If
search data matches with the element, then it displays the location of data first found and if data is
not found, it is searched at next location in the conditional loop until the data is found or it reaches
at the upper bound. Example Code for Single Searching using Linear Search
DECLARE SearchData: REAL
DECLARE Found: BOOLEAN
INPUT SearchData
Found  FALSE
Index  1
WHILE Index <=30 AND Found = FALSE
IF SearchData = Marks[Index] THEN
Found  TRUE
OUTPUT “Found at “, Index
ELSE
Index  Index + 1
ENDIF
ENDWHILE
IF Found = FALSE THEN
OUTPUT “Not found”
ENDIF
Page | 34

Example Code for Multiple Searching, using Linear Search


To search and output all locations where the search data is found, a count controlled loop is used
instead of conditional loop.
DECLARE SearchData: REAL
DECLARE Found: BOOLEAN
INPUT SearchData
Found  FALSE
FOR Index  1 TO 30
IF SearchData = Marks[Index]
THEN
Found  TRUE
OUTPUT Index
ENDIF
NEXT Index
IF Found = FALSE
THEN
OUTPUT “not found.”
ENDIF
Bubble sort – is a method of sorting data in an array into alphabetical or numerical order by
comparing adjacent items and swapping them if they are in the wrong order.
Each element of the array is compared with the next element and swapped if the elements are in
the wrong order, starting from the lower bound and finishing with the element next to the upper
bound. The element at the upper bound is now in the correct position. This comparison is repeated
with one less element in the list, until there is only one element left or no swaps are made.
Page | 35

DELCARE Flag: BOOLEAN


DECLARE Boundary: INTEGER
DELCARE Temp: INTEGER
Flag  TRUE
Boundary  4
WHILE Flag = FALSE
Flag  True
FOR Index  1 TO Boundary
IF Marks[Index] > Marks[Index + 1] THEN
Temp  Marks[Index]
Marks[Index]  Marks[Index + 1]
Marks[Index + 1]  Temp
Flag  FALSE
ENDIF
NEXT Index
Boundary  Boundary – 1
ENDWHILE
Page | 36
WRITEFILE “Teachers.txt”, Name
NEXT Count
CLOSEFILE “Teachers.txt”
Page | 37
File Handling
Q 1) Why files are needed?
When a program is being executed data is stored in variables, constants, arrays etc. These data
structures use RAM, making them temporary, when program is closed Files stored data in
secondary storage devices. These are permanent and non-volatile. They retain data even after
computer is switched OFF, so the data can be accessed next time program is run.

Q 2) Describe File Handling


Text files consist of lines of text that are read or written consecutively as strings.
A file must be opened in a specified mode before any file operations are attempted. This is written
as follows:
OPENFILE <File identifier> FOR <File mode>
The file identifier may be a literal string containing the file names, or a variable of type STRING
that has been assigned the file name.
Q 3) Explain different file modes
The following file modes are used:
READ - for data to be read from the file
WRITE - for data to be written to the file. A new file will be created and any existing data in the file
will be lost.
APPEND for data to be added to the existing file, if the file is not existing then it will be created.
WRITE MODE: To create a new text file and write data in it
To create a new text file, firstly it is opened in WRITE mode, data is written in it and then it is
closed. If file is already existing, new file will be created and all existing data will be lost.
Syntax to create a new text file:
OPENFILE <File name> FOR WRITE
WRITEFILE <File name>, <String Variable to be written>
CLOSEFLE <File name>
Page | 38
For example, to store a name “Inqilab Patel” in a text file Teachers.txt, firstly “Inqilab Patel” is
stored in a string variable and then file is opened and variable is stored at the end of file.
OPENFILE “Teachers.txt” FOR WRITE
WRITEFILE “Teachers.txt”, Name
CLOSEFILE “Teachers.txt”
READ MODE: To display contents of text file
To display contents of a text file, firstly it is opened in READ mode, data is read one line at a time
into a temporary variable and displayed on screen, then next line is read until it reaches End Of
File (EOF) marker. Then files is closed.
Syntax to read first line from text file:
OPENFILE <File name> FOR READ
READFILE <File name>, <String Variable to store content>
OUTPUT <String Variable>
CLOSEFLE <File name>

For example to read 1st line from text file Teachers.txt and to store in a variable “TextLine”
OPENFILE “Teachers.txt” FOR READ
READFILE “Teachers.txt”, TextLine
PRINT TextLine
CLOSEFILE “Teachers.txt”
CLOSEFILE “Teachers.txt”
Two Files: Read data from 1st file and store in another file, for example from Teacher.txt to
staff.txt:
OPENFILE “Teachers.txt” FOR READ
OPENFILE “Staff.txt” FOR WRITE

READFILE “Teachers.txt”, TextLine


WRITEFILE “Staff.txt”, TextLine

CLOSEFILE “Teachers.txt”
CLOSEFILE “Staff.txt”
Page | 39
Binary Logic
INPUT OR AND NAND NOR XOR
A B
X=¿
X= A +B X= A . B X= A . B X= A +B
( A . B ) +( A . B)
0 0 0 0 1 1 0
0 1 1 0 1 0 1
1 0 1 0 1 0 1
1 1 1 1 0 0 0

Q 1) Describe each logic gate.


NOT Gate: X=1 if Input A is 0. Inverter
AND Gate: X =1 if BOTH input are 1
“The only time the output will be 1 is when both inputs are 1.”
OR Gate: X=1 if Either input is 1
NAND Gate: X=0 if BOTH input are 1
“The only time the output will be 0 is when both inputs are 1.”
NOR Gate: X =0 if EITHER input is 1
“The only time the output will be 1 is when both inputs are 0.”
XOR Gate: X=1 if Either input is 1 BUT NOT BOTH. Or when BOTH input are DIFFERENT.
“The only time the output will be 1 is when both inputs are different.”

Q 2) Draw and describe XOR gate. [5]

XOR Gate gives output only when BOTH input are different.
If A = 1 OR B = 1 BUT NOT BOTH then output will be 1.
IF BOTH input are 0 then output will be 0.
IF BOTH input are 1 then output will be 0.
IF BOTH input are same output will be 0.
Page | 40
Draw a logic circuit corresponding to the logic statement: [3]
X = (A is ON OR B is ON BUT NOT BOTH) OR (NOT(C is ON AND A is ON))

Complete Truth table

A B C Working space X
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Page | 41
Write logic expression and complete the truth table for the following logic circuit:

Logic Expression: ………………………………………………………………………

A B C Working space X

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1
Page | 42
7 Consider the truth table:

A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0
1 1 1 1
(a) Draw a logic circuit to represent the given truth table.
Each logic gate should have maximum of two inputs.
Do not simplify the logic circuit. [6]

B X

(b) Write a logic expression for the given truth table.


Do not simplify the logic expression.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
........................................................................................................................................... [3]
Page | 43
9 Database
A database is an organized and persistent (permanent) collection of data.
A database is persistent as it uses secondary storage (HDD or SSD) as work area rather than memory. It
directly stores records on disc as soon as it is entered, automatically.
Database Management System (DBMS) is a mechanism for manipulating data with high level command. It hides low
level details such are as how data are obtained.
Database management system also has ability to search record by queries and to create reports and view data.
functions of databases:
• adding and removing data.
• manipulating or changing data.
• accessing and analysing data.
• storing data.
• avoiding data duplication.
• maintaining accuracy and consistency.
• sharing data.
Entity
An entity is a “real world thing” about which data is held. Examples of entities include:
A customer A product A pupil A supplier

An attribute is a feature of that entity. For example, a hotel room might have an attribute about
whether it has a view or whether it is single or double. A student might have a date of birth and an
address.
An entity is stored as a table in a database and an attribute becomes a field in a table.
All the data about a particular entity is stored in a single table. Each data item about the entity is a
field.
Page | 44
Data types
Different data types are identified so that a computer can store and process the data appropriately.
Data types include:
 Text/Alphanumeric (STRING or CHAR in programming and pseudo code)
 Character (a singe character)
 Number (numeric) may include:
o Auto number
o Currency
 Date/Time
 Boolean (or Yes/No).
Primary Keys
Each table has a primary key. This is a field chosen so that it can uniquely identify each record.

SQL - Structured Query Language (pronounced as siːkwəl or "seequel") is the most common
language for extracting and organising data that is stored in a relational database.
SQL is the language of databases. It facilitates retrieving specific information from databases that
are further used for analysis.
SELECT Command
SELECT Command tells the database what information user wants to retrieve followed by FROM to specify which
table.
WHERE statement specifies a condition that has to be met before record is returned
ORDER BY DESC places data in descending order...
The SELECT statement allows you to ask the database a question (Query it), and specify what
data it returns. We might want to ask something like
Tell me the name and class of all the students.
The structure of SELECT Command is given below:
SELECT <Field names>
FROM <Table name>
WHERE <condition>
ORDER BY <ASC or DESC>
Take a look on following Student table.
RollNo FirstName LastName DoB Class Section Points
101 Osman Zaheer 12/05/2005 AS K 10
102 Wajid Ali 05/08/2000 A2 G 8
103 Rehan Ghayas 07/02/2003 A2 S 10
104 Jane Oliver 22/08/2005 AS T 5
105 Abdullah Patel 11/11/2009 OL K 10
106 Muzna Marea 14/07/2006 AS K 10
To select all the items from this table we can use:
SELECT *
FROM <Table>
Page | 45

SELECT *
FROM Student;
This would display all the Name and class of students who are in section K and class is AS.

SELECT RollNo, FirstName, Class


FROM Student
WHERE Section = “K” AND CLASS=”AS”;

This would return the following:


RollNo FirstNam Class
e
101 Ahmed AS
106 Muzna AS
This would display all the Name and class of students who are in section K or in section T.

SELECT LastName, Class


FROM Student
WHERE Section = “K” OR Section=”T”;

This would return the following:


LastName Class
Zaheer AS
Oliver AS
Patel OL
Marea AS

To display name and roll of students who are in class AS:


SELECT ROllNo, FirstName, LastName
FROM Student
WHERE Class = “AS”
This would return the following:
RollNo FirstName LastName
101 Ahmed Zaheer
104 Jane Oliver
106 Muzna Marea

SELECT LastName, DoB --what to return


FROM Staff; --where are you returning it from

This would return the following:


LastName DoB
Zaheer 12/05/2005
Ali 05/08/2000
Ghayas 07/02/2003
Oliver 22/08/2005
Patel 11/11/2009
Marea 14/07/2006
Page | 46
Page | 47
The output can be organised in ascending or descending order. For example to display roll
number, first name, last name and points in ascending order of points:

SELECT RollNo, FirstName, LastName, Points


FROM student
ORDER BY Points DESC --sorts the Points values in big to small order

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
COUNT() - Returns the number of rows
SUM() - Returns the sum
Dummy Database Table: TMarks
RollNo Month Marks Result
101 Feb 89 Pass
101 Jan 78 Pass
102 Feb 75 Pass
102 Jan 34 Fail
103 Jan 78 Pass
104 Jan 87 Pass
COUNT()
The COUNT() function returns the number of rows that matches a specified criterion.
Syntax:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Example:
To count number of records:
SELECT COUNT(RollNo)
FROM Marks;
Example
To Count number of Students who are pass:
SELECT COUNT(Result)
FROM Marks
WHERE Result=”Pass”;
SUM()
The SUM() function returns the total sum of a numeric column.
Syntax:
SELECT SUM(column_name)
Page | 48
FROM table_name
WHERE condition;
Example:
To calculate total marks
SELECT SUM(Marks)
FROM Marks;
Work Example:
A shop that sells books has set up a new database table called BookList to store book details. Part of
this table is given.
CatNo Title Fiction Author PaperBack Price StockLevel
BK01 The Princes’ Story Yes B Penn Yes 4.50 500
BK04 Computer Science No I Patel No 25.00 5
BK05 The Revision Guide No I Patel No 25.00 120
BK06 Computer Science No R Dale Yes 27.35 8
BK07 The Princes’ Story Yes B Penn No 12.50 50
BK12 Famous Five Yes E Bly Yes 2.75 45
BK15 Secret Seven Yes E Bly Yes 2.75 250
BK26 CompSci Workbook No I Patel Yes 6.75 300
BK31 Networking for AS No I Patel Yes 6.99 0
(a) State the number of records and fields:
Records ………………………….
Fields ……………………………. [2]
(b) (i) Give the name of the field that would be used for the primary key.
..................................................................................................................................... [1]
(ii) State the reason for choosing this field for the primary key.
...........................................................................................................................................
..................................................................................................................................... [1]
Page | 49
(c) Complete the table to identify the most appropriate data type for each field based on the data
shown in the table BookList [2]

Field Data type


CatNo
Title
Fiction
Price
(d) Write the output from this structured query language (SQL) statement.
SELECT CatNo, Title, Author
FROM BookList
WHERE StockLevel = 5;
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [2]
(e) Complete this SQL statement to display all the titles by the author B Penn. [2]
SELECT .....................................................................................................................................
FROM .........................................................................................................................................
WHERE .....................................................................................................................................;
(f)Write SQL script to find sum of price of all books that are not
fiction.

(g) Write SQL script to count number of books whose stock level is more
than 100.

You might also like