Upload
philgiddyboy
View
52
Download
0
Embed Size (px)
DESCRIPTION
OCR programming notes
Citation preview
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 1 of 21
Designing Solutions to Problems (3.2.1) Programs aim to ensure that the...
o User can input data easily o Output is clear and understandable
Aim is to be user friendly, i.e. effective, efficient and satisfying for the end user.
Very often, the user interface requires data to be input using a keyboard and mouse.
Usually takes the form of a GUI (Graphical User Interface) or a form-based interface.
A number of factors should be considered when designing an input screen...
o The user – age, computer literacy, disabilities etc.
o Layout – using headings, not cluttering but using all space etc.
o Order – heading at top, action buttons (in forms etc.) at bottom
o Validation – interface should reject invalid data
o GUI objects – objects should make data input efficient / avoid errors
o Online help – interface should keep user informed (progress bars etc.)
Data capture forms are used to collect data to be input into a program.
o Layout – data fields should match / correspond to paper version
o Instructions – no validation checks on paper; clear instructions essential
o Readability – if data cannot be read, it cannot be input (encourage CAPITALS)
Reports are presentations of data – must consider...
o The user – age, computer literacy, disabilities etc.
o Type of output – often a pie chart can be clearer than text, for example
o Title – report may be stored and later read out of context; heading essential
o Date – representative of data at a specific time; date should be included
Allows the user to input and output all data accurately. Reduces potential of costly errors.
Makes best use of facilities available to the program, e.g. quick processor time. Efficient interfaces increase productivity for the user.
Comfortable for end user – program is easy to learn: use of familiar tools and icons etc. Keeps down training costs and improves morale.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 2 of 21
When designing other types of interface, such as touch screen interfaces, other
factors must be considered. For example, the contact areas must be large enough on
the touch screen to be used effectively.
People with disabilities should also be catered for, for example, by adding sound
output in addition to the visual output.
Remember that programs do not necessarily run on a computer.
Embedded software (like in a vending machine) will need to be designed.
User interface will typically include custom input methods.
Software will need to be designed before the main program is written.
Output may involve custom screens, LEDs or sound.
Programs need to be presented so that they can be easily checked for completeness.
This can be done using a data dictionary.
This is a file containing descriptions of the data in a program – these details include:
o Identifier (i.e. the name) for variables / fields
o Data type / data structure
o Size of the data
o Any validation that needs to be carried out on the data
As computer programs are so complex nowadays, it has become difficult for one
person to devise a solution or to implement it on their own.
A modular, top-down design can be used to tackle such problems.
Tasks are continually split down using stepwise refinement.
Subtasks are implemented independently as modules.
These modules are then put together to create a solution for the main problem...
Mobile phone (for example)
Voice calls
Receiving voice
Sending voice
Capture voice
Convert voice to digital
Transmit on network
Text messages
Receiving text
messages
Sending text messages
Multitap text entry
Predictive text entry
Transmit on network
Phonebook
Multitap entry
Search functions
File access
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 3 of 21
There are many advantages to modular design:
1. Program is easier to write and test.
Each module is small and can be written independently.
2. Design clearly shows how different parts of program relate.
Reduces errors caused by different parts of a large program.
3. Programmers working on separate modules can easily develop the program.
Modules can be allocated according to expertise of programmer.
4. Modules are written separately to perform a small, specific task.
Can be reused in other parts of the program.
An algorithm is a sequence of steps designed to perform a particular task.
Well-designed algorithms list every instruction the computer needs to execute.
This allows the computer to solve the problem.
Program flowcharts use a diagram to show the operation of the algorithm.
They use conventional symbols and flow lines...
Start / Stop There should only be one start point, although there can be multiple stop points.
Process Operations and instructions which do not involve making a decision, an input / output.
Input / Output Used to show that an input or an output operation should be carried out.
Decision Decision needs to be made. One entry point and at least two exit points.
Subroutine Complex operations can be represented with a subroutine.
Connector Used to show points of the flowchart that should be connected to each other.
Pseudocode is an alternative method that uses text instead of a diagram.
It is effectively a simplified version of programming code.
Common programming language functions are mixed with English phrases.
There are no real ‘rules’ for writing pseudocode, but guidelines do exist.
o Describe each step as briefly as possible.
o Use uppercase letters with keywords.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 4 of 21
o Use lowercase letters with code close to English.
o Indent as appropriate.
Rapid Application Development is a method for designing and writing software.
It produces successive prototype versions of the software.
This continues to happen until the final version is produced.
RAD is similar to the spiral model.
o Several increasingly refined prototypes are created.
To solve the problem, programmers produce a prototype with reduced functionality.
This is then reviewed with the end user who can suggest changes.
This cycle is repeated producing successive prototypes, each time improving.
Referred to as iterative development, each cycle lasts typically one to three weeks.
Advantages of RAD include:
1. End user is involved in development process.
Prevents problems caused by misunderstood requirements.
2. Prototyping means a tangible product can be seen earlier in the project.
Provides more confidence for end user about correct solution.
3. Generally the length of development is shorter compared to waterfall model.
Uses Computer Aided Software Engineering (CASE) tools.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 5 of 21
Disadvantages of RAD include:
1. Not efficient when dealing with large-scale projects.
Initial prototypes dynamically different from final product.
2. Focuses on end result rather than on the processing.
Can produce solutions that are inefficient in their use of resources.
The Structure of Procedural Programs (3.2.2) These are short definitions of key terms for structures of procedural programs.
The definitions highlighted in red above at the three basic programming constructs.
These allow us to control how the program will execute the statements in it.
ITERATION is useful because otherwise we would have to write the instructions out
the correct number of times.
There are two types of control loop, condition-controlled and count-controlled.
o A condition-controlled loop keeps going until a certain condition is met.
o A counter-controlled loop repeats until it has run a certain number of times.
There are different kinds within each control loop.
Within the condition-controlled loop there is a WHILE and a REPEAT UNTIL loop...
Statement – single instruction or step within a program.
Subroutine – set of instructions that perform a specific task as part of a larger program.
Procedure – subroutine that executes its statements, and then returns control to the
main program.
Function – subroutine that executes its statements and returns a single value.
Parameter – an item of data that is given to a procedure / function.
Sequence – control structure in which a set of instructions is each executed once, in the
order in which they are written.
Selection – control structure in which an option of statements is provided and a
condition is used to decide which (if any) statements should be executed.
Iteration – control structure in which a group of statements is executed repeatedly (like
a loop, also called repetition).
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 6 of 21
WHILE REPEAT UNTIL
Condition is tested before each cycle. Condition is tested after each cycle.
Instructions may never be executed. Instructions will always be executed ≥ once.
In both cases, it repeats if the condition is TRUE and exits if the condition is FALSE.
By changing the conditions and/or some of the data in the program, it is possible to
convert a WHILE loop into a REPEAT UNTIL loop that performs the same function.
Infinite loops can be caused by an error in the logic of an algorithm.
They repeat endlessly when a condition in a WHILE loop can never be false.
A similar situation will occur in a REPEAT UNTIL condition if it can never be true.
Counter-controlled loops are often referred to as FOR loops.
FOR loops use a variable to determine whether instructions should be repeated.
Typically used when the number of iterations is known before entering the loop.
Nesting constructs are where there are loops within loops.
They give programmers the flexibility to write complex and
powerful algorithms.
Care must be taken as beginnings / ends cannot overlap each other.
Indenting instructions in constructs is a good way of ensuring this.
A subroutine is a portion of code within a larger program.
Also called a procedure, method, function, or routine, it performs a specific task.
When a subroutine is defined, it is given an identifier (name) and some instructions.
Two types of subroutine are procedures and functions...
The parameters of a procedure are a special kind of variable, used to refer to one of
the pieces of data provided as input to the subroutine.
These pieces of data are called arguments.
An ordered list of parameters is usually included in the definition of a subroutine.
Each time the subroutine is called, its arguments for that call can be assigned to the
corresponding parameters.
Procedure – executes its statements before returning control to the main program.
Function – executes its statements and returns a single value.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 7 of 21
Instructions are then executed using the actual values substituting parameters.
This is referred to as ‘passing parameters’ to the procedure.
Recursion is when a subroutine calls itself.
The subroutine is executed as normal until it gets to the
line where it calls itself.
o If a new subroutine is started every time the
subroutine is called, the process would go on
indefinitely.
Therefore a recursive subroutine usually has parameters.
There is also a case where based on the value of the parameters, the subroutine can
be executed and exit without needing to call itself.
This is known as the stopping condition.
o Once this has been reached, the subroutine is executed completely and then
control is passed back to the previous call that can now be executed.
Tracing the execution of a recursive call means following the execution step by step.
As you follow it, you note...
o Which lines are executed
o What happens when each line is executed
o Where recursive calls are made
This is best illustrated as an algorithmic diagram...
Comparing iterative and recursive solutions to a problem...
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 8 of 21
Iteration Recursion
Uses a loop to repeat instructions.
End condition to the loop decides when to stop looping.
Must include instructions that move a tracking variable towards the end condition.
Repeats by calling itself with simplified arguments.
Stopping condition causes subroutine to terminate without calling itself.
Simplified arguments used in the recursion eventually lead to the stopping condition.
There is only one function call – so one set of variables.
Therefore executing the iterative algorithm will use less memory.
Many function calls, each with its own distinct set of variables.
This means that it will take more memory during execution.
You need variables to keep track.
These variables usually need to be initialised before the loops start.
Need to keep track of the variables as loop progresses ∴ code can be more difficult to write / understand.
A new set of variables is automatically created on each function call.
Code is also usually simpler to understand and closer to the way a human would explain the algorithm.
Data Types and Data Structures (3.2.3) A data type is a formal description of the kind of data used in a computer program.
NUMERIC
Used to store numbers.
Stored by converting to binary.
Integer used for whole numbers. o 2 / 4 bytes
Real used for decimals. o 4 / 8 bytes
Currency = specialised numeric data.
BOOLEAN
Data that can only have two values.
Generally TRUE / FALSE.
Used to store whether a condition has been met.
Typically stored in 1 byte for ease.
CHARACTER (ALPHANUMERIC)
Stores just one character / symbol.
Typically 1 byte.
If we want to store longer text than one character, we use a string.
STRING (ALPHANUMERIC)
Each character usually takes 1 byte.
The length of a string is the number of characters stored in it.
A telephone number would be stored as a string because each digit (character) is important, not the actual value of the overall number.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 9 of 21
Data structures allow us to store more than one item of data together.
o Under one identifier (name).
Can be used to access individual items of data.
Two data structures – arrays and records.
Arrays contain several items of data.
Used to group variables of the same ‘category’.
Actual data stored in the memory is called an element of the array.
The number after the array is called the index...
VotesForCandidate(1) = 2300
The highest and lowest values of the index are the bounds.
The advantages of using an array as opposed to separate variables...
o All elements are declared in one statement.
o If number of elements changes, change bound of array in declaration.
o Array contains similar data; loops can be used to perform similar operations.
Using the VotesForCandidate array, this is an example of a one-dimensional array.
o A one-dimensional array denotes only row data.
o Multidimensional arrays denote data in the form of rows and columns.
Records can be used to store several data items under one identifier.
Individual items of data inside the record are called fields.
It helps to know the number of records in a file and the size of the records.
This allows the size of the file to be calculated.
The code below defines a student and assigns values to its records...
In a serial file, data is stored in the order in which it arrives.
Array Index Element
DIM TheStudent as Student
TheStudent.Name = “Jack Bennett”
TheStudent.Gender = “M”
TheStudent.Age = 17
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 10 of 21
New data is simply added to the end of the file.
This is known as appending the data.
To search for data you need to start from the first item.
By then searching each item in turn, you will find the record you are looking for.
You need to confirm whether the item you are searching for exists in the file.
By searching every item in the file, you can clarify that the item cannot be found.
In a sequential file, data is stored according to a key field in the data.
The key field is a field in each record that is used to
identify the record.
For example, if each student was given a Student ID a
sequential file of students would be stored in order of the
Student ID.
Adding new items into sequential files requires insertion
into existing records.
o This is usually achieved by recreating the file.
Searching for an item is similar to a serial file.
However if you reach an item with a higher ‘key value’ then you know the item
cannot be found, and there is no need to continue the search.
An indexed sequential file is a sequential file where data is arranged according to a
key field, but which also has an index that allows records to be found directly.
For example, if a program printing a register from a student file, it will access the
data sequentially. But if you want to look up the details of an individual student,
then the index is used to find the required record quickly.
Random files (not to be confused with random-access files) allow data to
be stored anywhere in a dedicated section of a disk.
A hash algorithm (calculation) is performed on a field in the record to
be stored.
o The result of this calculation then becomes the address.
As a result, records can appear randomly scattered across the disk.
Finding data is extremely quick as long as you know the key field and
hash algorithm.
o There is no need to refer to other data in the file.
As a result random files are very useful for large databases where
individual records are often looked up individually.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 11 of 21
How can we estimate the size of a file?
1. Determine the size (in bytes) of each field in the record.
2. Add the field sizes to calculate the size of one record.
3. Multiply the size of one record by the number of records in the file.
4. Add 10% to the result for additional storage needed to manage the file on disk.
o This is called an overhead.
Obviously this will give an estimate in bytes.
If necessary it can be converted into kilobytes (÷ 1024).
It can then be converted again into megabytes (÷ 1024 again).
Supposing a school has 1300 students...
The size of each field can be given by...
Field Data Type Size
Name String 20
Gender Character 1
Age Integer 2
Total size of each record is 23 bytes.
Size of 1300 records is therefore 23 × 1300 = 29,900 bytes.
Adding 10% for overheads gives us 29,900 × 1.1 = 32,890 bytes.
Dividing this by 1000 gives us an estimate of 32.9 kB.
These are the main file operations – the way they are implemented varies.
PPRREEPPAARRIINNGG TTHHEE FFIILLEE:: most languages require the program to make the operating
system aware that a file is about to be used. This is done using an OPEN command.
When the file is opened it is often necessary to specify how the file is going to be
used – this is called access mode. It protects the data in the file from being
corrupted. This is why it is good practice to open a file for as little time as necessary.
RECORD Student
Name : String
Gender : Character
Age : Integer
END RECORD
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 12 of 21
When the operation is over, the file should be closed. This releases the file so that it
can be used by another part of the program or indeed a different program.
RREEAADDIINNGG DDAATTAA FFRROOMM AA FFIILLEE:: languages provide different methods for reading data. The
simplest way is to read the data from the file one line at a time. This is useful for
searching through a serial file. In this case it is necessary to test, before reading each
line, that the end of the file has not been reached.
WWRRIITTIINNGG DDAATTAA TTOO AA FFIILLEE:: you also need to be able to write the data into a file that has
been correctly opened – this can include adding data to the end of a serial file
(appending). Inserting data into a sequential file will require all subsequent records
to be moved to make space for the data to be inserted. An alternative method is to
create a new file and copy all the records from the present file into it, inserting the
new data in the file at the correct location. The new file then replaces the old file.
This is called merging the data into the sequential file.
FFIILLEE MMAANNAAGGEEMMEENNTT:: programming languages also provide facilities for copying, moving,
updating, deleting files and finding out if a file exists.
Common Facilities of Programming Languages (3.2.4) Programs use variables that can be given different values.
Setting an actual value to a variable is known as assigning.
The assignment operator is usually the equals sign (=).
o <variable> = <expression>
Not to be confused with equality operator which also often uses ‘=’ sign.
o Hence it is often read as ‘becomes’ rather than ‘equals’.
o Some languages use a different sign (e.g. ‘:=’) – most don’t!
You cannot swap the left- and right-hand sides of the assignment operator.
o Using x = 7, swapping would give 7 = x (7 becomes x – nonsense!).
o Left-hand side therefore must be a single variable.
o Right-hand side must be an expression that equates to a single value.
Arithmetic operations are used to manipulate numeric data and produce a result.
Numbers which are manipulated are called operands.
Arithmetic operations only tell us how to manipulate the data.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 13 of 21
Unary operators only have one operand – operator written before operand.
Binary operators have two operands – operator written between two operands.
Adding, subtracting or multiplying integers will result in an integer.
When dividing however, this is not the case.
Many languages allow for a number of operators to perform divisions on integers...
Operation Symbol Meaning Examples
Ordinary (Real) division
/ Normal division operation; result is real number, even when operands are integers.
13 / 5 = 2.6
15 / 3 = 5.0
2 / 9 = 0.222...
Quotient (Integer division)
DIV
sometimes % or \
Operands are integers and result is integer part of result.
13 DIV 5 = 2
15 DIV 3 = 5
2 DIV 9 = 0
Remainder (Modulo arithmetic)
MOD Operands are integers and result is remainder part of result.
13 MOD 5 = 3
15 MOD 3 = 0
2 MOD 9 = 2
Relational operators compare data.
They produce a TRUE / FALSE result.
Also known as comparison operators.
Most common relational operators are...
The same operator symbol can have different meanings.
TAKE ‘–’ FOR EXAMPLE, IN THE EXPRESSIONS:
–m unary operator for negation n – m binary operator for subtraction
–m result is negative of value of m n – m result is value of m from value of n
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 14 of 21
Relational Operator Mathematical Equivalent Meaning = (or ==) = Equal to <> (or !=) ≠ Not equal to < < Less than > > Greater than <= ≤ Less than or equal to >= ≥ Greater than or equal to
Binary operators have two operands – operator written between two operands.
Therefore all of these operations are binary.
Boolean operators are very straightforward and logical.
The three main operators are AND, OR and NOT.
The AND operation has two operands.
o The result is TRUE if both operands are TRUE.
o Otherwise the result is FALSE.
The OR operator also has two operands.
o Result is TRUE if either of the operands is TRUE.
o Result is only FALSE if both the operands are FALSE.
The NOT operator only has one operand.
o Result is TRUE if operand is false, and vice versa.
Operations can be put together to make complex expressions.
Like BODMAS in maths, expression must be computed using operator precedence.
Unary operators – (negation), NOT
Multiplication and Division *, /, DIV, MOD
Addition and Subtraction +, –
Relational (comparison) operators <, >, <=, =>, = (equality), <>
Boolean operators AND, OR
Assignment = (assignment)
Again as with maths, parentheses (brackets) can be use to change the order.
o Items in brackets should be evaluated first.
If there’s more than one set of brackets, then they are evaluated in
turn from the innermost to the outermost.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 15 of 21
Most programs need to deal with text.
Therefore most languages provide operations that manipulate strings.
Concatenating two strings means joining them together to make one string.
Many languages use the operator ‘+’ for this operation.
Where FullName, FirstName and Surname are string variables...
FullName = FirstName + Surname
A better version would concatenate a space between FirstName and Surname...
FullName = FirstName + “ ” + Surname
Most languages have inbuilt functions to extract part of a string.
Often called LEFT, RIGHT and MID.
Which is used depends whereabouts in the string letters need to be extracted from.
FORMAT LEFT(<string>,<number of characters>)
What it does Returns the given number of characters from the left of the string.
Example LEFT(“robson”,3) returns the string “rob”
FORMAT RIGHT(<string>,<number of characters>)
What it does Returns the given number of characters from the right of the string.
Example RIGHT(“robson”,3) returns the string “son”
FORMAT MID(<string>,<starting position>,<number of characters>)
What it does Returns the given number of characters from the given starting position.
Example MID(“robson”,2,3) returns the string “obs”
Another common requirement is to search a string for another shorter string.
This generally uses LOCATE, for example, as LOCATE(<search string>,<main string>).
In this example, if the search string is found, it will return an integer.
o This integer is obviously the position within the main string.
o However if the string is not found, it typically returns the number 0.
Locating strings varies greatly between languages.
The principle however remains the same.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 16 of 21
Determining the length of a string is easy.
Most languages use LENGTH(<string>).
This will return an integer.
o For example, LENGTH(<robson>) will return 6.
Dealing with character codes ASCII and CHAR is straightforward.
o CHAR(<character code>) returns the character that has that code.
o ASCII(<character>) returns the character code of the given character.
Comparing strings generally uses alphanumeric comparison in most languages.
Codes of characters are compared in turn, starting from the first character.
o This allows you to determine which string is greater.
It can cause unexpected results in many programs.
o As strings are compared with each other.
For example, upper and lower case characters do not have the same code.
o Therefore the comparison “Kent” = “kent” would result in FALSE.
This is because such comparisons are case sensitive.
Also where strings contain digits, then “11” will be considered lower than “2”.
o This is because the first character code is lower in “11” (i.e. 1 < 2).
The SPACE character (and most common punctuation symbols)
Digits 0 to 9 in order
Uppercase letters A to Z in order
Lowercase letters a to z in order
Accented letters (such as á, ë, ñ, ô etc.)
For this reason, programmers must be aware of how strings are compared.
For example, they must replace accented characters with non-accented equivalents.
o The name Zoë would have to be replaced with Zoe.
Otherwise “Zoë” would come after other words such as “Zoo”.
:::: KKEEYY TTEERRMMSS FFOORR IINNPPUUTT // OOUUTTPPUUTT OOFF DDAATTAA
Modal – when dialogue boxes appear and prevent the user from continuing to run a
program until they have been closed.
Prettyprinting – changing text, source code etc. by changes in positioning, spacing,
colour, contrast, size and similar modifications to make the content easier for people to
view, read and understand – i.e. the beautification of lots of text.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 17 of 21
Writing Maintainable Programs (3.2.5) These are short definitions of key terms for writing maintainable programs.
Good programming techniques...
enable the programmer to focus on what the program is intended to do
make it easier to check that a program fulfils its requirements
lead to less mistakes in the coding
enable other programmers to understand each other’s codes
allow the original programmer to familiarise themselves quickly
can ultimately lead to increased productivity
Most languages insist that identifiers begin with a letter.
When declaring variables, programmer should use meaningful identifiers.
For this reason single letter identifiers should be avoided.
As spaces are not allowed, use underscores / capitalisation appropriately.
Use prefixes at the start of identifier names to remind you of the data type.
When declaring variables / constants, programmer must be aware of scope.
o Local variables are declared and used inside a module / subroutine.
o Global variables are declared at beginning of the code; available throughout.
Using local variables as far as possible = good programming style.
Some programming languages will initialise variables (when they are declared).
o This basically means that the variables are given a starting value.
Generally integers are set to 0, Booleans are set to FALSE and strings are empty.
Constants can make code easier to read and maintain.
Variable – facility for storing data which can be referenced by identifiers. The current
value of the variable is the data actually stored in the variable.
Constant – a special kind of variable whose fixed value cannot be altered by the
program during execution.
Identifier – the name for a variable or constant.
Reserved Word – words already used in the language for a specific purpose, generally
functions and operations that are inbuilt.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 18 of 21
Many programs contain values that do not change while the program is running.
These may be universal constants that are always the same.
New programmers tend to use literals in their code for such values.
o This means that the code contains the actual values spelt out in full.
As a general rule literals should be avoided in code.
They should be substituted with constants unless there is good reason not to.
Modularised code makes the program easier to understand.
Code should be written as a series of small routines.
Complex operations should be broken into subroutines (defined separately).
Modularisation is easier to achieve if top-down techniques have been utilised.
Most languages allow comments to be inserted.
These are read by the programmer, and ignored by the computer.
Comments are vital to making the code understandable.
They should be written as the code is, not after.
o Subroutines should have comments explaining what it does.
o Variables and constants should have their purpose explained.
o Code itself should use inline comments explaining stages of the algorithm.
Comments shouldn’t however simply repeat the code.
They must not clutter the program and potentially add confusion.
Indentation Every time a code structured is used which has a beginning and an end statement on separate lines, the code within the structure should be given a new level of indentation.
Formatting As well as the vertical white spaces created by indentation, the code should be grouped into logical blocks that perform parts of the main task by entering blank lines between them.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 19 of 21
Testing and Running a Solution (3.2.6) Programmers can make three types of error while writing a program.
Categories of errors are syntax error, logic error and runtime error.
Test strategies specify what type of testing should be carried out at each stage.
Occurs when a statement has been written in the program that breaks the rules of the language. As it cannot be understood, it is not executed.
For example, missing punctuation, using unrecognised identifiers, not using enough arguments for functions etc.
Occurs because there is a mistake in the algorithm that results in the program doing something other than what it was intended to do.
For example, instructions in wrong order, or incorrect conditions for IF statements.
Occurs due to an unexpected situation with the data being processed or another external factor. Program would otherwise work under normal operating conditions.
For example, (stack) overflow errors, or library errors.
BLACK BOX TESTING
Only concerned with inputs / outputs; not with how program works.
Tests whether inputs produce expected outputs.
Ideally you would test every possible input to the program – but impossible!
Therefore necessary to group similar inputs and test representative value.
If test successful, we assume all other values in that group have been tested.
VALID (NORMAL) DATA – data which you would normally expect the user to input. INVALID DATA – data which should generate an error message. BORDERLINE DATA – must be careful to test data at boundaries.
WHITE BOX TESTING
Tests the algorithm in the code to check all works as intended.
Focus on identifying and testing every possible route / path.
On each test run, path of execution is noted so it can be compared.
Path consists of numbers of lines of code that are executed.
Path determined by values of the conditions in constructs.
Therefore useful to also note whether the condition was TRUE or FALSE.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 20 of 21
Alpha and beta testing are different to black and white box testing.
Carried out when software is nearly complete and is being tested as a whole.
Applies especially to commercial software: developed for external end user.
Acceptance testing is different once again.
It is designed to demonstrate to the end user that the software works correctly.
It shows that all desired features have been implemented.
Takes place after all other development and testing is complete.
Software is tested against requirements agreed between developers and end user.
Debugging tools provide facilities for finding and removing bugs (faults) in software.
Most obvious is translator diagnostics.
o Messages generated by translator while it translates source into object code.
Useful for finding out where there are syntax errors.
Often include warnings where there might be a logic error.
To find a logic error, it is useful to use breakpoints and stepping.
o Breakpoints are markers added to a line of code requesting that the program
stops running when it gets there – useful for carrying out variable checks.
o At this point the programmer can make the program run one instruction or
step at a time – this is called stepping.
ALPHA TESTING
Takes place within the company producing the software.
Employees test the program as though they were potential users.
At this stage, software is not complete and there will be several bugs.
Restricting number of people allows swift replacement with updated versions.
BETA TESTING
Takes place after alpha testing.
Software is now very similar to the final product.
Released to potential users outside the company.
Testing takes place in actual conditions software will be used in.
Useful as end users may find bugs the company had not anticipated.
Beta testers also report constructive comments about features of program.
Programming Techniques and Logical Methods
OCR F452 Written Exam (May 2010)
:: Jack Bennett, 12F
Page 21 of 21
Dry runs are executing a program by hand.
You write in the values of variables and other runtime data on paper.
This checks its operation and can track down bugs.
It is often carried out using a trace table.
o Gives systematic way of recording what happens when
sections of code are executed.
o It has a column for...
Line of code being executed
Every variable used
Recording any values that are output
It’s necessary to ensure that the finished program will run smoothly for the end user.
This is called installing the program on the end user’s computer.
Executable files (.exe) are often the best way of installing a program.
If they are not available, the source code and translator program must be copied.
o From the programmer’s computer to the end user’s computer.
Sometimes having just the executable code is not enough to allow.
The end user may not be able to run the program.
In this case, we need an installation routine.
This is a program that will automate the installation process.
The installation routine is generally delivered with the software.
The sorts of functions carried out by the routine are...
o Copying the executable program to the correct folder.
o Preparing any data files that are needed by the program.
o Copying any library files that the program uses.
o Making the program easy to access (icons, shortcuts etc.).
o Initially configuring user preference settings (colour scheme etc.).
Some languages provide facilities for creating installation routines.