You are on page 1of 33

Paper 2 – Programming and

Problem Solving
IGCSE – Computer Science – Revision Notes
Content

2.3 Databases

2.2
Programming
• 2.2.1 Programming concepts
• 2.2.2
2.2.2 Data
Data structures;
structures; arrays
arrays

2.1 Algorithm design


and problem-solving

• 2.1.1
2.1.1 Problem-solving
Problem-solving and
and
design
design
•• 2.1.2
2.1.2 Pseudocode
Pseudocode and
and
flowcharts
Algorithm Design & Problem Solving

Structure Diagrams
 Structure diagrams are a graphical way of representing a problem, showing
the different levels of detail.
 They are a great way to illustrate all the systems and sub-systems.
Example
Below is a structure diagram showing how a satellite navigation system can be
broken down into smaller sub-systems.

A Sub-Routine is set of programming instructions for a given task that forms a


sub-system, not the whole system. Sub-Routines written in high level languages
are called ‘procedures’ or ‘functions’ depending on how they are used.
Algorithm Design & Problem Solving

Top-Down Design
Most systems consist of increasingly smaller and smaller sub-systems.
Computers are designed to perform tasks and solve problems. How it goes about doing these tasks is up to
way the system is designed, and the programmer develops the product.
Different problems can require different types of computer hardware, software, and peripherals. Top down
design is the name given to breaking a problem down into increasingly smaller and smaller manageable parts
(also known as decomposition).

We see this all around us in our everyday lives:


 Global organizations and companies are broken down into regional divisions
 Large firms are broken down into smaller departments, and sub-teams
 Computer systems are made up of smaller sub-systems

In programming, these smaller tasks/parts are sometimes referred to as:


 Modules
 Sub-routines
 Procedures
Once finished, these modules (‘chunks’) of code are all put together to form the main program.

Benefits of Top-Down Design


 Breaking a problem down into smaller parts/tasks makes it far easier to understand, solve and manage
 Top down design allows several programmers or teams to work on the same project, without getting in
each other’s way
 Each module of code to be tested separately
TOP – DOWN DESIGN EXAMPLE
When designing a new system, one method is to start with the big idea and work your way down. In order
to visualize this approach, it’s often best to use mobile phone system. Notice how it goes from the full
system, and then into something like structure charts, shown in the following example of a the three
distinct areas that a phone will deal with. At each level of the chart the elements of the system become more
detailed, or more specific. 

There are many benefits to top down design, including the ability to allow few individuals to quickly control the direction the
project is taking. The opposite of top down design is bottom up, which is something you should be aware of, but not
something that you’ll necessarily be tested on.
Algorithms
 An algorithm is a set of instructions/steps/rules that are followed to solve a
problem.
 We follow algorithms every day, maybe without even realizing we are doing
so:
 You have a routine for cleaning your teeth
 You follow a series of memorized steps when making a drink of tea
 Cookery books have pages full of algorithms
Algorithm design
 There are two common methods to express algorithm designs, they are 
pseudocode and flowcharts.
 In either way, our algorithms should be focused o the logic of the task which
means that we should be able to implement them using any programming
language. This is known as being ‘language independent’.
Pseudocode
 Pseudocode is a method of expressing
an algorithm design.
 Pseudocode is lines of instructions written
in a language close to English but with
common programming terms used where
possible (selection and iteration etc).
 People with limited programming
knowledge should be able to
follow pseudocode as it normally doesn’t
resemble any one programming language.
 There are no definitive rules for writing
pseudocode but it should make sense and
logically solve the problem/task.
 Once a problem has been solved logically
using pseudocode, it can then be coded
into an actual programming language of
choice.  One line of pseudocode may
result in several lines of actual code.
FLOW CHARTS
Flowcharts are a graphical way of representing an algorithm design.
Flowchart must have a clear start and finish (unless looping).

Used to indicate the start and


Start / Finish
finish of the algorithm.

A process / action to be
Process performed, e.g. a calculation
or the assignment of a value.

Used to show data being


inputted into the system (e.g.
Input / Output by a user), or data being
outputted (e.g. a message or
the value from a variable).

A question / test of a
condition that allows the
Decision
flowchart to branch into one
of two paths, yes or no.
Flow Chart Example
VALIDATION AND VERIFICATION

Validation and Verification are both used to ensure that data entered into a computer
system is correct and reasonable.  The use of both Validation and verification is vital
for the smooth running of computer systems.

VALIDATION VERIFICATION
 ​Validation is a process that checks  ​Verification differs to Validation. Its
that data is reasonable before it is purpose is not to judge that
accepted by a computer system. realistic / acceptable  data has been
 Validation is automated meaning that entered but rather the purpose of
a well designed algorithm should Verification is to ensure that data
successfully decide whether or not that has been entered into a
data is acceptable. computer is correct.
 There are a number of different  There are 4 Verification methods to
Validation checks that can be be aware of at this stage, these are:
performed on data. These include:  Visual Checking
 Range Checks  Double entry verification
 Presence Checks  Parity Checks
 Format Checks  Check sums
 Type Checks
 Character Checks Parity checks and Checksums are
 Check Digits discussed in the error checking section
RANGE CHECKS
A range check is used to ensure that numbers are only accepted into a program if it falls within a
certain acceptable range.
Example - If a program asks for somebodies age then you might limit entries to be between 13
and 100.  This would potentially prevent people under the age of 13 from signing up and it
would also prevent people giving an unrealistic age e.g. 250 years old.
Pseudo code for a validation check like this may look like:
Age = 0
OUTPUT "Please enter your age"
Age = INPUT()
WHILE Age < 13 OR Age > 100 DO
     IF Age < 13 THEN
          OUTPUT "Sorry, you are too young"
     ELSE IF Age > 100 DO
          OUTPUT "Sorry, Age entered is not realistic - it is too high"
    END IF
    OUTPUT "Please re-enter your age"
    Age = INPUT()
END WHILE
​You can test this out yourself using the Python Code button below...

Python Code
PRESENCE CHECKS
A Presence check is used to ensure that some data has been entered. This is used where you
cannot allow the user to progress until they provide you with information e.g. a user cannot sign
up to a service if they have left the e-mail field empty.

Example - An internet blog has the ability to post comments. You do not need to create an
account, however before the post is published you do need to enter your name. In this case there
are no rules about how long your name should be, or even that it has to be realistic. The only rule
is that you have to enter a name.

Pseudo code for a validation check like this may look like:

Name = ""
OUTPUT "Please enter your name so that we can post your comment"
Name = INPUT()
WHILE Name = "" DO
     OUTPUT "Sorry, You must enter a name before your post can be published"
     Name = INPUT()
END WHILE
OUTPUT "Thank you " + Name + "  Your comment has been published"

​ ou can test this out yourself using the Python Trinket below. Try testing what will happen when
Y
you enter nothing vs when you enter a name.

Python Code
FORMAT CHECKS
A format check is used to ensure that data entered matches a desired pattern.
Example 1: if a user is required to enter an email address then it should follow a set pattern of "XXXXX" + @
+ "XXXXX" + "." + "XXX"  This would allow an email address such as "example@gmail.com" to be accepted.
Example 2: Another example of a format check would be to check that an ID number has been entered in the
correct format.  Lets imagine that in our program an ID number must begin with the organizations initials ISS and
must end with 4 numbers e.g. ISS1432.
Pseudo code for a validation check like this may look like:

OUTPUT "Please enter an ID number e.g. ISS1111"


Accepted = False
While Accepted = False Do:
​     IDNo = INPUT()
     First = IDNo[0,1,2]
     Last = IDNo[3,4,5,6]
     Length = Len(IDNo)
     IF Length =7 THEN AND First = "ISS" AND (Last >=0000 AND Last <=9999):
        Accepted = TRUE
     ELSE:
          OUTPUT "ID Not acceptable - Please try again"
     END IF
END WHILE
OUTPUT "Acceptable ID not entered”
   
​You can test this out yourself using the Python Code Button below. Try testing what will happen when you enter a
valid or invalid ID Number. This example is case sensitive - the ISS must be capital letters to be accepted

Python Code
TYPE CHECKS
 A Type check is used to ensure that the correct data type has been entered. This means that  if
you are requesting an integer then the program will only accept an integer, a string or any other
data type would be rejected.

An example scenario for this would be a program that asks the user to enter their age. This input
should be a whole number and therefor an integer. If any other type of data is entered then it
should be rejected and the user should be given the chance to try again.

Pseudo code for a validation check like this may look like:

OUTPUT "Please enter your age"


Accepted = False
While Accepted = False Do:
​     Age = INPUT()
     IF Age.isdigit():
        Accepted = TRUE
     ELSE:
          OUTPUT "Age Not acceptable - Must be a whole number"
     END IF
END WHILE
OUTPUT "Acceptable Age entered.
   
​You can test this out yourself using the Python Trinket below. ​Try testing what will happen when
you enter a string or a decimal number.

Python Code
CHARACTER CHECKS
A Type check is used to ensure that an entered string does not contain any unacceptable
characters. 
An example scenario might be that a user needs to choose a username. The username cannot
contain the ! or @ symbol as they are reserved for admin usernames.
Pseudo code for a validation check like this may look like:
OUTPUT "Please choose a username"
Accepted = False
Find = False
While Accepted = False Do:
​     Username = INPUT()
     length = len(Username)
     FOR x = 0 to Length DO:
          IF Username(x) = "!" OR Username(x) = "@"
               Find = True
          END IF
      END FOR
      IF Find = True THEN:
          Accepted = False
          Find = False
          OUTPUT "Unacceptable Username, cannot contain ! or @ symbols"
          Else:
               Accepted = True
          END IF
END WHILE
OUTPUT "Acceptable username entered"
   ​You can test this out yourself using the Python Code Button below. ​Try testing what will happen when you
enter a username that contains the symbols ! or @ then test what happens when you enter an acceptable username

Python Code
VERIFICATION CHECK METHODS
VISUAL CHECKING DOUBLE ENTRY VERIFICATION
A visual data check is as simple as it sounds. Double entry verification works by asking the
It is a very manual / human way of checking user to enter data twice.
which involves a user manually reading The two pieces of data will then be compared.
through data to ensure that it is correct. If the two entered pieces of data do not match
It is also possible that another person can be then a mistake has been detected.
asked to read through the data to check for A common example scenario for this is when
mistakes. This is similar to proof reading. If a choosing a password to sign up for an online
mistake is spotted then the data can be service. It is important that during this
changed. process a mistake is not made. 
If the user war trying to set their password as
"Apple" but accidentally misspelled it as
"Appple" then they may struggle to access their
account.
To avoid this, new members are asked to
enter their chosen password twice.
The chances of accidentally misspelling the
password twice in the exact same way are slim
and therefor this reduces the chance of
inaccurate data being entered.

Python Code
TESTING
 Testing is an important process required to find and remove errors from your code.
 Failure to properly test code before releasing it can result in errors. 
 Depending on the use of your software these errors could be catastrophic

Testing is the process of finding and removing errors from your code. Spotting and
removing syntax errors is easy to spot as your interpreter will usually point you in the
right direction by telling you that the are there. Finding Logical errors on the other hand
can be a lot trickier and can end up being a very time consuming process.  It is vital that
proper testing is completed before code is published. 

**** Can you imaging the consequences air plane auto pilot or life support machine software
had bugs in it! ****

WHAT WE ARE TESTING FOR?


We are generally looking to see if our code
works in the way that it is expected to.
 Does it accept or reject data that it is
supposed to?
 Does it crash unexpectedly
 Does it produce the correct result
 Are users able to enter incorrect data
TEST DATA
Test data is made up data that you choose to enter into your program. The test data should fall into three main
categories:
 Valid Data
 Invalid Data
 Boundary Data

VALID DATA
This data should be data that is accepted by the program. This data
should not cause any errors and should allow the program to process
normally.
Example 1 - If a program asks a user to enter a number less than 50.
(X < 50)
A Valid Test data would be 7  (Or any number between 0 and 49)
Example 2 - If a program asks a user to choose a password that is
more than 8 characters long
​A valid test data would be "TopSecret123" (Or any other password
with 9 or more characters)
TEST DATA
Test data is made up data that you choose to enter into your program. The test data should fall into three main
categories:
 Valid Data
 Invalid Data
 Boundary Data

INVALID DATA
This data should be data that is not accepted by the program. This data should be
rejected by the program. Your program should take adequate steps to reject invalid
data, if it fails to reject it then errors can occur or the program can crash.

Example 1 - If a program asks a user to enter a number less than 50. (X < 50)

An Invalid Test data would be 55  (Or any number greater than 50)
Another Invalid test data would be string like"Apple" as it is not a number and should
be rejected.

Example 2 - If a program asks a user to choose a password that is more than 8
characters long

​ n Invalid test data would be "Secret" (Or any other password with less than 9
A
characters)
TEST DATA
Test data is made up data that you choose to enter into your program. The test data should fall into three main
categories:
 Valid Data
 Invalid Data
 Boundary Data

BOUNDARY DATA
This data could be accepted or rejected by the program. The data chosen here must be on the
boundary of what is acceptable data. You should test both sides of the boundary i.e. is the data
accepted if it is just within the boundary and is it rejected if it is just outside.

Example 1 - If a program asks a user to enter a number greater than 40 but less than 50. (X > 40
and X < 50)

In this scenario the numbers 41 and 49 are the boundary numbers that should be accepted by the
program
numbers 40 and 50 are the boundary numbers that should be rejected.
TRACE TABLES
Once a you have finished coding your program and have started the testing process you will
need to think about the structure of your testing, After you have decided upon your test data it
is a good idea to use something called a trace table,
The trace table will allow you to follow through the program with your test data and
identify where errors may occur. Trace tables are an ideal method for testing the
efficiency and outcome of an algorithm

As an algorithm runs, the variables / arrays will be called upon,
changed, put through loops and selection all on the way to the
programs main goal.  “A trace table provides a structured method
of recording and studying the results and data for each step of the
algorithm.”
In order for this to work you will first need to devise your test data. You will then need to draw a table, each
column of the table should be labeled with the variable, array, output etc that you are trying to keep track of.  At
IGCSE level you will be provided with the table and test data for a given algorithm, you will just need to
demonstrate the ability to logically follow through the algorithm.

To test this algorithm you are given the following test data:

​1.8, 2.0, 1.0, 1.3, 1.0, 2.5, 2.0, 1.3, 1.8, 1.3, -1

These values are to be entered as the engine size 1 at a time. 

Engine Count Number Size Average Output


WORKING METHOD
Initial steps
To start the process of we will need to work through the flow chart step by step.
1. The first step of the flow chart is to set the engine, count and number variables to the value of 0
2. The next step is to accept the first user input and use it to set the value of the Size variable. This input
will be the first item of the test data which is 1.8.

Now we must follow through the flow chart to determine and document how the values will change.
We then take the value of Size (1.8) and we are asked "Is Size = -1?"
The answer to this is no and therefor we progress to the next question "is Size > 1.5?"
The answer to this is yes which takes us to step 3.

3. We must add 1 to the value of Count - at this stage count is 0,


add 1 to this = 1.  You should now write "1" in the Count
column of the trace table.
4. Step 4 requires us to add 1 to Number - at this stage Number
is 0, add 1 to this = 1. You should now write "1" in the Number
column of the trace table.
5. Step 5 requires you to add the Size variable to the Engine
variable. The engine variable is currently 0, 0 + 1.8 = 1.8. You
should write "1.8" into the Engine column of the trace table.

Looking at the flow chart you will see that after step 5, you are
looped back up to input the next test value for the Size
variable.  You should enter the next value which is 2.0 and then
once again follow through the algorithm whilst recording the
changes.

You ill continue to follow through until the algorithm ends.


OUTPUT FOR TRACE TABLE
Engine Count Number Size Average Output
O O O 1.8    
1.8 1 1 2.0    
3.8 2 2 1.0    
4.8   3 1.3    
6.1   4 1.0    
7.1   5 2.5    
9.6 3 6 2.0    
11.6 4 7 1.3    
12.9   8 1.8    
14.7 5 9 1.3    
16.0   10 -1    
        1.6  
           
          1.6, 5
DEBUGGING
The terms "debugging" and computing "bug" actually originate from Admiral Grace Hopper
in the 1940s. Grace was working on a Mark II computer at Harvard University where here
associates found a moth stuck in the circuits of her computer.  This "Bug" was actually
preventing the computer from functioning correctly. Removing the bug "Debugging"
actually fixed the system and hence the terms were born!

Two MAJOR types of ERRORS are


 Syntax Error &
 Logical Error

Syntax Error Logical Error


• When initially running a program that you are • Logical Errors are often more difficult as the
working on you may be alerted that your code program will run as if there are no errors,
contains a syntax error.  These are usually easy to however an unusual result may be produced or it
find as you are often told which line they are on will crash at an unexpected point. It is then the
by the interpreter. job of the programmer to find a mistake in the
code that caused the problem.  
COMMON MISTAKES TO LOOK
FOR
Loops can be the route of many 2. WHILE or REPEAT UNTIL loop has no exit clause
problems. Here are a few possible Example - your code will repeat forever until the input is "-1".  An
examples: example situation may be that you need to continue entering numbers and
1. The Loop does not repeat totaling them until the value -1 is entered/ An incorrect piece of code could
enough times look like this:
Example - A program is designed total = 0
to print the numbers 1 to 1000 num = 0
(inclusive), This means that the x = ""
code will need to loop 1000 times. WHILE x != "-1" DO
​FOR x = 0 to 999       num = INPUT()
     OUTPUT x + 1      total = total + num
This will only repeat 999 times END WHILE
and will only print the numbers 1 OUTPUT total
to 999 (Inclusive) This code would repeat forever as the user is never given the
Try in Tablet Python App opportunity to make x = "-1". 
for x in range(0,999): ​Note that entering a string rather than an integer will cause the program to
print x + 1 crash. Further validation would need to be implemented to ensure that
only integers are accepted.
To fix this problem you could
The code could be corrected by adding a line that allows the user to
change the upper limit of the FOR
change x - e.g. x = INPUT() 
loop from 999 to 1000 like this:
total = 0
FOR x = 0 to 1000
num = 0
     OUTPUT x + 1
x = ""

WHILE x != "exit" DO
This adjustment will now allow
     num = INPUT()
the code to repeat 1000 times.
     total = total + num
      x = INPUT()
END WHILE
COMMON MISTAKES TO LOOK FOR
3​ . Wrong operator used in a 4. Final output is within the loop causing excessive output
WHILE or REPEAT UNTIL
loop Example - Lets say that your program is meant to take 10 numbers from
the user. Total them up and then output the result at the end.  Here is an
Example - Your code is meant to example of incorrect code:
repeat as long as x is greater than
100. An incorrect piece of code Total = 0
would look like this: FOR x = 0 to 10
      OUTPUT "Please enter a number"
WHILE x < 100 DO      Num = INPUT()
This would actually cause the      Total = Total + Num
code to repeat whilst the number      OUTPUT  "Your total is" + Total
is 99 or less. - The opposite of END FOR
what is required.
The problem with this code is the position of the (OUTPUT "Your total
WHILE x >= 100 DO is" + Total). This line is within the loop which means that it will actually
This is almost correct as it would output a subtotal to the user 10 times. The 10th output is actually all that
keep the loop repeating for the user needs to see.
numbers while they are 100 or ​To fix this problem and to ensure that the total is only displayed at the end
greater, however the scenario of the program, the line should be moved outside and after the for loop as
specifies that x must be greater below.
than 100. This means 101 and up.
Total = 0
The correct code for this scenario FOR x = 0 to 10
may read:       OUTPUT "Please enter a number"
     Num = INPUT()
WHILE x >100 DO      Total = Total + Num
or END FOR
WHILE x >=101 DO OUTPUT  "Your total is" + Total

There are many other problems that could be caused by loops.  When faced with a real life problem OR an
exam question the ideas above are good starting points for the debugging process.
Thank You
RANGE CHECK PYTHON CODE
name = “ “
print "Please enter your age so that your comment can be published“
age = int(input())
while age <13 or age > 100:
if age< 13:
print "Sorry, you are too young to post a comment “
age = int(input("Please enter a valid age"))
elif age > 99:
print "That age is not realistic“
age = int(input("Please enter a valid age"))
print "Thank you Your comment has been posted"

The above code works do validate the age through the use of a WHILE loop.  The user will
not be allowed to progress to the next part of the program until the age lies between 13 and
100 (A REPEAT UNTIL loop could also be used). Of course this program is not perfect as a
10 year old would simply get a chance to enter their age again and lie about it, however the
code should illustrate the practical implementation of a range check.
PRESENCE CHECK PYTHON CODE
Name = "“
print "Please enter your Name so that your comment can be published“
Name = input()
while Name == "":
print "Sorry, your name must be entered before your post can be published.
Please enter your name: "
Name = input()
print "Thank you " + Name + " Your comment has been posted"

The above code works to validate the presence of a name through the use of a WHILE loop.  The user will not
be allowed to progress to the next part of the program until the Name variable contains data. Whilst the Name
variable remains empty the user will be asked to enter a name. (A REPEAT UNTIL loop could also be used).
FORMAT CHECK PYTHON CODE
print "Please enter an ID number e.g. ISS1234“
Accepted = False
while Accepted == False:
IDNo = input()
First = IDNo[0:3]
Last = int(IDNo[3:7])
Length = int(len(IDNo))
if Length == 7 and First =="ISS" and (Last >= 0000 and Last <=99990):
Accepted = True
else:
print "ID Not acceptable – Please Try Again"
print "Acceptable ID entered"

The above code works but it could be improved.  Currently it does not let the user know why the code that they entered
was incorrect. It would be possible to break down the IF statement into nested IFs so that the user could be provided
with helpful prompts e.g. "Your ID number does not start with "ISS""
TYPE CHECK PYTHON CODE
print "Please enter your age - It must be a whole number“
Accepted = False
while Accepted == False:
Age = input()
If Age.isdigit():
Accepted = True
else:
print "invalid age - Must be a number“
print "Age accepted"

In the real world this solution would need to be validated further. You might want to add a range check to it to
ensure that a realistic age is entered e.g. a max age of 100.
CHARACTER CHECK PYTHON CODE
print "Please enter a username“
Accepted = False
Find = False
while Accepted == False:
Username = input()
Length = len(Username)
print Username
for x in range(0,Length):
if Username[x] == "!" or Username[x] =="@":
Find = True
if Find == True:
print "Unacceptable username - Cannot containg ! or @. Please try again"
Accepted = False
Find = False else:
Accepted = True
print "Username accepted"

You might also like