0% found this document useful (0 votes)
13 views34 pages

Computer Mocks

The document explains various data types in programming, including character, integer, real, and boolean, along with their usage and conversion methods. It discusses the importance of binary logic, logic gates, and the differences between low-level and high-level programming languages, including their respective advantages and disadvantages. Additionally, it covers the concept of defensive design in software development, emphasizing the need for robust and reliable programs that can handle unexpected inputs and potential misuse.

Uploaded by

mansasingh2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views34 pages

Computer Mocks

The document explains various data types in programming, including character, integer, real, and boolean, along with their usage and conversion methods. It discusses the importance of binary logic, logic gates, and the differences between low-level and high-level programming languages, including their respective advantages and disadvantages. Additionally, it covers the concept of defensive design in software development, emphasizing the need for robust and reliable programs that can handle unexpected inputs and potential misuse.

Uploaded by

mansasingh2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

 The 'character' data type can store a single letter, number or symbol such as 'A', 'b', $, 4.

Note: Telephone numbers are stored as a string rather than an integer data type because an integer
data type will remove any leading zeros from the number

 The integer data type is used to store whole numbers - i.e. those without a decimal point.

For example

1234 is an integer
1234.0 is not an integer
 real is used to store numbers that use decimal points.
 Casting transforms one data type into another data type. Such as string to integer.

Symbol Example Purpose

str() str(123) number into string

int() int("4") string into integer

float() float("1.234567") string into 7 digits of precision number

real() real("1.123456789123456") string into 15 digits of precision number

bool() bool("true") string into boolean true or false

BOOLEAN LOGIC:
Why use binary form?

 Underneath the surface computers are electrical devices that process information by
controlling the flow of electricity through billions of wires and transistors (electrical
switches) inside the central processing unit and other components.
 The presence of electricity represents a 1, and an absence of electricity represents a 0.

The transistor

 Transistors are electrical components made from semiconductor materials that can act as
electrically-controlled switches.
 Transistors can be used to temporarily store data, for example in some forms of primary
storage (memory).

Logic gates

 Multiple transistors can be arranged together to form more complex "switches" that only
allow electricity to flow through if all or some of the transistors are "on".
 These arrangements are called logic gates.

Examples of logic gates

 The AND gate performs the boolean AND function:


o It will only output true if both of its inputs are true.
 The OR gate performs the boolean OR function:
o It will output true if either or both of its inputs are true.
 The NOT gate performs the boolean NOT function:
o It takes one input and inverts it.

 Binary logic is much the same as general logic, except it works on 1's and 0's. Given one or
more binary inputs a logical output will result.
 It is common practice to consider binary 1 to be 'True' and binary '0' to be 'False'.
 A truth table shows every possible combination of inputs and the resulting output.
 The truth table shows the input and output state for each combination.
 The table can then be used to look up the output.

A truth table lists every possible combination of input and the resulting output.

With two inputs there are 4 possible combinations (you work it out by 2^number of inputs) The
truth table above shows that the output Q is true only when all inputs are also true.
For example 3 inputs has 2^3 or 8 combinations
4 inputs has 2^4 or 16 combinations

AND

 AND evaluates to True (1) if and only if both operands are True (1).
 '.' is the symbol for the AND operator.
OR

 OR evaluates to True (1) if any of the two operands are True (1).
 '+' is the symbol for the OR operator.

NOT (negation)

 NOT negates a logical value.


 The symbol for the NOT operator is a line above the variable.
 For example, NOT A is written as A with dash above.
 Logic gates are made of transistors.
 Logic circuits are made of logic gates.
 Logic Statement
 A logic statement describes the output in terms of all the inputs and it can be used instead
of a truth table to work out the result of every combination of input.
 For instance you can also write a logic statement for the above logic diagram like this:
 Q = NOT (A OR B)

OCR
Exam
Logic operation
symb
ols

NOT A ¬A

A AND B A∧B

A OR B A∨B

LANGUAGES AND IDE

An instruction that can run inside a CPU is called machine code and is in binary

Assembly language (low level language)

Assembly language is made up of a predetermined set of commands that can be read by a person
(such as ADD). Each command translates directly into a machine code number. So these commands
are basically mnemonics used by people to more easily remember, read, and write instructions for
the computer.
Assembly language is called a low level language because it is almost the same as machine code. It
has a low level of abstraction i.e. there is a direct link between an instruction in assembly and the
machine code which it represents.
The complete set of commands available is called the instruction set of the CPU. And each type of
CPU has its own instruction set.
The instructions within an assembly language are called 'mnemonics' as they are much easier to
remember than a binary number.

Programming in assembly

Programming in assembly language is still quite difficult as the programmer needs to know a lot
about the hardware details inside the CPU. Another issue is that the code only works on a specific
CPU family. If you use a different CPU, you need to rewrite the code using a different version of
assembly language.
The main advantage of assembly language is that programs in Assembly run fast compared to
programs written in a high level language, because there is less code overall.
Why do we use LLLs?

 LLLs provide exact control over the central processing unit.


 LLLs need less translation, and often lead to faster code which is useful for computers
with low specifications such as embedded systems.

An example of a program that is typically written in assembly is a device driver, used to directly
control hardware such as a graphics card. Drivers need to be as fast and efficient as possible and so
assembly language is often used to create it.
High level language

High level languages were developed in order to make programming a lot easier for people,
compared to coding in assembly language.

A high level language has two main features

 It has a set of keywords such as PRINT or IF


 It has a set of grammar rules (syntax) which define how to combine them correctly

A programmer writes source code (programming code) using the allowed set of keywords and its
syntax rules.
There are many high level languages. For example Java, Python, C++, C and so on. High-level
languages are "machine-independent". That means that they can be ported to different computers
and still run.

 High-level languages are portable, which means that they can be run on many different
types of hardware.

However, source code needs to be converted into machine code to run in a CPU.

This is the task of a piece of software called a 'translator'

A translator is a piece of software that converts programming code into machine code. The
programming code could be high level source code or low level assembly instructions.

There are three different types of translators which are:

 Assembler - converts assembly language instruction into machine code


 Compiler - converts high level source code into machine code and stores it in an executable
file
 Interpreter - converts a single line of high level source code into machine code and then
immediately runs it on the CPU.

Compilers convert programs written in a high-level language into machine code instructions.
A compiler reads all the source code in one go, examining each keyword and their arguments. It
translates those keywords into a set of machine code instructions. Each keyword often translates
into a lot of machine code instructions.

Often, the compiler will check the code for basic syntax errors, and notify the user if it finds any.

Once the code has been successfully "compiled", it is stored in an executable file. This executable
file can then run without either the compiler or the source code being present.

 Compilers translate the whole of a program in one go.


 Compilers will provide a list of errors once it has attempted the compilation process:
o This can make debugging easier.
 C, C++, Visual Basic, and Swift are all compiled languages.

Pros of compilers

 Compilers produce an executable program:


o There is no need to repeat this process more than once per version of the
software.
 Compilers hide the source code from the end user:
o This helps to protect developers' intellectual property.

Cons of compilers

 The compilation process can be very slow:


o This can slow down development if many small changes need to be made.

 Much like a compiler, an interpreter translates source code written in a high-level language
into machine code. Where it differs from a compiler is that it doesn't translate the entire
source code in one go.
 Instead, an interpreter translates a single line of source code and then immediately carries
out the resulting machine code instructions. Then it reads the next line of source code and
does the same. It carries on doing this until the program is terminated.

 Interpreters convert source code into machine code instructions and execute those
instructions immediately, line by line.

 Because of this source code -> translate -> run loop, an interpreter tends to be a bit slower
compared to compiled code.
Pros of interpreters

 Interpreters will stop as soon as they encounter an error:


o This is useful for debugging.
 Interpreted languages are 'portable':
o This means that they can be run on many different types of central processing
unit as long as there is an interpreter available for the platform.

Cons of interpreters

 Running an interpreted program is slower than a compiled program because we have to


translate each line every time we run the software.
o But it is quicker to get started which can be good for small changes.
 Interpreters do not produce a compiled program file:
o The process must be repeated each time the program is run.

E.g Python and JavaScript

Assemblers

 Assembly is a very low-level programming language.


 Each instruction directly corresponds to a binary sequence, and the assembler replaces
the commands with the relevant binary.

Pros of assemblers

 Assembly provides exact control over the hardware:


o This can lead to very efficient code that takes up little space in memory and is
quick to execute.
 Assembly can be used on low specification machines.

Cons of assemblers

 Assembly is very difficult to use, and needs deep technical knowledge of the central
processing unit and the memory.

IDE:

An IDE brings all the tools necessary for coding into one application. The tools are designed to work
seamlessly together.

Integrated development environments (IDEs) are software packages that facilitate software
development. They provide a number of features to make programming easier:
Run-time environment

 The run-time environment (RTE) allows you to run programs to test how well they work.
 There are often multiple run time environments available so that you can simulate your
application on multiple different devices.

Code editor

 A code editor is a text editor which allows you to write the source code.
 The code editor usually contains extra features such as:
o Syntax highlighting.
o Code-completion.

Translators

 The IDE will usually have an interpreter, compiler, or assembler built in.
 The IDE usually abstracts the translation process by providing the user with a 'Run' button
rather than them having to use complex commands.

Debug tools

 IDEs usually contain error diagnostics which will highlight syntax errors in real time as you
program.
 IDEs usually also contain a debugger, which allows you to run your code line-by-line to
find faults.
 Features of IDEs

o Code editor

 Syntax highlighting

 Code-completion

o Debug tools

 Diagnostic tools

 Debugger

o Translator

 Compiler

 Interpreter

o Run-time environment

Editor:

Help you to write code efficiently and easily with aids such as colour coded highlighting, auto-
completion and brace matching.
Runtime Environment

This means it allows you to build the project from its files, compile it all and then run it as if the code
was running on the target CPU. It will not run as fast as the real thing, but it really helps complete
the project faster and easier.
Debug tools

These allow you to spot and correct programming errors.


A basic feature of debugging is to be able to single-step through the code. In this way you can see
how the variables are changing and how the program flows. To make it a bit more flexible you can
choose to 'step-into' a subroutine or you can 'step-over' it if you know it is working.

'Breakpoints' can be placed in the code and when that point is reached in the program as it runs, it
stops and allows you to see variable values at that instant. Another tool is 'Watch variables' with this
one you can tell the program to stop at the instant a variable has a certain value.

And of course it will highlight any syntax errors that are preventing the program from compiling.
Translator

This is either a built-in compiler or a built-in interpreter depending on the language. The compiler
IDE will create the final executable code and also be used within the run-time environment to
execute the source code.

 A scientific simulation has been written which will iterate many times.
 Should a compiled or an interpreted language be used, and why?
 A compiled language should be used.
 Interpreters would translate code for every iteration, whereas compilers translate the
whole code only once.
 Therefore a compiled program will perform better due to the reduced translation time.

 Every CPU runs binary instructions called machine code.

 Machine code is difficult to produce by hand.

 Assembly language provides mnemonics instead of raw machine code.

 A program written in assembly mnemonics is easier to understand.

 Assembly language is a low level language because each instruction has a machine code
equivalent.

 High level languages were developed to make it easier to write programs.

 There are many high level languages - C, Python, Javascript, Fortran.

 A program in a high level language is written as source code.

 Source code is made up of a set of keywords and arguments written down according to the
syntax rules of the language.

 A translator converts source code or assembly mnemonics into machine code.

 Compiler and Interpreter are high level language translators.

 A compiler converts all the source code in one pass to create an executable file containing
machine code.
 An interpreter converts a single line of source code into machine code and runs it.

 An IDE combines a set of standard development tools into one application.

DEFENSIVE DESIGN:

Defensive design is an approach to software development that aims to produce robust and
reliable programs.

Defensive design is the practice of anticipating every possible way that an end-user could misuse a
system or device. During the defensive design process, methods are put in place to eliminate misuse.
If this is not completely possible then it will aim to minimise the negative consequences.

You know that defensive design has not been good enough when

 The program crashes.


 The program behaves in an unintended fashion.
 Data security has been compromised.
 Defensive design considerations include:
o Anticipating misuse of the program.
o Writing maintainable code.
o Testing the program.

Anticipating misuse

 There are a number of ways that a system could be misused:


o Malicious inputs.
o Attempts to remotely connect.
o Attempts to alter access rights.
o Brute force attacks.

Robust and reliable

 Robust programs can handle unexpected inputs and data without crashing and without
being tricked into malicious action.
 Reliable programs will work as intended under many different conditions or situations.

Input sanitisation

 Input sanitisation involves the removal of unwanted characters from input data.
 This is a chief line of defence against attacks such as the SQL injection attack.
 Any data entered by users which might be executed or become part of a query should
first be sanitised.

Input validation

 Input validation is the process of making sure that input data meets certain criteria.
 If a user's data is rejected, they should be informed and asked to enter it again.
Input validation rules

 Type checks check the type (e.g. Integer) of the input.


 Range checks check that the data is inside an allowed range, e.g. less than 100.
 Presence checks check that the required data has been input.
 Format checks check that the data fits a set format, e.g. an email address has an @
symbol.
 Length checks check that the number of characters entered is inside a permitted range.

Authentication and contingencies:


Contingency planning

 It is impossible to predict all possible cases of misuse, but there are ways to help reduce
errors. For example:
o Providing helpful prompt messages.
o Providing error-recovery routes (e.g. an undo feature).
o Preventing access from certain parts of the system.
o Using exception handling.

Authentication

 Authentication is the process of checking that a person or system is authorised to use a


system.
 The most common form of authentication is to require users to enter a username and
password.
 Once a user has authenticated themselves, they should be able to see data relevant to
themselves and no one else.

Exceptions

 When an error arises in a program, the program is said to 'throw' an exception.


 An exception is a description of the error that arose.
 Exceptions can be 'caught' or handled rather than allowing the program to crash.

Handling exceptions

 If an exception can be dealt with internally, then we can catch the exception and
continue with the program.
 This is done using a structure as below:
o try: ---
o except: ---
 The code within the try block will be executed.
o If an exception is thrown inside the try block, then the except block will be run to
'clean up' after the exception.
A menu-driven user Interface limits the user to being able to pick from a displayed list of choices.

Validation seeks to ensure that the data entered is valid for further processing by the program
handling it.

The four validation methods are

 Checking and limiting the Length of the data


 Checking the Range of the data
 Checking the Type of the data
 Checking the Format of the data

Length validation is checking to see if the entered value is within the allowed number of characters.
For example, password forms may reject an entry if it is less than three characters, as it would be too
short for security. Empty fields (those with a length of zero) may also be rejected.
Range validation

Range validation is used when inputs have to fall between certain values. If a form asks for the user's
age, then it makes sense to check that they do not input a negative number, or a decimal. Defensive
design in this case is writing the software code to check that these conditions are met.
ype validation

Type validation is checking that the input conforms to the allowed data types.

For example, perhaps the input can only be a numeric value and so alphabetic or symbol characters
are rejected. The software must be coded to deal with these inputs without causing a program error.
Format validation

The data format is often important, inputting data records into a database often needs to check that
the input is in the correct format.

For example an UK National Insurance number has the format XX999999X where the first two and
the last characters must be letters whilst the middle characters are numeric.

Authentication is a way of confirming that the user is authorised to access the system.
Username & Password

The most common way of doing this is to ask for a username and password. The entered details are
then checked against a database containing valid accounts.
Two-factor authentication

For high security sites such as financial services 'two-factor' authentication is becoming popular. This
means that after the user enters a valid user name and password, the system sends an SMS text
'authentication code' to the designated mobile phone. They then have to enter this as well.

The idea is that an unauthorised person is less likely to have the mobile phone to hand as well.
Biometric authentication

This method checks some physical feature of the authorised person such as their fingerprint. The
user puts their thumb on a fingerprint entry device, the data is sent off to a database and checked
against their valid data.

A program may need modifying for any of the following reasons:

 To add a new feature

 To fix a bug

 To improve the speed or performance

 To port it so that it will run on a different CPU or Operating System

The process of ensuring that code can be easily amended or updated is called Maintainablility.

Maintainable code is code that can be read, understood, and fixed by other developers.
Comments

 A comment is a line of code that is completely ignored by the computer.

Purpose of comments

 Comments can be used to add description to your code to make it easier for other people
to understand.
 They can also be used to leave notes and reminders to yourself as you work on a complex
program.

How to comment

 To write a comment in most languages, you must use a special character which tells the
computer to ignore the rest of the line:
o In Python, that character is a #.
o In C-style languages it is //.
 The exact character depends on the language being used.

 Comments should be used throughout the code to:


o Explain complex processes.
o Clarify the purpose of algorithms.
o Clarify the purpose of a subroutine, as well as its parameters and return type and
value.

include comments after each of the following:


 Variables and constants - While you should use descriptive names for every variable and
constant, comments can provide an extra hint about what you intend to use them for.
 Procedures and subroutines - These, more than any other type of code, cause the program
flow to jump around between sections, so you should include a description up front about
what data each subroutine is calling, what it is doing to that data, and what it returns to
the main program.
 Throughout the program - Good programmers include enough comments that the reader
could, if they wanted to, rewrite the program following just the descriptions provided. At
the same time, comments should describe what a block of code is doing overall, rather
than specific descriptions of what every line is for.

Indentation

 It is good practice to keep indentation of code consistent throughout the code.


 When a new block of code opens, it should be indented to the right.
 When a block of code closes, it should return to the left.
 This makes code easier to read by visualising the scopes involved.

Parameters vs global variables

 It is good practice to pass data around the program using parameter passing rather than
using global variables.
 This is because passing parameters prevents other subroutines from unexpectedly
changing the value of the variables.

Identifier names

 Identifier names should be clear about their purpose. For example, which of the following
two examples makes more sense:
o newBalance = oldBalance * INTEREST_RATE;
o a = b * c;

Code structure

 Code should be well structured through the use of subroutines.


 This allows people to identify a single subroutine that they need to reuse or work on.

TESTING:

Errors in software are often called bugs. Testing helps to identify bugs. Debugging gets rid of
bugs.
Bugs

 Bugs are mistakes in the programming of a system.


 Bugs are not deliberate attempts to bring down systems

Testing

 The purpose of testing is to check that a program:


o Works as intended under good conditions.
o Copes with errors when given bad data.
 Different types of testing take place at different points in the development and
deployment of a solution.

This process of spotting and correcting mistakes is called 'debugging'.

TYPES of testing:
Terminal testing

 Terminal testing happens at the end of development:


o The results of this final testing are used to check how the software performs
when given a certain set of test data.

Iterative testing

 Iterative testing involves testing code as it is written.


o The results of this continual testing are fed back into the development process.

Test data

 To make sure that testing is thorough, both expected and unexpected data should be
used in testing:
o Valid data is correct and of the right format.
o Extreme data is correct but on the edge of the valid range.
o Invalid data is not within the acceptable range or is an invalid format.
o Null data is where no data is entered to see what happens.
o Erroneous data is of the wrong type altogether.

Test plans

 Test plans make sure that testing is effective by detailing exactly which tests will be
performed, what test data will be used, and what the system's intended outcome should
be.
 A test plan should be created before development. It is part of the design stage.
 Testing should cover all of the success criteria of the project

Syntax errors

 A syntax error is a mistake in the way the code is written.


 It is similar to a spelling or grammar mistake in English.
 Syntax errors prevent programs from running as a translator needs code to be
syntactically correct.
 Misspelling, forgetting brackets, missing end of line marker, case sensitive.

Logic errors

 Logic errors are mistakes in the logic of the program.


 Programs will run, but their outcome will not be as intended.
 They are much more difficult to debug than syntax errors.
Runtime errors

 Runtime errors are errors that happen while the program is running.
 Runtime errors cannot be found during translation.
 These errors can only be detected while a program is running.
 The chance of experiencing a runtime error can be reduced through testing.

Examples of runtime errors

 Bad inputs that throw an unhandled exception.


 Receiving unexpected or corrupted data.
 Running out of memory.

Debugging tools and methods

 Comments
 Debugging outputs
 Break points A 'break point' is a command for the debugger to stop running the code right at
that point.
 Single-stepping
 Test code a good way to spot the logic error is to write some test code and apply it to that
chunk of code.

Testing ensures that the program

 Works correctly without error


 Meets the needs of the user

A test plan is a formal document which details the tests to be performed on the software. It
describes:

 The scope of the testing


 The tests to be performed
 The reason for each test
 The data to be used in tests
 The expected outcome of each test

Whilst writing the test plan, the 'test data' that is going to be used for each test, must be identified.

There are three types of test data :

1. Normal use data


This is the data that is expected to be entered into the application.

2. Boundary / Extreme data

This is testing the very boundary of acceptable data. Boundry data is still acceptable and it will be
processed in the same way as normal data.
For example, the user is asked to enter a username with between 1 and 10 characters. The
borderline test data would be a username with 1 character and a username with 10 characters.

Boundary data is excellent for testing the hard limits written into the software and that the
application still runs properly when handling it.

3. Invalid or erroneous data

This is data that the program rejects as invalid. That might be because it is the wrong data type.

If invalid data is presented, then the application needs to handle it properly i.e. not crash. Usually the
user is told that the data provided has been rejected.

During program development, the programmer will write a portion of their code. They will then test
the code they have just written to check that it is working as expected before moving onto
developing the next part, and testing again.
This is called iterative testing.

Final testing, otherwise known as 'User Acceptance Testing', 'Terminal testing', or 'Project sign off', is
done after the project is thought to be complete.

Final testing is carried out using the "black box" testing approach.

Just like the earlier tests, the process of final testing will have been laid out in the initial test plan,
according to user requirements, complete with the exact test data to use and the expected
outcomes.

PROGRAMMING FUNDAMENTALS:

Declaration

 Before variables can be used, they must be declared.


 Declaring a variable means telling the computer:
o What the identifier (name) should be.
o What type of data will be stored.
o A variable is a location in memory that holds one or more values. It has a label or
name to identify it and its values can be changed as the program runs.
o A constant is a location in memory that holds a value. It has a label or name to
identify it and its value cannot be changed as the program runs.
o An advantage of using a constant is that it only needs to be declared in one place.

Assignment

 Changing the value stored inside a variable is called assignment.


 The value assigned to a variable must match the data type of the variable.
 Assignment operators assign values.
 The simplest assignment operator is "=".

 The compound assignment operators include:-


 a += b (a = a + b)
 a -= b (a = a - b)
 a *= b (a = a*b )
 a /= b (a = a/b)

Language specifics

 Some languages don’t need you to declare variables before you use them:
o These languages automatically declare the variable before the first assignment.

Input

 Input is collecting data, usually by the keyboard.


 This is written in pseudocode as:
o OUTPUT "Please enter [something]..."
o variable = USERINPUT

Output

 Output is putting data to the screen, usually as text.


 This is written in pseudocode as:
o OUTPUT "Text goes here”

Sequence

 In a sequence algorithm, the computer follows a series of steps that are executed in the
same order every time it runs.
 This is often not very useful for longer codes because we cannot use any selection or
iteration structures.

Flow chart

 The flow chart for a sequence program will have the blocks one by one.
 One arrow will connect each block to the next block.
 There will be no diamond shapes, so the diagram will be mainly:
o Ovals.
o Rectangles.
o Parallelograms.

Selection

 Selection allows us to execute a section of code depending on whether a condition is met


or not.
 Meaning Symbol

Greater than >

Less than <

Greater than or equal to >=

Less than or equal to <=

Not equal to !=

Are the same ==

The last one (==) is often confused with the equal sign =. They are not the same thing.
If you use =, you are setting (aka assigning) one value to be equal to another.
If you use ==, you are comparing one value to another to see if they are equal.

If-statements

 An if-statement is an easy way of checking if a condition is true.

 The start of the statement is marked with an IF, and the end of it with an END IF. You can
instruct the program to do any number of things between the two.
 Do you notice the expression between IF and THEN? The expression is a comparison that can
only be true or false. If the expression is true then the source code between the IF and END
IF is run. If the expression is false then the program jumps to the next statement after the
END IF.

Switch-case statement

 A switch-case statement checks the value of a single variable.

 IF is a very versatile type of conditional statement. But once you begin having to nest
multiple IF statements inside one another in order to match a complicated set of conditions,
the code can start to become very awkward to read and difficult to follow.
 Some programming languages solve this issue by introducing a different type of conditional
statement: SWITCH / CASE.
 SWITCH / CASE allows the programmer to set up a list of possible options, and jump straight
to the one that matches the current conditions.
 Just like an IF statement, SWITCH / CASE accepts an expression (in this case,
"Number_of_Pets") and evaluates it. But CASE can handle multiple options with a single
check of the conditions.

 In the OCR exam reference language the format is


 switch ... :
 case ... :
 case ... :
 default :
 endswitch

Flow diagram

 The diamond symbol is used to show selection in a flow diagram

Iteration allows a group of statements to be repeated multiple times. Iteration statements are
often called loops

Definite iteration

 A block of code will repeat a known number of times.

Indefinite iteration

 A block of code will repeat while a specified condition is true.


 A flow diagram for iteration uses the diamond shape.

 In pseudocode, WHILE loops begin with the keyword WHILE and end with the keyword END
WHILE. The code to be repeated is often indented to make it easy to tell apart from the rest
of the algorithm.

 count = 1
 WHILE count < 10
 PRINT count
 INCREMENT count by 1
 END WHILE
 In this example, the algorithm sets a variable called count to 1. Then the WHILE loop is set to
test if count is less than 10. If it is then the PRINT and the INCREMENT pseudocode is
applied.
 It is important that the algorithm sets a starting value for the variable count because the
while loop needs something to evaluate. This is called 'initialising' the variable.
 There is no limit to the number of times a WHILE loop can potentially run. So it is important
that the condition that the loop is checking will eventually become false. Otherwise the loop
carries on forever.

 Loops repeat tasks. A FOR loop runs for a set number of times. A WHILE loop will continue to
run until a certain condition is no longer met.

 Much like WHILE and REPEAT, FOR loops are used to carry out the same task a number of
times. But unlike the other types of loop, FOR loops only run for a set number of times,
determined by a 'counter'.
 They end with NEXT (counter name). Every time the loop goes around, the computer
automatically increments the counter by 1. So no specific program line is needed to do the
incrementing. Once the count is complete, it exits the loop.
 For example
 FOR a = 1 TO 10
 PRINT 'I am looping'
 DISPLAY a
 NEXT a

 The counter variable in this case is called the single letter 'a'. Its starting value is 1 and the
final value is 10.
 The PRINT and the DISPLAY pseudocode is carried out
 then the 'NEXT a' increments the counter
 and the algorithm jumps back to the FOR line to test the counter once more.
 Once the counter reaches its end point (in this case, 10), the loop ends.
 In the OCR exam reference language the format is
 for ... to ...

 next ...

 And for steps of more than one it is

 for ... to ... step ...

 next ...

Arithmetic Operators

Basic operators

 Addition is done using a + sign.


 Subtraction is done using a - sign.
 Division is done using a / sign.
 Multiplication is done using a * sign.
 Exponentiation is done using a ^ sign.

Integer division

 The integer division operator returns the quotient (whole part) of a division.
 For example:
o 5 DIV 2 would give 2.

Modulo operator

 The modulo operator gives the remainder of the division of two numbers.
 For example:
o 5 MOD 2 would be equal to 1.
 Relational Operators
 Relational operators compare two values, and produce a True or False value.
Equality

 We can test if two values are equal using the equality operator. For example:
o 2 = 2 would evaluate to True.
 We can test if two values are not equal using the not-equal-to operator:
o 2 ≠ 2 would evaluate to False.
Boolean Operators
 Boolean operators perform logical operations and always result in True or False values.
 True OR True = True.

Arrays are useful when you have access to large amounts of related data, but you don't
want to store in multiple variables.

There are many different ways to organise data, and each way is called a "data structure". One such
data structure is called an 'array'.
it allows related data item to be stored as a group.
Arrays

 Arrays are a data structure that store a fixed number of values under a single identifier.
 The values must be of the same type.
 An array is a collection of related data. Each piece of data within the array is an element. The
position of each element within the array is pointed to be its index. Arrays usually begin at
index 0, not index 1.

 In order to access an element of an array, you use its index


 Like this
 MyArray = (3,56,21,5,7)
 print MyArray[1]

 This will print out '56' because that is the element at index 1.
 You can also change the value of an element by using its index, like this
 MyArray = (3,56,21,5,7)
 MyNumber = 11
 MyArray[4] = MyNumber
 This will replace whatever was in position 4 in the MyArray array with "11". So we are
replacing the number 7 with the number 11

Array elements

 Each piece of data inside an array is called an element.


 Each element has an index, which is its position within the array.
 We start counting the indices from 0.

Arrays in pseudocode

 An array of ten items can be created using the following syntax:


o array name_of_array[10]
 Values can be assigned as follows:
o name_of_array[0] = "Hello"
 Values can be accessed as follows:
o print(name_of_array[0])

 A static array has a defined length which does not change.

 The length of a static array is declared in advance, like this


 array MyList[5]

 Like this
 array MyList[]

 The length of a dynamic array can change as a program runs.

For example, when you want to print every item in a long array, you could use a FOR loop
like in this pseudocode:
 01 FOR x = 0 TO MyList.length - 1
 02 PRINT MyList[x]
 03 NEXT x

2D Array

 A 2D array is a data structure where arrays are filled with other arrays.
 This can be used to represent a 2D surface, or records.
 two dimensional array, also known as a matrix. Where one-dimensional arrays are lists, two
dimensional arrays are tables.
 To locate an item in this table two pieces of information needs to be provided - the row
number and the column number. For instance, the value "23" is at row 1 and column 1.

 The 2D array looks like


 My2DArray [3,4]

 The pseudocode above is declaring a 2D array made up of 3 rows and 4 columns. A 2D array
can be used to store tabular data very efficiently.
 2D array is ideal for storing any data that has been arranged in a grid - for example the
computer screen you are reading right now is made up of pixels, and any pixel can be
identified by its vertical and horizontal location.
accessing elements

 To access an individual array, we can access the array as usual:


o array = my2DArray[4]
 To access an individual element, we use this syntax:
o array[5][0]
 This would get the first element of the sixth array.

Uses of 2D arrays

 2D arrays are often used to represent a 2D surface, for example a chess board:
o Each element of the 2D array could contain the chess piece in that location.
 2D arrays can be used to represent a database:
o The outer array stores a collection of records.
o The inner arrays store a single record.

 In OCR pseudocode you should add .length to the string statement.


 For example if you wanted to know how many characters (including symbols and spaces) are
in this string:
 MyString = "Hello"

 You would use the .length extension as follows:


 MyString = "Hello"
 print MyString.length

 Since "Hello" is five characters long, this command would print out "5".

common string functions

 Convert string into all upper case

 Convert string into all lower case

 Split a string at a given position into two strings

 Trim a string so there are no start or trailing white spaces

 Remove all white space from a string


 Extend a string by duplicating itself (5 become 5555 etc)

Concatenation

 Concatenation is joining two strings together.


 This can be done with the + sign. E.g:
o "Hello " + "World" = "Hello World".

Accessing a character

 Remember, strings are just lists. So we can access a specific character in the exact same
way as we access a list element:
o string[3] would get the fourth character.

Length of a string

 The length of a string is given by the len function:


o len("Hello") would give 5.

Substrings

 A substring is a part of a longer string.


 In pseudocode, we use the function:
o stringname.subString(startPos, numberOfChars)
 This takes a substring starting at the 'startPos'th character, and takes the stated number
of characters.

Complete the code snippet:

myElement = my2DArray[5][0] // Select first element of sixth array.

Without files, we can only store data in the memory.


Text files

 Text files consist of string data that can be read and processed by many applications.

Binary files

 Binary files consist of binary data that is read and processed by specific applications.

Files

 Files allow us to store data so that it persists even when our program is not running.
 This allows programs to 'carry on where they left off' when they are executed.

Open the file

 First we open the file for use, so that the operating system knows that we are using it.
 We can do this using:
o openRead("filename.txt")
o openWrite("filename.txt")

 In Python, the command is:


 Myfile = open ('filename', 'mode')

 The open command has two arguments. The first is the name of the file, and the other is the
'mode' in which the file is to be opened.

Assign the file to a variable

 The file must be assigned to a variable so that we can keep refering to it.
 This can be done as follows:
o myFile = openRead("filename.txt")
o myFile = openWrite("filename.txt")

Read / write

 We can now read or write to the file using the following commands:
o myFile.readLine() will return the next line of a file as a string.
o myFile.writeLine() will write a line to the file.
o myFile.endOfFile() will return True if we reach the end of the file.

Close the file

 Finally, we must close the file so that it is free for another program to access.
 We can do this using:
o myFile.close()

 In Python, you close files using the close() method


 Look at this example of Python code:
 filehandle = open('mytextfile.txt', 'r')
 filehandle.close()
 filehandle = open('mytextfile.txt', 'w')
 filehandle.write('this is a test')
 The first line of code shows a file called mytextfile.txt being opened in 'write' mode. If the
file doesn't exist, the open command will create it. If mytextfile.txt already exists, then all
the data within it is discarded, ready for the program to write new data into it.
 If a number of lines needs to be inserted, then the command is just repeated. You will need
to tell the program to add new lines using the newline character (\n), or it will just put
everything onto the same line.

 filehandle.write('Monday\n')
 filehandle.write('Tuesday')

 This results in a text file containing two lines of text.


Using append

The 'write' mode effectively creates an empty file by discarding all of the existing data within that
file.

If the data needs to be kept, then don't use 'write'. Instead, open the file in 'append' mode. This will
keep the existing data intact, and any new data is added to the end of the file.

In Python the read() method is used to read in the entire file into one string variable. Like this:
filehandle = open('mytext.txt', 'r')
MyString = filehandle.read()

This reads the entire file into the variable string MyString. There has to be enough computer
memory available to do so, or an error will occur.
You can use the same Python method to just read part of a file, by telling the program how many
characters from the file you would like it to enter. Like this:
fh = open('mytext.txt', 'r')
MyString = fh.read(1000)

This will enter the first 1000 characters from the file rather than the entire file.

A database is a collection of data or information which is held together in an


organised or logical way.
Each column in a table is called a field and contains information about a particular
item of data. Each row in a table is called a record.

 Each piece of information is entered into a 'field'

 Related fields are organised into records

 Related records are placed into tables

 Related tables are collected into a database

 Records
 Structured data refers to any data that resides in a fixed field within a record or file so
that it can be easily entered, stored, queried, and analysed.
Records

 Records are made up of fields.


 For example, a person could be represented as a record where the fields include their
name, age, and address.

Comma separated values (CSV)

 One method of storing a record is using comma separated values.


 Each record is put on its own line.
 Each field is separated by a special character such as a comma.

Pros and cons

 Pros:
o Very simple, text-based format.
o Can be read by many applications.
o Easy to use in programs.
 Cons:
o Inefficient for large datasets.
o Can only store text data.
o No built-in means of sorting or searching.
 Structured Query Language
 A database is a structured collection of data. Structured query language (SQL) is a
language used to query this data.

 If we wanted to retrieve every record from this table, the SELECT command is:-
 SELECT * FROM Characters

 The asterisk * is called a 'wildcard' and it means 'all records' or 'all fields'. The FROM is
followed by the name of the table.
 If we wanted to fetch all fields from within a specific record then the wildcard is useful for
that as well, for example if we wanted all fields from the Donald Duck record the SELECT
statement is
 SELECT * FROM Characters WHERE First Name = "Donald"

 The SELECT command is also used to fetch specific fields from within a record set. For
example
 SELECT Address, City FROM Characters WHERE First Name = "Donald"

Wildcards

 Sometimes we don't know the exact value we want to use in a where clause.
 We can use wildcards to find records which match some sort of pattern.
 We can use the % symbol to represent anything. For example, if we want to find any
names starting with 'Ba' then we could query:
o SELECT name FROM users WHERE name LIKE "Ba%";

Where clause

 Sometimes we don't want to return data for all records.


 We can filter the data using a where clause as follows:
o SELECT * FROM users WHERE ID=3;
 The above line would only return a user's data where they have an ID of 3.

 The general format of the SELECT ... WHERE command is :-


 SELECT fields FROM table WHERE Criteria
SQL

 SQL is a language that can tell databases what to do.


 SQL can be used for selecting, inserting, updating, and deleting data.
 For GCSE you only need to know how to select (search for) data.
Select statements

 A SELECT statement searches for and returns data. E.g:


o SELECT * FROM table_name;
 The * character tells the database to return all fields.
 The * character can be replaced by specific fields. E.g:
o SELECT name FROM users;

Inputting into an array

Let's consider a problem:

Write a program that requests the user to input a list of their favourite animals. The user types in
'end' to indicate that the list is complete. This data needs to be stored and then printed out once the
input is complete.

Solution

As the data is a list, an array should be used. And as the list is open-ended, a dynamic array should
be used.

The first lines of pseudocode are:

01 array favourite_animals[]
02 count = 0
Line 1 declares a dynamic array and the second line initialises a variable named count which will be
used with the array.

A DO - UNTIL loop will be used to keep asking the user for their input
03 DO

04 animal = INPUT("Enter animal name or type end")


05 IF animal != 'end' THEN
06 favourite_animals[count] = animal
07 INCREMENT count
08 END IF
09 UNTIL animal == 'end'

Comments:

 Line 3 is the start of the DO loop


 Line 4 asks for user input and stores it in animal
 Line 5 is checking if end has been entered, if not then the array is updated
 Line 6 copies the value of animal into the array favourite_animals at index count
 Line 7 increments the index counter count
 Line 8 is the end of the IF block
 Line 7 the UNTIL checks to see if the word end has been typed in yet, if not loop back to the
DO

Once end has been entered, the loop is finished. Now the pseudocode below will print out the
animal names
08 PRINT "Your favourite animals are\n"
09 FOR x = 0 TO favourite_animals.length - 1
10 PRINT favourite_animals[x] + "\n"
11 NEXT x

Comments:

 Line 8 prints out the heading, including a newline character to force a new line
 Line 9 the FOR is traversing the array from beginning to end
 Line 10 prints out the animal name from the array and concatenates a newline character as
well
 Line 11 loops back to the FOR

Once all the array has been printed, then program exits the FOR loop.
Complete program

This is the complete program


01 array favourite_animals[]
02 count = 0
03 DO
04 animal = input("Enter animal name or type end")
05 favourite_animals[count] = animal
06 increment count
07 UNTIL animal != 'end'
08 PRINT "Your favourite animals are\n"
09 FOR x = 0 TO favourite_animals.length - 1
10 PRINT favourite_animals[x] + "\n"
11 NEXT x

Array functions

There are a number of common actions that can be done on arrays. These include

 append - add an item to the end of an array

 insert - insert an item at a specific location in the array, all the data above is moved up one
location

 delete - remove an item from a location, then all the data moves down one place.

 split - split an array at a given point and create two new arrays.

 slice - take a chunk of data out of an array to form a new array, the original array remains
intact

Many computer language have built-in commands that can carry out these types of actions.

If the action is not available in that language, then a procedure can be written to carry it out.
Random numbers:

In your exam, the OCR exam reference language format will use this format to form a random
number:
random( ..., ....)
for example, to return a random number in the set 1 to 6, the command is

random (1,6)

Import:
from random import random, sample

using random ()

The random() function returns a random floating point "real" number between 0.0 and less than 1.0

We declare a variable called 'num' and assign the returned random number to it. In Python, this is
done using the assignment operator = :
num = random()

Then this number is printed out, along with a description.

In pseudocode, this would use the keyword OUTPUT. The Python equivalent is "print":
print('Random floats 0.0 to 1.0: ', num)

The file is run in the IDE and the Shell shows the resulting floating point number. Every time the
script runs, a different random number will be produced.

random() generates a random number between 0.0 and 1.0. So the first step to getting an integer
between 1 and less than 10 is to multiply our generated random number by 10.
random()*10

At this point, it's still a floating point number. It might have some data after the decimal point. So we
need to convert it to an integer. You can read more about converting, or "casting" one data type to
another in our data types section. In python, you can convert numbers into integers using the int()
function.
int( random()*10 )

Since int() rounds down, we now have a random integer between 0 and 9. If we want it to be
between 1 and 10 instead, we need to add 1 to the result:
int( random()*10 ) + 1

Now we have a random integer between 1 and ten. Time to assign it to a variable, so that the
program can keep track of it. Let's use "num" again.
num = int(random()*10)

And the 'print' command displays it:


print (num)
The loop needs a counter so that it can iterate the correct number of times and no more, we shall
give the counter a single letter name:
i=0

Next, the python empty list needs to be declared.


i=0
myarr = []

An initial message is displayed before the loop begins:


i=0
myarr = []
print('Six random integers 1 to 10: ')

which helps the user understand the purpose of the output.

Sub procedure:

The code in red is just doing the same thing, over and over. In order to create a sub-procedure, take
this block of code and enclose is in a procedure statement, like this
procedure
FullName = FirstName + SecondName
Print FullName
end procedure
This block of code needs to be given a sensible name in order to use it - let's call it print_name as
shown below
procedure print_name
FullName = FirstName + SecondName
Print FullName
end procedure
We are still not quite there yet, because the code is using two
variables FirstName and SecondName but these need to be defined before they can be used. So let's
supply that information to the procedure. Like this
procedure print_name (FirstName, SecondName)
FullName = FirstName + SecondName
Print FullName
end procedure

We can describe a subroutine as:

A subroutine is a block of code intended to be used a number of times within a program. The code is
packaged as a single, named, unit.

The action of accessing a subprocedure is called 'calling' a subprocedure. When it is called, the code
within it runs and then the program returns to the next line of code in the main program.

Another advantage of using a procedure is reliability. The block of code only needs to be tested in
that one place in the program. Once it is proven to work, the programmer can be confident that it
will work no matter where it is called from. This also saves a lot of programming time.
Another common name for a sub-procedure is subroutine.

Advantages of using a sub-procedure

 More efficient program


 Improved reliability
 Saves total programming time
 The example we used was supplied with two values, known as the parameters of the
subprocedure. There can be zero, one or any number of parameters passed into a
subprocedure. For example
 hello_world() - a subprocedure with no parameters
 hello_world (Name) - a subprocedure with one parameter required

Function and Subprocedure difference

The difference between a function and a subprocedure is that a function always returns a single
result whereas a subprocedure may return none at all or many values.
Advantages of using subprocedures

When code is structured in this way it offers some real advantages

 It is simpler for others to read the code and understand what it is doing
 It is simpler for yourself to understand your own code if you have been away from it for
months or years
 It is easier to test the individual parts of the program
 It is easier to allocate parts to different members of the team
 It is easier to maintain and update the code in the future
 It is easier to re-use some of the code for other projects

Linker
Sometimes a large program is broken down into several software modules. Each module is compiled
into an object file which has machine code. Then these object files are linked together to form a
single executable file. The software that combines object files is called the linker.

You might also like