Vous êtes sur la page 1sur 85

A Level.

Computing (9691/2)

www.revision-notes.co.cc

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

2.1 DESIGNING SOLUTIONS TO PROBLEMS


Candidates should be able to: 1. 2. Discuss the importance of good interface design; Design and document data capture forms, screen layouts, report layouts or other forms of input and output (eg sound) for a given problem.

Purpose of a human-computer interface


A human-computer interface must allow effective and efficient communication between the computer and the human user. Humans need to communicate with computers to: give instructions Print, Save, Open, Delete, Copy, Paste etc. enter information file names, number of pages to print; make choices Yes, No, Cancel etc.. Computers need to communicate with humans to: inform of errors illegal operation, printer out of paper, wrong password; tell on progress copying, deleting, installing, downloading; display the results of processing ask for options eg number of pages to be printed, which file to open. provide help with performing tasks this help could be in the form of status bar text, yellow Tip boxes, an Office Assistant or even a full-blown help file accessed via the Help menu. Failure to create an interface that allows effective dialogue would mean that: only the highly trained would be able to use the system and even they may need some training; the number of errors would increase if there is no feedback to tell the user that the correct instruction was being carried out (or had been carried out); working on such a system would usually be very slow.

ADDITIONAL NOTES:

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Good interface design


A good interface is needed to make it easier for the end-user. It will allow them to: learn to use the system quickly; enter data quickly; enter data without errors. A good interface is also needed to ensure that the output is clear and understandable. Learn to use the system quickly A good interface will have a layout with which is familiar to the user. It will use familiar controls (input boxes, buttons, etc.) and place these controls in familiar places. There will be consistency between the different screens. Enter data quickly To help the user to enter data quickly, the interface will contain. Some of these will have the predicted response set as a default value. Enter data without errors Accurate data entry can be helped by the use of drop-down lists, option buttons and check-boxes. Dialogue boxes can also be used to alert the user to validation errors.

ADDITIONAL NOTES:

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Considerations when designing an interface


A user interface must match both the abilities and the needs of the intended users. It must take into account: the potential user expert/novice, young child/older adult, specialist professional/general public; partially sighted or physically disabled. For example, a novice user should be provided with command buttons that are large enough to select easily; an expert user should be provided with keyboard short-cuts in order to select commands quickly and without having to take her hands from the keyboard. A young childs interface should be bright and possibly include pictures within command buttons particularly for the pre-reading age group; a specialist professional such as a graphics design artist may need a graphics tablet and a very high resolution VDU. It is also appropriate to vary the input and output devices according to the potential users concept keyboards for children; speakers for the visually impaired; microphones for voice recognition if another form of input is not possible. tasks to be performed are they repetitive, do they require special skills, are the tasks similar or different. Note that an office worker who regularly switches between word processing and spreadsheets will probably require a Windows like interface while a travel agent who only uses the computer to book holidays will require an interface consisting of forms and dialogues. environment if the computing device will be used in a noisy atmosphere then a natural language recognition interface is useless. If the environment is dirty, such as in a car repair shop, then an interface that requires the use of a mouse cannot be used. available technology interfaces change as technology develops. Only the most recently developed interfaces are able to make use of natural language recognition or touch screens.

Interface design tips


Interface windows and dialogues should be given meaningful titles to identify them: labels, text boxes, buttons etc should be appropriately laid out not too cluttered, nor too spaced. The type and format of data entry should be indicated for each text box; items should be arranged in a logical sequence; colours should be used very carefully each colour should be used for a specific reason and not just because the designer likes it; default values should be used within text boxes, combos, option-groups and check-boxes; on-screen help facilities should be provided where necessary; the user should be able to correct/confirm entries before final submission (e.g. use confirmation prompts such as Yes/No buttons). error messages should be clear they should inform the user of the error and tell them how to proceed.

ADDITIONAL NOTES:

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Designing forms for input and output


A typical question for this section may be:
An electronic general knowledge game displays, on the screen, the following: a question four possible answers a clock to allow a set amount of time to answer the question a score (which is added to if the question is answered correctly) the score required in order to win the game. The player touches the answer that they want to input as their choice.

You will be expected to use good interface design techniques and draw the interface. For example:

Note that the context of this question implies a full-screen video game if the interface was not fullscreen, then a title to the window would be expected.

ADDITIONAL NOTES:

10

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Data requirements
Candidates should be able to: 3. Determine the data requirements of a program (relating to 3.2.3: Data types and data structures).

This is a skills section in which you may need to state the details of data that a program will use. For each data item you will need to include the following details: The identifier name of the variables (or fields) that will hold the data; The data type; The size of the data; The validation that needs to be carried out on the data.

A possible question may be:


A gaming system stores the 100 highest scores. Describe the fields that will be necessary in terms of their name, data type and size.

Solution:
Field name Name Score Date Data type String Integer Date Size of field (bytes) 15 2 8

Note that in the context of this question, it is a game name that is required and so 15 bytes is sufficient if the players full name (first and last) was required then 25 or more bytes would probably be needed.

ADDITIONAL NOTES:

DJM

11

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Sub-dividing a problem
Candidates should be able to: 4. Explain the advantages of designing a solution to a problem by splitting it up into smaller problems (top-down/modular design); Produce and describe top-down/modular designs using appropriate techniques including structure diagrams, showing stepwise refinement.

5.

Top down/modular design


Top-down design is when a problem is split into smaller sub-problems, which themselves are split into even smaller sub-problems until each is just one element of the final program. Benefits and drawbacks of modular programs
Benefits Smaller problems are easier to understand Drawbacks Modules must be linked and additional testing must be carried out to make sure that the links work correctly Programmers must ensure that crossreferencing is done Interfaces between modules must be planned

Smaller problems are easier to test and debug

Development can be shared between a team of programmers each person programming different modules according to their individual strengths. Code from previously developed modules can be re-used

ADDITIONAL NOTES:

12

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Structure diagrams
A structure diagram is a pictorial representation of a modular system.

Stepwise refinement
Stepwise refinement is the process of developing a modular design by splitting a problem into smaller sub-tasks, which themselves are repeatedly split into even smaller sub-tasks until each is just one element of the final program

ADDITIONAL NOTES:

DJM

13

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Algorithms
Candidates should be able to: 6. 7. 8. Produce algorithms to solve problems; Describe the steps of an algorithm using a program flowchart; Describe the steps of an algorithm using pseudo-code.

Algorithm
An algorithm is a sequence of steps, which perform a specific task. In computing, algorithms are usually represented as a program flowchart, or in pseudo-code.

Program flowchart
A program flowchart is a pictorial representation of an algorithm. Program flowcharts use special symbols:

Start/stop symbol

Process symbol

Input/output symbol

Decision symbol

ADDITIONAL NOTES:

14

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods Flowchart to output the first five square numbers

ADDITIONAL NOTES:

DJM

15

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Pseudo-code
Pseudo-code is a simplified form of programming code that uses common programming keywords, but does not use the strict syntax rules of a programming language. An example of a pseudo-code algorithm:
BEGIN INPUT CardNumber REPEAT INPUT PIN IF PIN is wrong for this CardNumber THEN OUTPUT Wrong Pin END IF UNTIL Pin is correct INPUT Amount IF there are enough funds THEN Dispense Cash Update customers balance ELSE OUTPUT Sorry, insufficient funds END IF END

ADDITIONAL NOTES:

16

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Evaluating algorithms
Candidates should be able to: 9. Understand, and implement algorithms and evaluate them by commenting on their efficiency, correctness and appropriateness for the problem to be solved.

Algorithms should be evaluated using the following criteria: Efficiency Correctness Appropriateness

Efficiency
An algorithms efficiency can be judged in terms of: speed how quick the algorithm produces the required output; memory requirements how many lines of code the algorithm contains.

Correctness
Although an algorithm is expected to produce the correct outputs, correctness can still be measured in terms of: accuracy how many decimal places Produce output with greater accuracy e.g. more decimal places; range will the algorithm work with the complete range of inputs, or can it only deal with positive numbers, whole numbers, numbers below 1 million, etc. reliability will the algorithm always produce correct output within the range that it is designed to work, or are there values which it will not accept (zero, for example).

Appropriateness
Appropriateness can be measured in terms of: length if the problem is simple then a short algorithm would normally be expected; speed if the output needs to be generated quickly, then the algorithm must be able to complete quickly; memory requirements an algorithm controlling a washing machine must not have the need for a lot of memory!

ADDITIONAL NOTES:

DJM

17

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Rapid Application Development


Candidates should be able to: 10. Describe the use of Rapid Application Development (RAD) as a design strategy, including prototyping and iterative development, and state its advantages and disadvantages. Rapid Application Development (RAD) is a method of designing and writing software by repeatedly producing prototypes, which are evaluated by the end-user and repeatedly refined until the final version is finished. RAD is an example of iterative development. During the RAD process: the prototypes are tested and evaluated by the end-user; the outcome of this evaluation is used in the development of the next prototype; this evaluation and development of successive prototypes is repeated until the finished software is produced. RAD usually uses CASE tools (Computer Aided Software Engineering). This allows prototypes with reduced functionality to be produced quickly each prototype should be produced within two or three weeks.
Advantages The end-user can see a working prototype sooner than in the Systems Life Cycle approach. Disadvantages RAD focuses on the end result rather than on the processing - this means that the final solution is likely to be inefficient in the way that it uses the available resources (e.g. memory and processor time). RAD is not time-efficient when developing large scale applications the initial prototypes are likely to be so different to the final product that a lot of rethinking in necessary between prototype versions.

The user is involved with the design and can influence the direction the software is taking (e.g. what changes need to be made; what key features need to be included in the next prototype). The overall development time is usually shorter and so costs are reduced.

ADDITIONAL NOTES:

18

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

2.2 THE STRUCTURE OF PROCEDURAL PROGRAMS


Candidates should be able to: 11. Define and correctly use the following terms as they apply to procedural programming: statement, subroutine, procedure, function, parameter/argument, sequence, selection, iteration/repetition, loop; 12. Identify the three basic programming constructs used to control the flow of execution, i.e. sequence, selection and iteration. Procedural programs are ones in which instructions are executed in the order defined by the programmer. Procedural languages are often referred to as third generation languages and include FORTRAN, ALGOL, COBOL, BASIC, and PASCAL.

Statement
A statement is a single instruction in a program, which can be converted into machine code and executed. In most languages a statement is written on a single line, but some languages allow multiple lines for single statements. Examples of statements are:
DIM name As String A=X*X While x < 10

ADDITIONAL NOTES:

DJM

19

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Subroutine
A subroutine is a self-contained section of program code that performs a specific task, as part of the main program. Procedure A procedure is a subroutine that performs a specific task without returning a value to the part of the program from which it was called. Function A function is a subroutine that performs a specific task and returns a value to the part of the program from which it was called. Note that a function is called by writing it on the right hand side of an assignment statement. Parameter (argument) A parameter is a value that is passed (given) to a subroutine (procedure or function). The subroutine uses the value of the parameter within its execution. The action of the subroutine will be different depending upon the parameters that it is passed. Parameters are placed in parenthesis after the subroutine name. For example:
Square(5) Square(8) Square(x) CalculateVolume(7,14,8) passes the parameter 5 returns 25 passes the parameter 8 returns 64 passes the value of the variable x three parameters are passed

ADDITIONAL NOTES:

20

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Control structures
Computer programs execute statements one line after the next, unless there is a command that instructs the program to jump backwards or forwards to an alternative line. Sequence Sequence is when the programming statements are executed one after the other, in the order in which they appear in the program. Selection Selection is a control structure in which there is a test to decide if certain instructions are executed.
If x < 10 then Do this line And this line Else Do this line End if

Iteration Iteration is a control structure in which a group of statements is executed repeatedly either a set number of times, or until a specific condition is True.
Repeat Do this line And this line Until n=5

ADDITIONAL NOTES:

DJM

21

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Flowcharts showing the control structures


Sequence Selection Iteration

ADDITIONAL NOTES:

22

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Selection
Candidates should be able to: 13. Understand and use selection in pseudo-code and a procedural programming language, including the use of IF statements and CASE/SELECT statements.

IF-THEN-ELSE
This selection method is used if there are two possible outcomes to a test:
IF x < 0 THEN OUTPUT Sorry, you cant have negative values ELSE a = x*x OUTPUT a END

SELECT-CASE
This selection method is used if there are more than two possible outcomes to a test:
SELECT CASE KeyPress CASE LeftArrow Move one character CASE RightArrow Move one character CASE UpArrow Move one character CASE DownArrow Move one character END SELECT

backwards forwards up down

ADDITIONAL NOTES:

DJM

23

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Iteration
Candidates should be able to: 14. Understand and use iteration in pseudo-code and a procedural programming language, including the use of count-controlled loops (FOR-NEXT loops) and condition-controlled loops (WHILE-ENDWHILE and REPEAT-UNTIL loops).

FOR-NEXT
This is an unconditional loop in which the number of repetitions is set at the beginning.
FOR X = 1 TO 5 Answer = X*3 OUTPUT X, Answer NEXT

WHILE-ENDWHILE
This is a conditional loop, which has a test at the start and repeats until the condition is false:
X = 0 WHILE X < 6 DO X = X + 1 Answer = X*3 OUTPUT X, Answer END

REPEAT-UNTIL
This is a conditional loop, which has a test at the end and repeats until the condition is true:
X = 0 REPEAT X = X + 1 Answer = X*3 OUTPUT X, Answer UNTIL X > 4

ADDITIONAL NOTES:

24

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Comparison of the different iterations


FOR-NEXT An unconditional loop it will repeat itself a set number of times. WHILE-WEND A conditional loop it will repeat until a variable has reached a stated value. The condition is tested at the start of the loop. Iteration statements will always execute at least once.
For x= 1 To 10 a=x*5 Output x, a Next x

REPEAT-UNTIL A conditional loop it will repeat until a variable has reached a stated value. The condition is tested at the end of the loop. Iteration statements will always execute at least once.
x=1 Repeat a=x*5 Output x, a x=x+1 Until x > 10

Iteration statements may not actually be executed.


x=1 While x < 11 a=x*5 Output x, a x=x+1 End While

ADDITIONAL NOTES:

DJM

25

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Nested selection and iteration


Candidates should be able to: 15. Understand and use nested selection and iteration statements.

Nested selection
This is where there is an IF statement contained within an IF statement. The following algorithm allows a maximum of four attempts to login to a computer system:
INPUT Password IF NumberOfTries < 5 THEN IF Password is correct THEN OUTPUT Successful Login ELSE OUTPUT Password was incorrect END ELSE OUTPUT You have made too many attempts END

Nested iteration
This is where there is a loop within a loop. A nested iteration is needed to initialise a two-dimensional array:
FOR row = 0 TO 7 FOR column = 0 TO 5 SET MyArray (row, column) = 0 NEXT column NEXT row

ADDITIONAL NOTES:

26

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Subroutines
Candidates should be able to: 16. Understand, create and use subroutines (procedures and functions), including the passing of parameters and the appropriate use of the return value of functions.

Subroutine/sub-program
A subroutine is a self-contained section of program code which performs a specific task and is referenced by a name. A subroutine resembles a standard program in that it will contain its own local variables, data types, labels and constant declarations. There are two types of subroutine. These are procedures and functions. procedures are subroutines that input, output or manipulate data in some way; functions are subroutines that return a value to the main program. A subroutine is executed whenever its name is encountered in the executable part of the main program. The execution of a subroutine by referencing its name in the main program is termed calling the subroutine. The advantages of subroutines. The advantage of using procedures and functions are that: the same lines of code are re-used whenever they are needed they do not have to be repeated in different sections of the program. a procedure or function can be tested/improved/rewritten independently of other procedures or functions. it is easy to share procedures and functions with other programs they can be incorporated into library files which are then linked to the main program; a programmer can create their own routines that can be called in the same way as any built-in command.

ADDITIONAL NOTES:

DJM

27

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Recursion
Candidates should be able to: 17. Identify and use recursion to solve problems; show an understanding of the structure of a recursive subroutine, including the necessity of a stopping condition; 18. Trace the execution of a recursive subroutine including calls to itself; 19. Discuss the relative merits of iterative and recursive solutions to the same problem. Recursion is when a function or a procedure contains a call to itself. Recursion is used when calculating factorials:
FUNCTION Factorial(n) IF n = 1 THEN RETURN 1 ELSE RETURN n * Factorial(n 1) END IF END

Note that a recursive function needs a stopping condition i.e. a statement that will stop it from repeating infinitely. In the Factorial function above the stopping condition is IF n = 1.

ADDITIONAL NOTES:

28

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods Tracing the execution of x = Factorial(3)
01 FUNCTION Factorial(n) 02 IF n = 1 THEN 03 RETURN 1 04 ELSE 05 RETURN n * Factorial(n 1) 06 END IF 07 END

Note that in the above algorithm, the recursion happens on line 05.

Line Number 01 02 05 01 02 05 01 02 03 07 05 07 05 07

Function Call Factorial(3)

Returned Value

Condition

State of Function Call

False 3 * Factorial(2) Factorial(2) False 2 * Factorial(1) Factorial(1) True 1 n=1: Completed 2*1=2 3*2=6 n=2: Resumed n=2: Completed n=3: Resumed n=3: Completed New Call: n=1 n=2: Postponed New Call: n=2 n=3: Postponed

ADDITIONAL NOTES:

DJM

29

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Iteration compared to recursion


Iteration
01 02 03 04 05 06 07 INPUT n a=1 FOR i=1 TO n a=a*n NEXT i OUTPUT a END

Recursion
01 FUNCTION Factorial(n) 02 IF n=1 THEN 03 RETURN 1 04 ELSE 05 RETURN n*Factorial(n1) 06 END IF 07 END

There is only one set of variable values that are used within the iteration.

A recursive subroutine is called repeatedly and each call has its own set of variables that are distinct from the variables in the other function calls.

Iteration requires less memory than recursion because it only uses one set of variable values. Iteration variables may need to be initialised and the value of the tracking variable may need to be tested for each iteration. There needs to be a stopping condition that causes the subroutine to stop without calling itself. Recursive subroutines are often more elegant and easier to understand than the equivalent iterations.

ADDITIONAL NOTES:

30

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

2.3 DATA TYPES AND DATA STRUCTURES


Data types
Candidates should be able to: 20. Define different data types, e.g. numeric (integer, real), Boolean, character and string; select and use them appropriately in their solutions to problems. A data type is a method of interpreting a pattern of bits.

Intrinsic data types


Intrinsic data types are the data types that are defined within a particular programming language. There are numerous different data types. They are used to make the storage and processing of data easier and more efficient. Different databases and programming systems have there own set of intrinsic data types, but the main ones are: Integer; Real; Boolean; String; Character; Date; Container. Integer An integer is a positive or negative number that does not contain a fractional part. Integers are held in pure binary for processing and storage. Note that some programming languages differentiate between short and long integers (more bytes being used to store long integers). In REALbasic an integer uses 4 bytes of memory this allows it to take a whole number value between 2, 147, 483, 648.

ADDITIONAL NOTES:

DJM

31

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Real A real is a number that contains a decimal point. In many systems, real numbers are referred to as singles and doubles, depending upon the number of bytes in which they are stored. In REALbasic, a single uses 4 bytes of memory and can have a value between 1.175494 e-38 and 3.402823 e+38; a double uses 8 bytes of memory and can have a value between 2.2250738585072013 e-308 and 1.7976931348623157 e+308. r. Boolean A boolean is a data-type that can store one of only two values usually these values are True or False. Booleans are stored in one byte True being stored as 11111111 and False as 00000000. Many of the properties of objects (windows, text-boxes, buttons etc.) in REALbasic have Boolean values e.g. the visibility of an object will be set to either True (visible) or false (Hidden). These values are often set using check-boxes. String A string is a series of alphanumeric characters enclosed in quotation marks. A string is sometimes just referred to as text. Any type of alphabetic or numeric data can be stored as a string: Birmingham City, 3/10/03 and 36.85 are all examples of strings. Each character within a string will be stored in one byte using its ASCII code; modern systems might store each character in two bytes using its Unicode. The maximum length of a string is limited only by the available memory. Notes: if dates or numbers are stored as strings then they will not be sorted correctly; they will be sorted according to the ASCII codes of the characters 23 will be placed before 9; telephone numbers must be stored as strings or the leading zero will be lost.

ADDITIONAL NOTES:

32

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Character A character is any letter, number, punctuation mark or space, which takes up a single unit of storage (usually a byte). Dates In most computer systems dates are stored as a serial number that equates to the number of seconds since January 1st, 1904 (thus they also contain the time). Although the serial numbers are used for processing purposes, the results are usually presented in one of several standard date formats for example, dd/mm/yyyy, or dd MonthName, yyyy. Dates usually take 8 bytes of storage. Container A container is a data-type used for storing images, video, sound or another type of complex file. Note that in MySQL databases the term blob (binary large object) is used rather than container Comparison of the common data types
Data Type Integer Real Boolean String Example value 42 23.1 True Hello World Storage Required 4 bytes 4 or 8 bytes 1 byte 1 byte for each character (if using Unicode, then 2 bytes are required for each character) 1 byte 8 bytes Lots!

Character Date Container

X 12/11/2009 Image, video or sound

ADDITIONAL NOTES:

DJM

33

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

User-defined data types


At times it is useful for programmers to be able to define their own data types. In such cases it is common for these user-defined data types to contain items from several of the different intrinsic types mentioned above.

Some programming languages allow the programmer to do this by defining Records.

Benefits of defined data-types


Whether intrinsic or user-defined, the use of data-types within a programming language: enable the compiler to reserve the correct amount of memory for the data e.g. 4 bytes for an integer; trap errors that a programmer has made and errors that a user of a program can make a variable defined as an integer cannot be given a fractional value; restrict the values that can be given to the data a Boolean cannot be given the value maybe; restrict the operations that can be performed on the data a string cannot be divided by 10.

ADDITIONAL NOTES:

34

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Data structures
Candidates should be able to: 21. Define and use arrays (one- and two-dimensional) for solving simple problems, including initialising arrays, reading data into arrays and performing a simple serial search on a onedimensional array. A data structure is a collection of different data items that are stored together in a clearly defined way. Two common data structures are arrays and records.

Array
An array is a data structure, which allows a set of items of identical data type to be stored together using the same identifier name. Arrays are declared in a similar way to standard variables, except that the array size and dimensions are included. For example, the following declares an array that reserves five locations in memory and labels these as Names:
DIM Names(4) As String

The five individual locations are Names(0), Names(1), Names(2), Names(3), Names(4). Each data item is called an element of the array. To reference a particular element a programmer must use the appropriate index. For example, the following statement assigns data to the 5th element:
Names(4) = Johal

Arrays simplify the processing of similar data. An algorithm for getting five names from the user and storing them in the array Names is shown below:
Dim Names(4) As String For i=0 to 4 Input Value Names(i)=Value Next i

ADDITIONAL NOTES:

DJM

35

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

One-dimensional arrays A one-dimensional array is a data structure in which the array is declared using a single index and can be visually represented as a list. The following diagram shows the visual representation of the array Names(4):

Two-dimensional arrays A two-dimensional array is a data structure in which the array is declared using two indices and can be visually represented as a table. The following diagram shows the visual representation of an array Students(4,2):

Each individual element can be referenced by its row and column indices. For example:
Students(0,0) is the data item JONES Students(2,1) is the item M Students(1,2) is the item LAMBOURNE

ADDITIONAL NOTES:

36

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Initialising an array Initialising an array is a procedure in which every value in the array is set with starter values this starting value would typically be for a string array, or 0 for a numeric array. Initialisation needs to be done to ensure that the array does not contain results from a previous use, elsewhere in the program. Algorithm for initialising a one-dimensional numeric array:
DIM TestScores(9) As Integer DIM Index As Integer FOR Index = 0 TO 9 TestScores(Index) = 0 NEXT

Algorithm for initialising a two-dimensional string array:


DIM Students(4,2) As String DIM RowIndex, ColumnIndex As Integer FOR RowIndex = 0 TO 4 FOR ColumnIndex = 0 TO 2 Students(RowIndex,ColumnIndex) = NEXT NEXT

ADDITIONAL NOTES:

DJM

37

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Serial search on an array The following pseudo-code can be used to search an array to see if an item X exists:
01 02 03 04 05 06 07 08 09 10 11 12 DIM Index As Integer DIM Flag As Boolean Index = 0 Flag = False Input X REPEAT IF TheArray(Index) = X THEN Output Index Flag = True END IF Index = Index + 1 UNTIL Flag = True OR Index > Maximum Size Of TheArray

Note that the variable Flag (line 04 and 09) is used to indicate when the item has been found and stop the loop repeating unnecessarily (line 12 ends the loop if Flag has been set to True). To complete the search algorithm some lines should be added, after the loop, to detect the times when the item X was not found in the array:
13 IF Flag = False THEN 14 Show Message Item not found 15 END IF

ADDITIONAL NOTES:

38

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Using an array with differing data types If an array is to be used to store data of different data types, then: 1. The different data must be defined within a Record:
RECORD Student Name: String Gender: Character Age: Integer END RECORD

2.

The array may now be declared to contain items of data type Record:
DIM MyArray(6) As Record

3.

Each record can now be stored as a single item within the array.

ADDITIONAL NOTES:

DJM

39

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Relative advantages of the different data types


Candidates should be able to: 22. Explain the advantages and disadvantages of different data types and data structures for solving a given problem. COMMENTS TO BE ADDED HERE

ADDITIONAL NOTES:

40

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Records
Candidates should be able to: 23. Design and implement a record format.

Key terms
The following terms are used to describe parts of a database:

Field A field is a single category of data within a database, which appears in all the records of a table it is a column within a table. Record A record is a collection of fields that contains data about a single item or person it is a row within a table. Table A table is a collection of related records.

ADDITIONAL NOTES:

DJM

41

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Key fields
A key field is used to identify the records within a database. There are two types of keys: primary key; secondary key. Primary key The Primary key is a unique field that identifies a single record. Some natural primary keys are: CarRegistrationNumber; ISBN a 10-digit code that uniquely identifies a book; MAC number a 6-part number that uniquely identifies a network card NationalInsuranceNumber can uniquely identify employees of a company (not usable for under 16s or for non-British nationalists!)

Secondary key A Secondary key is a non-unique field, used in a search, that does not always produce only one matching record. Some typical secondary keys are: LastName; PostCode; DateOfBirth

ADDITIONAL NOTES:

42

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Modes of file access


Candidates should be able to: 24. Define different modes of file access: serial, sequential, indexed sequential and random; and justify a suitable mode of file access for a given example.

Serial file
A serial file is one in which records are stored, one after the other, in the order in which they are added not in order of a key field. This means that new records are stored at the end of the file. The following shows a serial file that is used to store the number of entries for EdExcel GCSE Mathematics. The entries were received in the order: Kettlewood, Queens Park, St Marys, Wilton High, West Orling.
Centre Number 27102 38240 64715 30446 12304 Centre Name Kettlewood Queens Park St Marys Wilton High West Orling No of Candidates 85 103 121 156 105

Note that the key field in this file would be Centre Number (it uniquely identifies each school) Both disks and tapes can be used to store a file serially.

ADDITIONAL NOTES:

DJM

43

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Sequential file
A sequential file is one in which the records are stored, one after the other, in the order of the key field. The following shows a sequential file that is used to store the number of entries for EdExcel GCSE Mathematics. The entries were added in the order: Kettlewood, Queens Park, St Marys, Wilton High, West Orling but they are stored in the order of the key field Centre Number:
Centre Number 12304 27102 30446 38240 64715 Centre Name West Orling Kettlewood Wilton High Queens Park St Marys No of Candidates 105 85 156 103 121

As with a serial file, both tape and disks can be used to store a file sequentially and access to the records must take place from the beginning of the file. Benefits Sequential files allow the records to be displayed in the order of the key field this makes the process of adding a record slower, but significantly speeds up searches.

ADDITIONAL NOTES:

44

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Indexed sequential file


An indexed sequential file is one in which the records are stored, one after the other, in the order of the key field, but which also has an index that enables records to be accessed directly. Index An index is a file with two fields, created from the main file, which contains a list of: the key fields (sorted sequentially); pointers to where the records can be found in the main file. Indexed sequential files are useful when: it is sometimes necessary to process all the records in sequential order; and it is sometimes necessary to access individual records randomly.

Examples of indexed sequential files Company employee file At the end of each month all the records will be processed sequentially, in order to produce payslips. However, some records will need to be accessed randomly, at other times for example, when an employee changes address. A schools student file When an attendance report is printed, the file will be accessed sequentially, but when the details of an individual student are required the index will be used to find the required record quickly.

ADDITIONAL NOTES:

DJM

45

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Random (direct) access file


A random access file is one in which a record can be written or retrieved without first examining other records. A random access file must be stored on disk and the disk address is calculated from the primary key. In its simplest form a record with a primary key of 1 will be stored at block 1, a record with a primary key of 2 will be stored at block 2; a record with primary key 3 will be stored at block 3 etc:

It should be noted that this very simple method where [disk address] = [primary key] is very inefficient in respect of disk space. For example: if the lowest primary key is 1001, then all the disk space below block 1001 will be wasted. If there are some values which the primary key never takes (for example odd values) these storage spaces will be wasted.

In order to be more efficient with the use of disk space, random access files calculate disk addresses by using a hashing algorithm (also known as just hashing).

ADDITIONAL NOTES:

46

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Hashing
Hashing is a calculation that is performed on a primary key in order to calculate the storage address of a record. A hashing algorithm will typically divide the primary key by the number of disk blocks that are available for storage, work out the remainder and add the start address. The answer will be the storage address of the record. [disk address] = [primary key] MOD [number of blocks] + [start address] Example If a file was to be stored on the first 5000 blocks of a disk then: [disk address] = [primary key] MOD 5000 That is, the primary key of each of the records would be divided by 5000 and the remainder would be the disk address for the record. This means that a record with primary key of 27102 would be stored at the disk address calculated as follows:
27102 = 5 remainder 2102 5000

This means that the disk address for this record will be 2102.
The table shows some other disk addresses calculated using the same hashing algorithm:
Centre Number 27102 38240 64715 30446 12304 Centre Name Kettlewood Queens Park St Marys Wilton High West Orling No of Candidates 85 103 121 156 105 Disk Address 2102 3240 4715 446 2304

ADDITIONAL NOTES:

DJM

47

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Problems with hashing One problem that could occur with hashing is that a block may already contain a record and be full. For example records with key fields of 38240 and 43240 will both be assigned a disk address of 3240. If this happens then the new record will need be written somewhere else. Two common ways of determining this alternative location are: the record can be written to the next available block note that if it is the last address block which is full then the search for an available space will start from the first block. the record could be written to a separate overflow area and a tag is placed in the calculated location to indicate exactly where in this overflow area the record can be found.

ADDITIONAL NOTES:

48

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Exercise CPT2.2B
1. (a) (b) 2. What is meant by a serially organised file? [2] State two characteristics of a sequentially organised file. [2]

Details of each new loan in a library can only be added to the end of the loans file. What type of file organisation does the loans file use? [1] If a program is written which searches a sequential file for a match with a given word that might be recorded in the file, what are the steps for this process? [4] (a) (b) What file organisation is required if the priority is to find a specific record in a file? Justify your answer. [2] What file organisation is required if the priority is to access individual records quickly? Justify your answer. [2]

3.

4.

5. 6. 7.

List the steps required in order to add a record to a sequential file. [4] What is a direct access medium? [2] (a) (b) (c) What is meant by hashing? [2] Give two properties that a hashing algorithm should have. [2] A hashing algorithm uses the expression (ASCII Code)Mod 150. Why is Mod 150 used? [1]

ADDITIONAL NOTES:

DJM

49

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

8.

(a) (b)

What are the major steps that a typical hashing function/algorithm would use to convert a alphanumeric string into a two-byte integer. [2] Why is the hashing function used for passwords on a LAN, a one-way (irreversible) function? [1]

9.

List the programming steps required to generate a direct access file by using a hashing algorithm on a sequential file. Note that details of how a hashing algorithm works are not required. [3] When a member of staff logs onto a computer in a particular organisation, they enter there username and password. The password is input to the logon program as an alphanumeric string and converted to a two-byte integer using a hashing function or algorithm before being sent across a network or authentication. Outline three major steps that a typical hashing function/algorithm would use to convert an alphanumeric string into a two-byte integer. [3]

10.

ADDITIONAL NOTES:

50

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Handling data within files


Candidates should be able to: 25. Store, retrieve and search for data in files; 26. Use the facilities of a procedural language to perform file operations (opening, reading, writing, updating, inserting, appending and closing) on files of different access modes as appropriate. Before a program can use a file, the file needs to be opened. The program needs to specify whether the file is to be opened for writing, or opened only for reading. After the data has been read or written to the file, it then needs to be closed. All algorithms for handling data within files must have the following lines:
OPEN [New/Existing] File in READ/WRITE MODE CLOSE All Files

Note that these lines are not necessarily at the beginning and the end of the code, but they must be in place to make sure that the file(s) is opened and closed correctly.

Adding data
Serial file Adding data is simple it is added to the end of the file:
OPEN File in WRITE MODE GOTO End of File WRITE NewData CLOSE File

ADDITIONAL NOTES:

DJM

51

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Sequential file The addition of data to a sequential file is more complicated than in a serial file, because the record must be inserted into the correct position not just at the end of the file. In practise, when a record is added to a sequential file, it is usual to create a new file and copy all the records from the old file, but insert the new record in its correct position. An algorithm for this is shown below:
OPEN a NewFile in WRITE MODE OPEN ExistingFile in READ MODE READ First Record in ExistingFile REPEAT IF key of SelectedRecord in ExistingFile < key of NewRecord THEN COPY SelectedRecord into NewFile ELSE COPY NewRecord into NewFile COPY SelectedRecord into new file END IF READ Next Record in ExistingFile END REPEAT when new record has been copied COPY ALL remaining records from ExistingFile into NewFile CLOSE NewFile and ExistingFile

Random file The hashing algorithm is applied to the Key field in order to find the storage location for the new data.
OPEN File in WRITE MODE READ KeyField of NewRecord Apply Hashing Algorithm to calculate DiskAddress WRITE NewRecord to calculated DiskAddress CLOSE File

ADDITIONAL NOTES:

52

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Searching for/retrieving data


Serial file To retrieve data from a serial file, a program must examine the first record and then all subsequent records until the desired one is found or until the end of the file has been reached. The following algorithm does this:
OPEN File in READ MODE READ First Record SET Variable Found = False REPEAT IF RequiredRecord = SelectedRecord THEN SET Variable Found = True ELSE READ Next Record END IF END REPEAT when Found = True OR when EOF is reached CLOSE File

Note that to be sure that a record does not exist in a serial file, every single record must be examined. Sequential file Searching a sequential file is the same as searching a serial file, except that the search only has to continue until a record with a higher Key field is reached this would mean that the data is not in the file.
OPEN File in READ MODE READ First Record SET Variables Found = False, Exists = True REPEAT IF RequiredRecord = SelectedRecord THEN SET Variable Found = True ELSE READ Next Record IF Key of RequiredRecord > Key of SelectedRecord THEN Exists = False END IF END IF END REPEAT when Found = True OR Exists = False OR when EOF is reached CLOSE File

ADDITIONAL NOTES:

DJM

53

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Random file
OPEN File in READ MODE READ KeyField of RequiredRecord Apply Hashing Algorithm to calculate DiskAddress READ Record at DiskAddress IF Record does not exist THEN OUTPUT Record Not Found END IF CLOSE File

Deleting data
Serial or sequential file
OPEN a NewFile in WRITE MODE OPEN ExistingFile in READ MODE READ First Record in ExistingFile REPEAT IF Key of SelectedRecord <> Key of RecordToDelete THEN COPY SelectedRecord into NewFile ELSE DO NOT COPY SelectedRecord END IF READ Next Record in ExistingFile END REPEAT when EOF is reached CLOSE NewFile and ExistingFile DELETE ExistingFile RENAME NewFile to Name of ExixtingFile

ADDITIONAL NOTES:

54

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Calculating file size


Candidates should be able to: 27. Estimate the size of a file from its structure and the number of records. The basic formula for estimating the size of a file is: Size of file = [size of each record] [number of records] + [a little bit more!] If we consider a file with 200 records, which stores the details of an organisations customers:
CUSTOMER(RefCode, Name, PostCode, Telephone, DoB, Age)

We can estimate the size of the record as follows:


Attribute RefCode Name PostCode Telephone DoB Age Data type Integer String String String Date Real Extreme Example 99 999 Margaret Edwards WC12 16AA (0203) 9898 1234 31-12-76 104 Total Size of field (bytes) 4 20 9 16 8 4 62

Thus 200 records would require:

62 200 = 12400 bytes 12400 Kbytes 1024 = 12.1+ 1.21 (10%) = 13.3 Kbytes =
Note that to determine the maximum field length, an extreme case was considered and several bytes added to play safe.

ADDITIONAL NOTES:

DJM

55

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

2.4 COMMON FACILITIES OF PROCEDURAL LANGUAGES


Candidates should be able to: 28. Understand and use assignment statements.

Assignment
An assignment is an instruction in a program that places a value into a specified variable. Some typical assignments in REALbasic are:
TheLength = 20.5 TheUsersName$ = Charlie TheArea = TheWidth * TheLength TotalCost = LabelledCost + 15 Counter = Counter + 1

Note that the last example is a common method used to increment the value of a variable. It could be read as:
The new value of Counter is its existing value plus one

Type Mismatch errors A type Mismatch error occurs in a program when a variable has been declared as one data type, but it is later assigned a value that is of an incompatible data type. The following code will produce a Type Mismatch error because Charlie is not an integer:
DIM MyCounter AS Integer MyCounter = Charlie

Other Type Mismatches will be produced by the following:


DIM RentalDate As Date MemberRentalDate = September DIM ShoeSize As Integer JohnsShoeSize = 10.3

Note that a variable that is declared as a string will never produce a type mismatch error.

ADDITIONAL NOTES:

56

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Arithmetic operations
Candidates should be able to: 29. Understand arithmetic operators including operators for integer division (+, -, *, /, MOD and DIV) and use these to construct expressions.

Addition, subtraction and multiplication


Operator + * Meaning/purpose Addition Subtraction Multiplication Example Result=3+5 Result=37 Result=3*7 Result 8 -4 21

Powers
Operator ^ Meaning/purpose Power Example Result=3^2 Result 9

Division
A result of a division such as 17 4 can be expressed either as a real (4.25) or as two integers (4 remainder 1). The integer method, in most programming languages, uses the operators DIV and MOD.
Operator / DIV Meaning/purpose Division Integer Division returns the result of a division after ignoring the decimal portion of all numbers Remainder returns the remainder of the division of two integers Example Result=14/5 14 DIV 5 7.2 DIV 3.9 (= 7 DIV 3) 14 MOD 5 18 MOD 6 3 MOD 7 Result 2.8 2 2 4 0 3

MOD

ADDITIONAL NOTES:

DJM

57

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Relational operators
Candidates should be able to: 30. Understand a range of relational operators, eg =, <, <=, >, >= and <> and use these to construct expressions. Relational operators are used in the format: [Expression] [Operator] [Expression] and will always return a Boolean (True or False) value. Relational operators are typically used with the IF selection and also within conditional loops (REPEAT-UNTIL or WHILE-WEND). In the following table, the variables a and name$ have the following assignments:
a=3+5 name$=JAMES

Operator =

Meaning/purpose Equal tests if two expressions are identical Less Than tests if the first expression is less than the second Greater Than tests if the first expression is greater than the first

Example IF a=8 IF name$=JANET IF a=14 IF a<8 IF name$<JANET IF a<14 IF a>8 IF name$>JANET IF a>14 IF IF IF IF a<>8 name$<>JANET name$<>JAMES a<>14

Result True False False False True True False False False False True False True True True True True False False

<

>

<>

Not Equal tests if two expressions are different

<=

Less Than or Equal

IF a<=8 IF name$<=JANET IF a<=14 IF a>=8 IF name$>=JANET IF a>=14

>=

Greater Than or Equal

ADDITIONAL NOTES:

58

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Boolean operators
Candidates should be able to: 31. Understand the Boolean operators AND, OR and NOT and use these to construct expressions.

AND and OR
The AND and OR operators always return a Boolean result and are used in the format:
[Boolean] [Operator] [Boolean]

The following truth table summarises the result of the Boolean operations:
Values X True True False False Y True False True False X AND Y True False False False Results X OR Y True True True False

NOT
The NOT operator reverses the result of the Boolean expression and is used in the format:
NOT [Boolean]

The following truth table summarises the NOT operation:


X True False NOT X False True

ADDITIONAL NOTES:

DJM

59

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Examples of Boolean logic


Consider the following algorithm, which is used to monitor a printer and display its output via an LCD display in the front panel:
IF NOT(PaperTrayEmpty) AND (FilesWaiting > 0) THEN OUTPUT PRINTING ELSE OUTPUT PLEASE ADD PAPER END IF

If the values of the variables are:


PaperTrayEmpty = False FilesWaiting = 2

Then the output will be PRINTING The following table shows why:
X PaperTrayEmpty False FilesWaiting 2 NOT(PaperTrayEmpty) True Y FilesWaiting > 0 True True X AND Y

Other options are shown in this table:


X PaperTrayEmpty True True False FilesWaiting 2 0 0 NOT(PaperTrayEmpty) False False True Y FilesWaiting > 0 False False False False False False X AND Y

Note that in all three of these cases the output will be PLEASE ADD PAPER even the last one in which PaperTrayEmpty = False. To avoid this incorrect message, the algorithm should be rewritten using a nested IF, as shown on the next page:

ADDITIONAL NOTES:

60

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

IF PaperTrayEmpty THEN OUTPUT PLEASE ADD PAPER ELSE IF FilesWaiting > 0 THEN OUTPUT PRINTING ELSE OUTPUT STATUS OK END IF END IF

ADDITIONAL NOTES:

DJM

61

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Precedence of operations
Candidates should be able to: 32. Understand the effects of the precedence of standard operators and the use of parentheses to alter the order of precedence.

This is mathematics follow BODMAS!

ADDITIONAL NOTES:

62

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Evaluating expressions
Candidates should be able to: 33. Evaluate expressions containing arithmetic, relational and Boolean operators and parentheses.

SOME QUESTIONS TO BE ADDED HERE

ADDITIONAL NOTES:

DJM

63

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

String manipulation
Candidates should be able to: 34. Understand and use a range of operators and built-in functions for string manipulation, including location (LOCATE), extraction (LEFT, MID, RIGHT), comparison, concatenation, determining the length of a string (LENGTH) and converting between characters and their ASCII code (ASCII and CHAR).

Location
Many programming languages allow the searching for a short string of characters within a longer string. This would be similar to searching this book for the word computer. Common Key words for finding the location of one string within another are LOCATE, FIND and
POSITION Function LOCATE Purpose Returns the starting position of the first string, within the second string (returns 0 if the string is not found):
x$=Locate(math, mathematics) x$=Locate(the, mathematics) x$=Locate(tea, mathematics) 1 3 0

Result

ADDITIONAL NOTES:

64

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Extraction
At times, a programmer will only want part of a string. Any part of a string can be obtained using the RIGHT, LEFT and MID functions. The following string manipulation functions are called by typing: Result=FunctionName(String [,x, y])
Function RIGHT Purpose Returns the number of specified characters from the right of the string:
x$=Right(Computing, 3) ing

Result

LEFT

Returns the number of specified characters from the left of the string:
x$=Left(Computing, 3) Com

MID

Returns the number of specified characters from the middle of the string:
x$=Mid(Computing, 5, 2) ut

Concatenation
Concatenation is where two or more strings are joined together to make a single string. Note that when two strings are added together the second string is added to the end of the first:
Peter + Jones = PeterJones Peter + + Jones = Peter Jones 36.85 + 47 = 36.8547 47 + 36.85 =4736.85 3/10/03 + 15 = 3/10/0315

ADDITIONAL NOTES:

DJM

65

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Length
Sometimes a programmer will need to know how many characters there are in a string.
Function LEN Purpose Returns the number of characters in the specified string:
x=Len(Computing) 9

Result

Conversion
Strings and numbers Strings are a sequence of ASCII characters, even if they contain only numbers such as 241, and so they cannot be used within an arithmetic calculation they need to be evaluated first. Likewise a number such as 27.3 is not stored as ASCII characters and so cannot be used within any of the string functions (such as Left, Right, Mid). The function STR converts a number into a string and VAL converts a string into a number:
Function STR Purpose Returns the string form of the value:
x$=Str(31) 31

Result

VAL

Returns the numeric form of the string:


x=Val(42Chig) 42

Characters and ASCII codes The following two functions are used to either find the ASCII code for a specific character or to find the character from the ASCII code:
Function ASC Purpose Returns the ASCII code for the specified character:
x=Asc(A) 65

Result

CHR

Returns the character whose ASCII code is specified:


x$=Chr(68) D

ADDITIONAL NOTES:

66

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Relational operators and strings


Candidates should be able to: 35. Understand that relational operations on alphanumeric strings depend on character codes of the characters and explain the results of this effect (e.g. why XYZ < abc, 2 > 17 and 3 <> 3.0).

Storing strings
Strings are stored as a sequence of character codes - usually ASCII or Unicode. ASCII character codes Below is a table showing the most common characters and their ASCII codes:

Note the following: the codes less than 32 are control codes that are not used in strings; space (code 32) has the lowest code; next comes most of the punctuation symbols; then digits 09 then uppercase letters then lowercase letters all other characters (e.g. , , , etc.) have codes higher than these.

ADDITIONAL NOTES:

DJM

67

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Comparing strings
When comparing strings, the codes of each string are compared, character by character, to decide which string is greater. Because it is the ASCII codes that are compared the following applies:
Computing <> computing

in fact:
Computing < computing 10 < 2 02 < 1 1 120 < 1,120 computing < Computing

Sorting filenames The following table shows a list of inconsistently names music tracks and the order in which they would be sorted:
Required order Track 1.mp3 Track 2.mp3 Track 3.mp3 track 4.mp3 Track 5.mp3 Track 06.mp3 track 7.mp3 Track8.mp3 Track 11.mp3 Track12.mp3 track 13.mp3 Track21.mp3 Track 22.mp3 Sorted order Track 5.mp3 track 4.mp3 Track 06.mp3 Track 1.mp3 Track 11.mp3 Track 2.mp3 Track 22.mp3 Track 3.mp3 Track12.mp3 Track21.mp3 Track8.mp3 track 7.mp3 track 13.mp3

In order to get them sorted into the required order, they must be renamed with consistent use of uppercase letters, spaces and leading zeros. Recommended naming would be:
Track 01.mp3, Track 02.mp3, , Track 10.mp3, Track 11.mp,

ADDITIONAL NOTES:

68

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Data input
Candidates should be able to: 36. Input and validate data.

Input controls
Input can be via a command line prompt, but in modern graphical user interfaces, input is usually via a form or dialogue box. Such forms or dialogue boxes have a set of controls, which let the user enter data: Text boxes; Drop-down lists; Check-boxes; Option buttons.

ADDITIONAL NOTES:

DJM

69

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Validation
The drop-down lists, check-boxes and option buttons are extremely useful in that they provide an automatic means of validation the user can only input pre-determined values. Other validation needs to be programmed into the system and is often added to the submit button. Presence check Code can be added to check that a particular control has not been left empty or un-checked:
If Username.Text = Then Msgbox(You have not entered a Username) End

Range check Code can be added to check that a particular control has a value between an allowed maximum and minimum:
If val(Age.Text) < 11 OR val(Age.Text) > 70 Then Msgbox(The age that you have netered is not within the_ permitted range) End

Length check Code can be added to check that a particular control has a value between an allowed maximum and minimum:
If Len(Password.Text) > 12 Then Msgbox(The password that you have entered is too long) End

Note that all of the above validation code (and any additional validation) could be added to the submit button.

ADDITIONAL NOTES:

70

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Data output
Candidates should be able to: 37. Output data onto screen/file/printer, formatting the data for output as necessary. Output will be either to the screen, a file or the printer.

Output controls
Output to the screen could be via a dialogue/message box, a text box or a list box.

COMMENTS TO BE ADDED HERE

ADDITIONAL NOTES:

DJM

71

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

2.5 WRITING MAINTAINABLE PROGRAMS


Candidates should be able to: 38. Define, understand and use the following terms correctly as they apply to programming: variable, constant, identifier, reserved word/keyword; 39. Declare variables and constants, understanding the effect of scope and issues concerning the choice of identifier (including the need to avoid reserved words/keywords); 40. Initialise variables appropriately, before using them.

Variable
A variable is a value that can change during the execution of a program. There are two types of variables used by programmers and they are categorised according to their scope. Scope Scope indicates whether a variable can be used by all parts of a program or only within limited sections of the program for example, within a subroutine. Global variable A global variable is one that is declared at the start of the main program and is visible (useable) everywhere in the program and exists for the lifetime of the program. Note that if one procedure changes the value of a global variable, then the next procedure that uses the variable will be given this changed value this is a common cause of errors. Local variable A local variable is one that is only visible inside the procedure or function in which it is declared. Note that a local variable cannot be referenced from outside the procedure. In fact a local variable does not exist until the procedure starts executing and it disappears when the procedure stops executing. Thus any value that is held by a local variable is only stored temporarily. The lifetime of a local variable is the lifetime of the procedure in which the local variable is declared.

ADDITIONAL NOTES:

72

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods The advantage of using local variables rather than global variables is that the same variable names can be used in several different procedures without any chance of values being confused. Initialising variables Initialising a variable means setting it to a starter value. Initialisation will usually set the value of an integer to 0 or 1 and a string to Empty (). The following code initialises the variable Counter to zero before it is used in the iteration:
Counter=0 the variable is initialised REPEAT Counter=Counter+1 UNTIL Counter=10

Initialising a variable ensures that its value has not be been retained from a previous use of the routine and that the value has not been accidently set in another part of the program this helps avoid errors.

Declaration
A declaration is a statement in a program that gives the compiler or the interpreter information about a variable or constant that is to be used within a program. A declaration ensures that sufficient memory is reserved in which to store the values and also states the variables data type. Declaration of local variables
DIM DIM DIM DIM DIM MyCounter AS Integer FirstName, LastName AS String declares two variables TheLength AS Single DOB AS Date OverDueFlag AS Boolean

Intrinsic variable declarations Some programming languages require intrinsic variable declarations. This means that variables must be declared before they are used.

ADDITIONAL NOTES:

DJM

73

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods The advantage of intrinsic variable declaration is that it cuts out possible errors due to the misspelling of a variable name if a variable is used that has not been declared, the programming translator will identify it as an error.
DIM Number As Integer Number= Nubmer+1 This will be flagged as an Error!

Constant
A constant is a value that is set when the program initialises and does not change during the programs execution.

Identifier
Identifier is the name given to a variable, constant or subroutine. Assigning a variable or constant an identifier name means that it can be easily referenced from any part of the program within its scope and it helps to make the program more readable.

Reserved word/keyword

ADDITIONAL NOTES:

74

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Good program writing techniques


Candidates should be able to: 41. Explain the need for good program-writing techniques to facilitate the ongoing maintenance of programs; 42. Select and use meaningful identifier names and use standard conventions to show the data types and enhance readability; 43. Use declared constants to improve maintainability. Maintenance is the updating of a program after it has been released. Maintenance will be helped when the programmer uses good programming techniques. This means that the programmer should write code that is self-documenting and split into small sections. Specifically, the programmers should: use meaningful identifier names for variables, constants and subroutines; use declared constants; annotate code with comments; indent code within iteration and selection; split the code into modules when possible.

The need for good program-writing techniques


It is important for a programmer to use good programming techniques when writing code so that the code: can be easier to understand by other programmers (who are either part of the programming team, or who will be responsible for the maintenance of the program in the future); can be understandable by the programmer themselves in the future; is split into smaller blocks which are easier to debug individually and update; is less prone to errors because the meaningful variable names and comments make it selfdocumenting and easier to read.

ADDITIONAL NOTES:

DJM

75

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Meaningful identifier names


Identifiers are used to give names to constants and variables. They are also used to name procedures, functions and the main program.

Naming conventions
REALbasic identifier names must conform to the following rules (other programming languages may have slightly different rules): they must be unique; spaces must not be used; they must begin with a letter of the alphabet; the rest of the identifier must not contain punctuation it may only consist of a mixture of letters and digits (AZ, az and 09) and the underscore character _; they must not be a reserved word eg Print, Repeat, For, Dim, Loop, etc. Note that REALbasic names are not case sensitive this means that MyCounter is the same as MYCOUNTER, mycounter, mYcOUNTeR, etc. This is not the case in all languages, however.

Recommended naming policies


Do not use spaces within identifier names even with programming languages where they are permitted. Instead use the underscore character _ or, better still, type names in lowercase except the first letter of each word, which should be typed in uppercase. Examples of good identifier names:
FirstName TelephoneNumber AverageHeight LastName WeightAtBirth PostCode TestScore

Further clarity can be given to identifier names by including a prefix that identifies the data type. The above identifiers would be clearer if given the following names:
strFirstName strTelephoneNumber sglAverageHeight strLastName sglWeightAtBirth strPostCode intTestScore

ADDITIONAL NOTES:

76

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Using declared constants


Constants will be declared at the start of the main program. The following shows the declaration of constants for Pi and the VAT rate
CONST Pi = 3.142 CONST VatRate = 0.175

Declaring constants at the start of a program means that maintenance is made easier for two reasons: if the value of a constant changes, it only has to be changed in the one part of the program where it has been declared, rather than in each part of the program in which it is used; the code is easier to interpret: Total=VatRate*CostPrice allows a greater understanding than
Total=0.175*CostPrice

ADDITIONAL NOTES:

DJM

77

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Annotating code
Candidates should be able to: 45. Annotate the code with comments so that the logic of the solution can be followed.

Comments/remarks
Comments (originally called remarks) are added to program code to provide useful, or essential, documentation for the programmer and other people who read the code. All programs/subroutines should contain comments to indicate: the details of the person who wrote the code; the date that the code was written; the purpose of the code; how parts of the code work; the use of certain variables. Comments can be used anywhere in a program either as separate lines by themselves or on the same line as executable code provided they appear to the right of any code that will execute. Comments are usually indicated by the use of an apostrophe (), or two forward slashes (//).
PROCEDURE Arrange(NumberOfScores) Procedure to move the largest element in an array to the end Coded by J Jones, 02/03/09 DIM Ptr, Temp As Integer ptr is the value of the array index FOR Ptr = 1 TO NumberOfScores go through each element test the relative values of the elements IF Scores(Ptr) < Scores(Ptr + 1) THEN use a temporary store to help swap the elements Temp = Scores(Ptr) Scores(Ptr) = Scores(Ptr + 1) Scores(Ptr + 1) = Temp END IF NEXT Ptr increment the index to examine the next element END PROCEDURE

Note that comments are ignored when the program code is compiled and so they are not present within the stand-alone application.

ADDITIONAL NOTES:

78

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Indenting code
Candidates should be able to: 46. Use indentation and formatting to show clearly the control structures within the code. Indentation should be used within iteration and selection statements so that it is clear which instructions go together. Examples:
Original code INPUT Number Total=0 WHILE Number > 0 THEN Left=Number MOD 10 Right = Number DIV 10 Total=Total+Left Number=Right END WHILE Indented code INPUT Number Total=0 WHILE Number > 0 THEN Left=Number MOD 10 Right = Number DIV 10 Total=Total+Left Number=Right END WHILE

Original code FUNCTION TEST(X) IF X=1 THEN PRINT 1 RETURN 1 ELSE Number=X*Test(X-1) PRINT Number RETURN Number END IF END TEST

Indented code FUNCTION TEST(X) IF X=1 THEN PRINT 1 RETURN 1 ELSE Number=X*Test(X-1) PRINT Number RETURN Number END IF END TEST

ADDITIONAL NOTES:

DJM

79

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Using subroutines
Candidates should be able to: 44. Create appropriately modularised programs (following a topdown/modular design as produced in 3.2.1: Designing solutions to problems) making effective use of subroutines to improve maintainability.

COMMENTS TO BE ADDED

ADDITIONAL NOTES:

80

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

2.6 TESTING AND RUNNING A SOLUTION


Candidates should be able to: 47. Describe types of errors in programs (syntax, logic and runtime errors) and understand how and when these may be detected.

Syntax error
A syntax error is when a statement does not follow the rules of the language omitting parenthesis ( ), opening, but not closing a bracket and incorrect use of punctuation are common syntax errors. Note that the misspelling of a keyword can be considered as a syntax error if the language uses intrinsic variable declaration e.g. typing PLINT instead of PRINT would produce a syntax error. The following code contains many different syntax errors:
DIM X no data-type has been stated X=1 IF X > 1 no THEN statement Y=(2*X+3 no closing bracket PLINT Y misspelling of a keyword NEXT NEXT statement without a FOR (Should have been END IF)

Logic error
A logic error is an error in the design of the code it could be that the programmer has used the wrong formula or the programmer has written a routine that will exit a loop early (e.g. after three iterations instead of four).

ADDITIONAL NOTES:

DJM

81

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Run-time error
A run-time error is an error that can only be detected while the program is executing it cannot be detected during compilation run-time errors can be logical errors, but they are often arithmetic errors.

Arithmetic error An arithmetic error is when it is impossible to evaluate an arithmetic expression for example, an attempted division by zero. The following code will produce an arithmetic error on the fourth line because X was initialised to zero and the first iteration will attempt to divide by X when it is this initial value:
X=0 X is initialised to zero Y=1 FOR i=1 TO 10 Y=Y/X attempted division by zero on first iteration X=X+i NEXT

ADDITIONAL NOTES:

82

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Testing algorithms
Candidates should be able to: 48. Identify why/where an error may occur in an algorithm and state how the algorithm may be corrected. This is a skill, which develops with your programming experience. An example question may be as follows:
The following procedure has been written to output the answers to three divisions before going on to the next part of the main algorithm. (It does not work). PROCEDURE DIVIDE X=Y=Z=0 C=1 REPEAT Z=X/Y READ X,Y C+1=C UNTIL C=3 END PROCEDURE PLINT Z Question State one syntax error in the procedure, explaining why it is a syntax error and how it can be corrected. Answer C+1=C is a syntax error because an assignment statement must only have one value on the left hand side of the equals. This is corrected by writing the assignment as C=C+1. Note that in some programming languages X=Y=Z=0 would be a syntax error and would be corrected by writing it as X=0, Y=0, Z=0. Also some languages may consider PLINT Z as a syntax error (other languages would identify it as an Illegal Command). Z=X/Y is an arithmetic error because Y has been initialized to be zero. This could be corrected by swapping the statements Z=X/Y and READ X, Y. The placement of PLINT Z outside of the procedure is a logic error it should be in the REPEAT-UNTIL loop if the answers to all three divisions were going to be outputted. The statement UNTIL C=3 is also a logic error because line 3 initialises C=1 and so the loop would only be executed two times, not three. The statement should read UNTIL C>3 or UNTIL C=4.

State one arithmetic error in the procedure, explaining why it is an arithmetic error and how it can be corrected. State one logic error in the procedure, explaining why it is a logic error and how it can be corrected.

ADDITIONAL NOTES:

DJM

83

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Testing strategies
Candidates should be able to: 49. Describe testing strategies including white box testing, black box testing, alpha testing, beta testing and acceptance testing.

White box
White box testing examines the actual code and tests the different routes through the program.

Black box
Black box testing is when selected test data is imputed and the actual output is compared with the expected output, without considering the way in which the program works.

Alpha testing
Testing is performed by the programming team, using their own test data and their own computer systems, to correct bugs and to check that the original objectives have been met. Benefits of alpha testing are: Sections of the program can be tested in isolation; Testers know what they are looking for.

Beta testing
Testing is performed by a group of actual end-users not connected with the programming team. They use real data, on a variety of computer systems, in order to detect bugs before the official release of the software. Benefits of beta testing are: The actual end-users will use the program in ways not predicted by the programmers and so will discover bugs that were missed by the programmers; The system will be tested on many different hardware systems, of varying ages and with many different configurations.

Acceptance testing
Tests and test data are decided upon by the end-user/client, to ensure that the original objectives have been met, before the user accepts the system as finished.

ADDITIONAL NOTES:

84

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Selecting test data


Candidates should be able to: 50. Select suitable test data for a given problem, including normal, borderline and invalid data. Test data needs to be chosen to ensure that a program works with valid data in all scenarios and that it does not accept invalid data. This means that test data needs to include: normal data; borderline data; invalid data.

Normal data
Normal data are any data that is expected to be inputted by the real users and should be accepted and correctly processed by the program. There might be several sets of normal data if there are several different scenarios within the objectives of the program.

Borderline (extreme/boundary) data


Borderline data are any data that are at the maximum or minimum for a particular processing scenario. Borderline data will include maximum and minimum values for both valid and invalid data. It will also include the values at which different processing will occur within selection statements.

Invalid data
Invalid data are data that should not be accepted by the system an appropriate error message should be displayed. Note that many tests may need to be performed in order to fully prove that a system is working correctly, but each test should only use a limited amount of data. This is so: there is a manageable number of data to input; expected results can be calculated easily.

ADDITIONAL NOTES:

DJM

85

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods Example:


Software calculates the cost of parking at a council car park as follows: Free form 5am to 8am 3 per hour or part of an hour between 8am and 5pm Free from 5pm to 12 midnight No parking from 12 midnight to 5am

Solution: Suitable test data will include: data within each of the valid parking periods; data that crosses more than one of the valid parking periods data at the boundaries of the valid parking periods; data not within the valid parking periods. The test data should be presented in a table similar to the following:
Test data 6am to 7am 9am to 11am 10am to 10:30am 6pm to 7pm 3pm to 7pm Reason for test Test that no charge is made between 5am to 8am Test that a charge of 3 per hour is applied between 8am and 5pm Test that a charge of 3 is applied per part hour Test that no charge is made between 5pm to midnight Test the correct charge is applied when parking crosses from a 3 per hour period to a free period Test the charge is correctly applied for the maximum possible parking period. Test that the correct charge is applied up to 5pm Test that the free period starts at 5pm Test that there is no parking allowed between 12 midnight to 5am Kind of test data Valid data Valid data Valid data Valid data Valid data Expected outcome Free Charge is 6 Charge is 3 Free Charge is 6

8am to 5pm

Borderline data

Charge is 24

4pm to 5pm 5pm to 6pm 1am to 2am

Borderline data Borderline data Invalid data

Charge is 3 Free Data is rejected

ADDITIONAL NOTES:

86

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods Example 2:


A procedure has been written which will accept any two numbers and output the larger. Give different sets of data, which could be used to test the procedure.

Solution 2:
Test data 3 and 7 3 and 4 2 and 2.5 3 and 3 Reason for test Test that the procedure works with ordinary, common data Test that the procedure works with negative values Test that the procedure works with real numbers Test what happens when the two inputs are equal Kind of test data Valid data Valid data Valid data Valid data Expected outcome 7 3 2.5 3

Note that in this case there are no invalid numbers and no boundary values to test all numbers are valid from .

ADDITIONAL NOTES:

DJM

87

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Dry running algorithms


Candidates should be able to: 51. Perform a dry run on a given algorithm, using a trace table.

EXAMPLE TO GO HERE

ADDITIONAL NOTES:

88

DJM

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Debugging tools
Candidates should be able to: 52. Describe the use of a range of debugging tools and facilities available in procedural programming languages including translator diagnostics, break points, stepping, and variable checks. A translator converts a programmers source code into machine code. In doing this, a translator will also check for illegal commands, undeclared variables and syntax errors.

Translator diagnostics
Translator diagnostics are messages generated by the translator (e.g. the compiler) while it is translating the source code into the object code. Translator diagnostics will provide information mainly about syntax errors, but also about undeclared variables including misspellings. A translator will identify the keywords in a statement: it will check the keywords with its table of reserved words; if it recognizes the keyword as a command, it will check the syntax of the command; it will check that the keyword follows the rules for variable names; it will check the keywords with its table of declared variables.

Break points
Break points can be set within program code so that the program stops temporarily to check that it is operating correctly to that point.

Stepping
Stepping is executing the code one line at a time and usually involves the programmer examining the value of the variables at each step.

Variable checks
Variables can either be outputted on the screen as the code executes or variable dumps can be made to the screen or printer at various points during execution.

ADDITIONAL NOTES:

DJM

89

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

Installation routines
Candidates should be able to: 53. Describe the purpose of an installation routine in the delivered version of the program.

An installation routine is a routine that will copy an executable of a completed program onto the computer(s) from which it will be run A typical installation routine will do any/all of the following: extract the program from a compressed file on the installation CD copy the program to a designated folder on the target computer; copy all necessary data files onto the target computer; copy (and register) any necessary library files; create a shortcut on the desktop and/or start menu so that the program can be easily; allow the user to personalise the program and configure some of its settings; save the programs configuration in the registry/configuration file.

ADDITIONAL NOTES:

90

DJM

www.revision-notes.co.cc