Computer Science Paper 2 Notes
Computer Science Paper 2 Notes
Design
• The program specification derived from the analysis stage is used as a guide for program
development.
• During the design stage, the programmer should have a clear understanding of the tasks to be
completed, the methods for performing each task, and how the tasks will work together.
• Documentation methods such as structure charts, flowcharts, and pseudocode can be used to
formally document the design of the program.
• inputs – the data used by the system that needs to be entered while the system is active
• processes – the tasks that need to be performed using the input data and any other previously
stored data
• outputs – information that needs to be displayed or printed for the users of the system
• storage – data that needs to be stored in files on an appropriate medium for use in the future.
Activity; Break down the ‘Check time’ sub-system from the smart phone alarm app into further sub-
systems
Flowcharts
A flowchart shows diagrammatically the steps required to complete a task and the order that they
are to be performed. These steps, together with the order, are called an algorithm. Flowcharts are
an effective way to communicate how the algorithm that makes up a system or sub-system works.
Example; Checking for the alarm time
2. a choice between several different values, such as: CASE OF … OTHERWISE … ENDCASE
Activity;
Re-write the algorithm to check for a mark between 0 and 20 and a pass mark of 10.
All types of loops can all perform the same task, for example displaying ten stars:
the FOR … TO … NEXT loop is the most efficient way for a programmer to write this type of task as the
loop counter is automatically managed.
FOR … TO … NEXT loops
A variable is set up, with a start value and an end value, this variable is incremented in steps of one until
the end value is reached and the iteration finishes. The variable can be used within the loop so long as
its value is not changed. This type of loop is very useful for reading values into lists with a known length.
REPEAT … UNTIL loop
This loop structure is used when the number of repetitions/iterations is not known and the actions are
repeated UNTIL a given condition becomes true. The actions in this loop are always completed at least
once. This is a post-condition loop as the test for exiting the loop is at the end of the loop.
OUTPUT
is used to display information either on a screen or printed on paper; it is usually followed by a single
value that is a string or a variable, or a list of values separated by commas, for example:
Explaining the purpose of an algorithm
An algorithm sets out the steps to complete a given task. This is usually shown as a flowchart or
pseudocode, so that the purpose of the task and the processes needed to complete it are clear to
those who study it. You will be able to practice this skill as you become more familiar with writing
and finding and correcting errors in algorithms.
Example; Output an alarm sound
The purpose of the following pseudocode is to output the alarm sound at the appropriate time. The
processes are: waiting 10 seconds, getting the current time, checking the current time with the
alarm time, and outputting the alarm sound when the times match.
Counting
Keeping a count of the number of times an action is performed is another standard method. For
example, counting the number of students that were awarded a pass mark:
Counting is also used to count down until a certain value is reached, for example, checking the
number of items in stock in a supermarket:
Maximum, minimum and average
Finding the largest and smallest values in a list are two standard methods that are frequently found
in algorithms, for example, finding the highest and lowest mark awarded to a class of students.
If the largest and smallest values are not known, an alternative method is to set the maximum and
minimum values to the first item in the list. For example, using this method to find the highest and
lowest mark awarded to a class of students.
Calculating the average (mean) of all the values in a list is an extension of the totalling method, for
example, calculating the average mark for a class of students
Linear search
A search is used to check if a value is stored in a list, performed by systematically working through
the items in the list. This is called a linear search, which inspects each item in a list in turn to see if
the item matches the value searched for.
For example, searching for a name in a class list of student names, where all the names stored are
different:
Bubble sort
This method of sorting is called a bubble sort. Each element is compared with the next element and
swapped if the elements are in the wrong order, starting from the first element and finishing with
next-to-last element. Once it reaches the end of the list, we can be sure that the last element is now
in the correct place. However, other items in the list may still be out of order. Each element in the
list is compared again apart from the last one because we know the final element is in the correct
place. This continues to repeat until there is only one element left to check or no swaps are made.
For example, the bubble sort algorithm can be used to sort a list of ten temperatures stored in the
array, Temperature [], into ascending order. It could be written in pseudocode as:
Length check
A length check checks either:
that data contains an exact number of characters, for example that a password must be exactly eight
characters in length so that passwords with seven or fewer characters or nine or more characters would
be rejected, for instance
or that the data entered is a reasonable number of characters, for example, a family name could be
between two and thirty characters inclusive so that names with one character or thirty-one or more
characters would be rejected.
Type check
A type check checks that the data entered is of a given data type, for example, that the number of
brothers or sisters would be an integer (whole number).
Presence check
A presence check checks to ensure that some data has been entered and the value has not been left
blank, for example, an email address for an online transaction must be completed.
Verification is checking that data has been accurately copied from one source to another
There are 2 methods to verify data during entry
1. Double Entry \n
• Data is inputted twice, potentially by different operators.
• The computer system compares both entries, and if they differ, an error message is displayed,
prompting for the data to be reentered.
2. Screen/Visual check
• A screen/visual check involves the user manually reviewing the entered data.
• After data entry, the system displays the data on the screen and prompts the user to confirm its
accuracy before proceeding.
• The user can compare the displayed data against a paper document used as an input form or
rely on their own knowledge to verify correctness.
Test Data
• Test data refers to input values used to evaluate and assess the functionality and performance
of a computer program or system.
• It helps identify errors and assess how the program handles different scenarios
Normal Data
• Normal data is the test data which accepts values in acceptable range of values of the program
• Normal data should be used to work through the solution to find the actual result(s) and see if
they are the same as the expected result(s)
• e.g. in a program where only whole number values ranging from 0 to 100 (inclusive) are
accepted, normal test data will be : 23, 54, 64 , 2 and 100
Abnormal Data
• Test data that would be rejected by the solution as not suitable, if the solution is working
properly is called abnormal test data / erroneous test data.
• e.g. in a program where only whole number values ranging from 0 to 100 (inclusive) are
accepted, abnormal data will be: -1, 151, 200, 67.2, “Sixty-Two” and -520
Extreme Data
• Extreme data are the largest and smallest values that normal data can take
• e.g. in a program where only whole number values ranging from 0 to 100 (inclusive) are
accepted, extreme data will be: 0 and 100
Boundary Data
• This is used to establish where the largest and smallest values occur
• At each boundary two values are required: one value is accepted and the other value is rejected.
• e.g. in a program where only whole number values ranging from 0 to 100 (inclusive) are
accepted, one example of boundary data will be: 100 and 101. 100 will be accepted and 101 will
not be accepted
Trace Table
• A trace table is utilized to document the outcomes of every step in an algorithm. It is employed
to record the variable's value each time it undergoes a change.
• A dry run refers to the manual process of systematically executing an algorithm by following
each step in sequence.
• A trace table is set up with a column for each variable and a column for any output e.g.
Test data is employed to execute a dry run of the flowchart and document the outcomes in a trace
table. During the dry run:
• Whenever a variable's value changes, the new value is recorded in the respective column of the
trace table.
• Each time a value is outputted, it is displayed in the output column.
0 0
1 1.4
2 1.3
1 1.1
3 1.3
2 1.0
4 1.5
3 1.2
5 1.3
6 1.4
7 1.3
4 0.9
8 1.5 Ready to go 4
Identifying errors
• Trace tables can be used to trace errors in a program. For example, if the requirement for the
previous question would be to accept riders that are of height 1.2 too, rather than rejecting
them, then the error would have been caught in the trace table as when 1.2 is entered, it would
increment rejected which it shouldn’t in our example
Writing and Amending Algorithms
There are a number of stages when producing an algorithm for a given problem:
1. Make sure that the problem is clearly specified – the purpose of the algorithm
and the tasks to be completed by the algorithm.
2. Break the problem down in to sub-problems; if it is complex, you may want to
consider writing an algorithm for each sub-problem. Most problems, even the
simplest ones can be divided into:
– Set up processes
– Input
– Processing of data
– Permanent storage of data (if required)
– Output of results
3. Decide on how any data is to be obtained and stored, what is going to happen
to the data and how any results are going to be displayed.
4. Design the structure of your algorithm using a structure diagram.
5. Decide on how you are going to construct your algorithm, either using a
flowchart or pseudocode. If you are told how to construct your algorithm,
then follow the guidance.
6. Construct your algorithm, making sure that it can be easily read and
understood by someone else. Precision is required when writing algorithms,
just as it is when writing program code. This involves setting it out clearly
and using meaningful names for any data stores. Take particular care with
conditions used for loops and selection, for example 'Counter >= 10' rather
than 'Counter ten or over'. The algorithms that you have looked at so far in
this chapter were not designed with readability in mind because you needed
to work out what the problem being solved was.
7. Use several sets of test data (Normal, Abnormal and Boundary) to dry run your
algorithm and show the results in trace tables, to enable you to find any errors.
8. If any errors are found, correct them and repeat the process until you think
that your algorithm works perfectly.
Have a look at this structure diagram and flowchart for the algorithm to select the largest, Max, and
smallest, Min, numbers from a list of ten numbers. This time the flowchart is more easily readable than
the structure chart:
Example 1: Writing algorithms in pseudocode
Tickets are sold for a concert at $20 each. If 10 tickets are bought then the discount is 10%, if 20 tickets
are bought the discount is 20%. No more than 25 tickets can be bought in a single transaction. a Use
pseudocode to write the algorithm to calculate the cost of buying a given number of tickets.
Explain how you would test your algorithm.
★ file handling: including opening, closing, reading from and writing to data and
text files.
There are five basic constructs to use and understand when developing a program:
• data use – variables, constants and arrays
• sequence – order of steps in a task
• selection – choosing a path through a program
• iteration – repetition of a sequence of steps in a program
• operator use – arithmetic for calculations, logical and Boolean for decisions.
Data Types
• A data type is a classification of data into groups according to the kind of data they represent
• Computers use different data types to represent different types of data in a program
• The basic data types include:
o Integer: used to represent whole numbers, either positive or negative
▪ Examples: 10, -5, 0
o Real: used to represent numbers with a fractional part, either positive or negative
▪ Examples: 3.14, -2.5, 0.0
o Char: used to represent a single character such as a letter, digit or symbol
▪ Examples: 'a', 'B', '5', '$'
o String: used to represent a sequence of characters
▪ Examples: "Hello World", "1234", "@#$%
o Boolean: used to represent true or false values
▪ Examples: True, False
Variables and constants are used to store a single item of data in a program. This can be accessed
through the identifier. Variables can be changed during program execution while constants remain the
same.
• Variables are declared using a data type, a name and a value (optional)
• Constants are declared using the 'const' keyword, a name and a value
• In all programming languages, variable names should follow certain rules, such as:
o Starting with a letter
o Not containing spaces
o Can contain letters, numbers, _ or $
o Not using reserved words (like if, while, for etc.)
• Examples of data types include integer, float, boolean, and string
Examples in Pseudocode:
score ← 10
const PI ← 3.14
Examples in Python:
score = 10
PI = 3.14
total_price_var=0
ticket_price_const=25
number_of_tickets=input(“Enter number of tickets”)
total_price_var=number_of_tickets*ticket_price_const
print(total_price_var)
print(ticket_price_const)
Output
Output refers to the process of displaying or saving the results of a program to the user.
Pseudocode example:
Python example:
Input
'User Input' is data or information entered by the user during program execution.
Pseudocode example:
INPUT name
Python example:
Task 1
Volume of a sphere
To calculate the volume of a sphere, we use the formula
V=4/3*3.142*radius**3
Your task is to create a program that asks the user for the radius of a sphere, then calculate its
volume. The program must output a message showing the result calculated.
radius=float(input("Enter Your Radius"))
volume=4/3*3.142*radius**3
print(volume)
Task 2
Volume of a cylinder
To calculate the volume of cylinder, we can use the formula
V3.142*radius**2*height
Your task is to create a program that asks the user for the radius and height of a cylinder, and then
calculate its volume. The program must output a message showing the result calculated.
radius=float(input("Enter Your Radius"))
height=float(input("Enter Your height"))
volume=3.142*radius**2*height
print(volume)
SEQUENCE
What is Sequence?
Pseudocode example:
PRINT "Hello, World!"
x←5
y←10
z← x + y
PRINT z
Python example:
print("Hello, World!")
x=5
y = 10
z=x+y
print(z)
e.g.
Pi_const=3.142
radius=float(input("Enter the radius of the sphere"))
volume=(4/3)*Pi_const*radius*radius*radius
print(volume)
e.g.
Pi_const=3.142
radius=float(input("Enter the radius of the sphere"))
height=float(input("Enter the height of the sphere"))
volume=Pi_const*radius*radius*height
print(volume)
SELECTION
What is selection?
Selection is a programming concept that allows you to execute different sets of instructions based on
certain conditions. There are two main types of selection statements: IF statements and CASE
statements.
If Statements
IF statements allow you to execute a set of instructions if a condition is true. They have the following
syntax:
IF condition
THEN
instructions
ENDIF
Pseudocode example:
x← 5
IF x > 0
THEN
ENDIF
Python example:
x=5
if x > 0:
print("x is positive")
age=input(“what is your age?)
if age>18:
else:
IF ELSE Statements
If else statements are used to execute one set of statements if a condition is true and a different set of
statements if the condition is false. They have the following syntax:
IF condition
THEN
Instructions
ELSE
Instructions
ENDIF
Pseudocode example:
x←5
IF x > 0
THEN
ELSE
PRINT “x is negative”
ENDIF
Python example:
x=5
if x > 0:
print("x is positive")
else:
print("x is negative")
Case statements
Case statements are used when there are multiple choices to be made. Different programming
languages provide different types of statement to do this. Have a look at the method your
programming language uses.
Pseudocode
INPUT Grade
Case of Grade
A: OUTPUT “Excellent”
B: OUTPUT “Not bad huh”
C: OUTPUT “Fair”
D: OUTPUT “Work harder”
OTHERWISE: OUTPUT “Invalid Input”
ENDCASE
Python Code
Grade=input("Enter your Grade")
if Grade==("A"):
print("Excellent")
elif Grade==("B"):
print("Not bad huh")
elif Grade==("C"):
print("Fair")
elif Grade==("D"):
print("Work harder")
else:
print("Invalid Input")
What is iteration?
Iteration is the process of repeating a set of instructions until a specific condition is met. It is an
important programming concept and is used to automate repetitive tasks.
• Count-controlled loops
• Precondition loops
• Postcondition loops
Count-controlled Loops
Example in Pseudocode:
count ← 1
FOR i <= 10
OUTPUT count
NEXT i
Example in Python:
print(count)
e.g.
Results
1
2
3
4
5
6
7
8
9
for counter in range(1,10,2):
print(counter)
1
3
5
7
9
Pre-condition Loops
• A precondition loop is used when the number of iterations is not known beforehand and
is dependent on a condition being true
• It is also known as an indefinite loop
• The loop will continue to execute while the condition is true and will stop once the
condition becomes false
Example in Pseudocode:
INPUT temperature
INPUT temperature
END WHILE
Example in Python:
total=0
mark=int(input("Enter value for mark, -1 to finish"))
while mark!=-1:
total=total+mark
mark=int(input("Enter value for mark, -1 to finish"))
print(total)
The program will keep adding what the user enter until the user keys in the value “-1”.The total will be
printed.
For example, this loop runs as long as number is less than 10:
number = 0
while number < 10:
print(f"Number is {number}!")
number = number + 1
Here, the variable number is set to 0 initially.
Before any code is run, Python checks the condition (number < 10). It evaluates to True so the print
statement gets executed and Number is 0! is printed to the console.
number is then incremented by 1. The condition is re-evaluated and it is again True, so the whole
procedure repeats until number is equal to 9.
This time Number is 9! is printed and number is incremented, but now number is equal to 10 so the
condition is no longer met and therefore the loop is terminated.
It's possible that the while loop never runs if it doesn't meet the condition, like in this example:
number = 50
while number < 10 :
print(f"Number is {number}!")
Postcondition Loops
• A post-condition loop is used when the loop must execute at least once, even if the condition is
false from the start
• The condition is checked at the end of the loop
Example in Pseudocode:
REPEAT
INPUT guess
UNTIL guess = 42
Example in Python:
Postcondition loops don’t exist in Python and would need to be restructured to a precondition loop
Python does not have built-in functionality to explicitly create a do while loop like other languages. But it
is possible to emulate a do while loop in Python.
To create a do while loop in Python, you need to modify the while loop a bit in order to get similar
behavior to a do while loop in other languages.
As a refresher so far, a do while loop will run at least once. If the condition is met, then it will run again.
The while loop, on the other hand, doesn't run at least once and may in fact never run. It runs when and
only when the condition is met.
So, let's say we have an example where we want a line of code to run at least once.
secret_word = "python"
counter = 0
while True:
word = input("Enter the secret word: ").lower()
counter = counter + 1
if word == secret_word:
break
if word != secret_word and counter > 7:
break
The code will run at least one time, asking for user input.
It is always guaranteed to run at least once, with True, which otherwise creates an infinite loop.
If the user inputs the correct secret word, the loop is terminated.
If the user enters the wrong secret word more than 7 times, then the loop will be completely exited.
The break statement allows you to control the flow of a while loop and not end up with an infinite loop.
break will immediately terminate the current loop all together and break out of it. So this is how you
create the a similar effect to a do while loop in Python.
Totalling
Pseudocode example:
total ← 0
for i ← 1 to 10
input num
next i
output total
Python example:
total = 0
for i in range(1, 11):
num = int(input("Enter a number: "))
total += num
print("Total:", total)
Counting
• Counting involves keeping track of the number of times a particular event occurs
• A count variable can be initialised to 0 and then updated within a loop, such as:
Pseudocode example:
count ← 0
for i ← 1 to 10
input num
if num > 5 then
count ← count + 1
end if
next i
output count
Python example:
count = 0
for i in range(1, 11):
num = int(input("Enter a number: "))
if num > 5:
count += 1
print("Count:", count)
(total=total+count)=total+=count
Counting
• Counting involves keeping track of the number of times a particular event occurs
• A count variable can be initialised to 0 and then updated within a loop, such as:
Pseudocode example:
Python example:
count = 0
for i in range(1, 11):
num = int(input("Enter a number: "))
if num > 5:
count += 1
print("Count:", count)
String Handling
Strings are used to store text. Every string contains a number of characters, from an empty string, which
has no characters stored, to a maximum number specified by the programming language. The characters
in a string can be labelled by position number. The first character in a string can be in position zero or
position one, depending on the language.
length – finding the number of characters in the string. For example, the length of the string "Computer
Science" is 16 characters as spaces are counted as a character. In Python, the len() function is used to
find the length of a string.
substring – extracting part of a string. For example, the substring "Science" could be extracted from
"Computer Science". In Python, the substring can be obtained using the slicing operator [:]
upper – converting all the letters in a string to uppercase. For example, the string "Computer Science"
would become "COMPUTER SCIENCE". In Python, the upper() method is used to convert a string to
uppercase
lower – converting all the letters in a string to lowercase. For example, the string "Computer Science"
would become "computer science". In Python, the lower() method is used to convert a string to
lowercase.
Pseudocode example:
length ← LENGTH(phrase)
substring ← SUBSTRING(phrase, 5, 2)
upper ← TO_UPPER(phrase)
lower ← TO_LOWER(phrase)
Python example:
length = len(phrase)
substring = phrase[4:6]
upper = phrase.upper()
lower = phrase.lower()
len("Computer Science")
len(MyString)
#Text in quotes can be used or a variable with data type string.
"Computer Science"[9:16]
MyString[9:16]
"Computer Science".upper()
MyString.upper()
#Text in quotes can be used or a variable with data type string.
"Computer Science".lower()
MyString.lower()
#Text in quotes can be used or a variable with data type string.
#Sring handling
sample_string="abcdefghijkk"
length_counter=len(sample_string)
print(length_counter)
character=sample_string[1]
print(character)
substring=sample_string[0:3]
print(substring)
#upper
uppercase=sample_string.upper()
print(uppercase)
#lowercase
sample = "ABBDWDAWD"
sample = sample.lower()
print(sample)
Arithmetic Operators
Pseudocode example:
a←5
b←3
c←a+b
d←a-b
e←a*b
f←a/b
g ← a MOD b
h←a^b
i ← a DIV b
Python example:
a = 5
b = 3
c = a+b
d = a-b
e = a*b
f = a/b
g = a%b
h = a**b
i = a//b
Logical Operators
Pseudocode example:
a←5
b←3
c ← (a = b)
d ← (a < b)
e ← (a <= b)
f ← (a > b)
g ← (a >= b)
h ← (a <> b)
Python example:
a = 5
b = 3
c = (a == b)
d = (a < b)
e = (a <= b)
f = (a > b)
g = (a >= b)
h = (a != b)
Nested Statements
• Nested statements involve including one statement within another statement. This can be done
with both selection (if/else) and iteration (for/while) statements
• In programming languages like Python, Java, and Visual Basic, nested statements are often
indicated by indenting the inner statement(s) relative to the outer statement(s)
Nested Selection
Pseudocode example:
if a > b then
if b > c then
else
else
if a > c then
else
Python example: