Computer Mocks
Computer Mocks
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.
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.
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)
OCR
Exam
Logic operation
symb
ols
NOT A ¬A
A AND B A∧B
A OR B A∨B
An instruction that can run inside a CPU is called machine code and is in binary
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?
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 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.
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.
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.
Pros of compilers
Cons of compilers
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
Cons of interpreters
Assemblers
Pros of assemblers
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
'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.
Assembly language is a low level language because each instruction has a machine code
equivalent.
Source code is made up of a set of keywords and arguments written down according to the
syntax rules of the language.
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.
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
Anticipating misuse
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
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
Exceptions
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.
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.
To fix a bug
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
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.
Indentation
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
TESTING:
Errors in software are often called bugs. Testing helps to identify bugs. Debugging gets rid of
bugs.
Bugs
Testing
TYPES of testing:
Terminal testing
Iterative testing
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
Logic 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.
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.
A test plan is a formal document which details the tests to be performed on the software. It
describes:
Whilst writing the test plan, the 'test data' that is going to be used for each test, must be identified.
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.
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
Assignment
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
Output
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
Not equal to !=
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
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
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.
Flow diagram
Iteration allows a group of statements to be repeated multiple times. Iteration statements are
often called loops
Definite iteration
Indefinite iteration
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
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.
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
Arrays in pseudocode
Like this
array MyList[]
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 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
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.
Since "Hello" is five characters long, this command would print out "5".
Concatenation
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
Substrings
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.
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")
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.
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.
Finally, we must close the file so that it is free for another program to access.
We can do this using:
o myFile.close()
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.
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
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
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.
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
Comments:
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
Array functions
There are a number of common actions that can be done on arrays. These include
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()
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)
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
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.
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
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.