85
A Level. Computing (9691/2) www.revision-notes.co.cc Designing Solutions Structure of Programs Data Types Facilities of Languages Maintainable Programs Testing www.revision-notes.co.cc

57135463 a Level Computing 9691 Paper 2 Notes

Embed Size (px)

Citation preview

A Level. Computing (9691/2)www.revision-notes.co.cc

Designing Solutions Structure of Programs Data Types Facilities of Languages Maintainable Programs Testing

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 7

ADDITIONAL NOTES:

2.1 DESIGNING SOLUTIONS TO PROBLEMS

Candidates should be able to: 1. Discuss the importance of good interface design; 2. 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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

8 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 9

ADDITIONAL NOTES:

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 child’s interface should be bright and possibly include pictures within command buttons – particularly for the pre-reading age group; a specialist professional such as a graphic’s 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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

10 DJM

ADDITIONAL NOTES:

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 full-screen, then a title to the window would be expected.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 11

ADDITIONAL NOTES:

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 Data type Size of field (bytes)

Name String 15

Score Integer 2

Date Date 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 player’s full name (first and last) was required then 25 or more bytes would probably be needed.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

12 DJM

ADDITIONAL NOTES:

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);

5. Produce and describe top-down/modular designs using appropriate techniques including structure diagrams, showing stepwise refinement.

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 Drawbacks

Smaller problems are easier to understand Modules must be linked and additional testing must be carried out to make sure that the links work correctly

Smaller problems are easier to test and debug Programmers must ensure that cross-referencing is done

Development can be shared between a team of programmers – each person programming different modules according to their individual strengths.

Interfaces between modules must be planned

Code from previously developed modules can be re-used

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 13

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

14 DJM

ADDITIONAL NOTES:

Algorithms

Candidates should be able to: 6. Produce algorithms to solve problems; 7. Describe the steps of an algorithm using a program flowchart; 8. 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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 15

ADDITIONAL NOTES:

Flowchart to output the first five square numbers

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

16 DJM

ADDITIONAL NOTES:

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 customer’s balance ELSE OUTPUT “Sorry, insufficient funds” END IF END

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 17

ADDITIONAL NOTES:

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 algorithm’s 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!

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

18 DJM

ADDITIONAL NOTES:

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 Disadvantages

The end-user can see a working prototype sooner than in the Systems Life Cycle approach.

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).

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).

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 re-thinking in necessary between prototype versions.

The overall development time is usually shorter and so costs are reduced.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 19

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

20 DJM

ADDITIONAL NOTES:

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) ‘passes the parameter 5 – returns 25 Square(8) ‘passes the parameter 8 – returns 64 Square(x) ‘passes the value of the variable x CalculateVolume(7,14,8) ‘three parameters are passed

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 21

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

22 DJM

ADDITIONAL NOTES:

Flowcharts showing the control structures

Sequence Selection Iteration

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 23

ADDITIONAL NOTES:

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 can’t 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 backwards CASE RightArrow Move one character forwards CASE UpArrow Move one character up CASE DownArrow Move one character down END SELECT

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

24 DJM

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 25

ADDITIONAL NOTES:

Comparison of the different iterations FOR-NEXT WHILE-WEND REPEAT-UNTIL

An unconditional loop – it will repeat itself a set number of times.

A conditional loop – it will repeat until a variable has reached a stated value.

A conditional loop – it will repeat until a variable has reached a stated value.

The condition is tested at the start of the loop.

The condition is tested at the end of the loop.

Iteration statements will always execute at least once.

Iteration statements may not actually be executed.

Iteration statements will always execute at least once.

For x= 1 To 10 a=x*5 Output x, a Next x

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

x=1 Repeat a=x*5 Output x, a x=x+1 Until x > 10

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

26 DJM

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 27

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

28 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 29

ADDITIONAL NOTES:

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

Function Call Returned Value

Condition State of Function Call

01 Factorial(3)

02 False

05 3 * Factorial(2) New Call: n=2 n=3: Postponed

01 Factorial(2)

02 False

05 2 * Factorial(1) New Call: n=1 n=2: Postponed

01 Factorial(1)

02 True

03 1

07 n=1: Completed

05 2 * 1 = 2 n=2: Resumed

07 n=2: Completed

05 3 * 2 = 6 n=3: Resumed

07 n=3: Completed

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

30 DJM

ADDITIONAL NOTES:

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

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

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 31

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

32 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 33

ADDITIONAL NOTES:

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 Example value Storage Required

Integer 42 4 bytes

Real 23.1 4 or 8 bytes

Boolean True 1 byte

String “Hello World” 1 byte for each character (if using Unicode, then 2 bytes are required for each character)

Character “X” 1 byte

Date 12/11/2009 8 bytes

Container Image, video or sound Lots!

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

34 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 35

ADDITIONAL NOTES:

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 one-dimensional 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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

36 DJM

ADDITIONAL NOTES:

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”

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 37

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

38 DJM

ADDITIONAL NOTES:

Serial search on an array The following pseudo-code can be used to search an array to see if an item X exists:

01 DIM Index As Integer 02 DIM Flag As Boolean 03 Index = 0 04 Flag = False 05 Input X 06 REPEAT 07 IF TheArray(Index) = X THEN 08 Output Index 09 Flag = True 10 END IF 11 Index = Index + 1 12 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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 39

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

40 DJM

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 41

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

42 DJM

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 43

ADDITIONAL NOTES:

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 Mary’s, Wilton High, West Orling.

Centre Number

Centre Name

No of Candidates

27102 Kettlewood 85

38240 Queens Park 103

64715 St Mary’s 121

30446 Wilton High 156

12304 West Orling 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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

44 DJM

ADDITIONAL NOTES:

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 Mary’s, Wilton High, West Orling but they are stored in the order of the key field – Centre Number:

Centre Number

Centre Name

No of Candidates

12304 West Orling 105

27102 Kettlewood 85

30446 Wilton High 156

38240 Queens Park 103

64715 St Mary’s 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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 45

ADDITIONAL NOTES:

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 school’s 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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

46 DJM

ADDITIONAL NOTES:

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).

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 47

ADDITIONAL NOTES:

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:

271025000

= 5 remainder 2102

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

Centre Name

No of Candidates

Disk Address

27102 Kettlewood 85 2102

38240 Queens Park 103 3240

64715 St Mary’s 121 4715

30446 Wilton High 156 446

12304 West Orling 105 2304

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

48 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 49

ADDITIONAL NOTES:

Exercise CPT2.2B

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

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]

3. 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]

4. (a) What file organisation is required if the priority is to find a specific record in a file?

Justify your answer. [2] (b) What file organisation is required if the priority is to access individual records quickly?

Justify your answer. [2]

5. List the steps required in order to add a record to a sequential file. [4]

6. What is a direct access medium? [2]

7. (a) What is meant by ‘hashing’? [2] (b) Give two properties that a hashing algorithm should have. [2]

(c) A hashing algorithm uses the expression (ASCII Code)Mod 150. Why is Mod 150 used? [1]

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

50 DJM

ADDITIONAL NOTES:

8. (a) What are the major steps that a typical hashing function/algorithm would use to convert a alphanumeric string into a two-byte integer. [2]

(b) 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]

10. 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]

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 51

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

52 DJM

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 53

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

54 DJM

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 55

ADDITIONAL NOTES:

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 organisation’s customers:

CUSTOMER(RefCode, Name, PostCode, Telephone, DoB, Age)

We can estimate the size of the record as follows: Attribute Data type Extreme Example Size of field

(bytes)

RefCode Integer 99 999 4

Name String Margaret Edwards 20

PostCode String WC12 16AA 9

Telephone String (0203) 9898 1234 16

DoB Date 31-12-76 8

Age Real 104 4

Total 62

Thus 200 records would require:

62 × 200 = 12400 bytes

= 124001024

Kbytes

= 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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

56 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 57

ADDITIONAL NOTES:

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 Example Result

+ Addition Result=3+5 8

– Subtraction Result=3–7 -4

* Multiplication Result=3*7 21

Powers

Operator Meaning/purpose Example Result

^ Power Result=3^2 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 Meaning/purpose Example Result

/ Division Result=14/5 2.8

DIV Integer Division – returns the result of a division after ignoring the decimal portion of all numbers

14 DIV 5 7.2 DIV 3.9 (= 7 DIV 3)

2 2

MOD Remainder – returns the remainder of the division of two integers

14 MOD 5 18 MOD 6 3 MOD 7

4 0 3

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

58 DJM

ADDITIONAL NOTES:

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 Example Result

= Equal – tests if two expressions are identical

IF a=8 IF name$=”JANET” IF a=14

True False False

< Less Than – tests if the first expression is less than the second

IF a<8 IF name$<”JANET” IF a<14

False True True

> Greater Than – tests if the first expression is greater than the first

IF a>8 IF name$>”JANET” IF a>14

False False False

<> Not Equal – tests if two expressions are different

IF a<>8 IF name$<>”JANET” IF name$<>”JAMES” IF a<>14

False True False True

<= Less Than or Equal IF a<=8 IF name$<=”JANET” IF a<=14

True True True

>= Greater Than or Equal IF a>=8 IF name$>=”JANET” IF a>=14

True False False

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 59

ADDITIONAL NOTES:

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 Results

X Y X AND Y X OR Y

True True True True

True False False True

False True False True

False False False 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 NOT X

True False

False True

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

60 DJM

ADDITIONAL NOTES:

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 Y X AND Y

PaperTrayEmpty FilesWaiting NOT(PaperTrayEmpty) FilesWaiting > 0

False 2 True True True

Other options are shown in this table:

X Y X AND Y

PaperTrayEmpty FilesWaiting NOT(PaperTrayEmpty) FilesWaiting > 0

True 2 False False False

True 0 False False False

False 0 True False False

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:

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 61

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

62 DJM

ADDITIONAL NOTES:

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!

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 63

ADDITIONAL NOTES:

Evaluating expressions

Candidates should be able to: 33. Evaluate expressions containing arithmetic, relational and

Boolean operators and parentheses.

SOME QUESTIONS TO BE ADDED HERE

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

64 DJM

ADDITIONAL NOTES:

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 Purpose Result

LOCATE 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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 65

ADDITIONAL NOTES:

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 Purpose Result

RIGHT Returns the number of specified characters from the right of the string:

x$=Right(“Computing”, 3) “ing”

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”

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

66 DJM

ADDITIONAL NOTES:

Length Sometimes a programmer will need to know how many characters there are in a string.

Function Purpose Result

LEN Returns the number of characters in the specified string:

x=Len(“Computing”) 9

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 Purpose Result

STR Returns the string form of the value:

x$=Str(31) “31”

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 Purpose Result

ASC Returns the ASCII code for the specified character:

x=Asc(“A”) 65

CHR Returns the character whose ASCII code is specified:

x$=Chr(68) “D”

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 67

ADDITIONAL NOTES:

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 0–9 • then uppercase letters • then lowercase letters • all other characters (e.g. é, å, π, etc.) have codes higher than these.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

68 DJM

ADDITIONAL NOTES:

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 Sorted order Track 1.mp3 Track 5.mp3 Track 2.mp3 track 4.mp3 Track 3.mp3 Track 06.mp3 track 4.mp3 Track 1.mp3 Track 5.mp3 Track 11.mp3 Track 06.mp3 Track 2.mp3 track 7.mp3 Track 22.mp3 Track8.mp3 Track 3.mp3 Track 11.mp3 Track12.mp3 Track12.mp3 Track21.mp3 track 13.mp3 Track8.mp3 Track21.mp3 track 7.mp3 Track 22.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, …

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 69

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

70 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 71

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

72 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 73

ADDITIONAL NOTES:

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 MyCounter AS Integer DIM FirstName, LastName AS String ‘declares two variables DIM TheLength AS Single DIM DOB AS Date DIM OverDueFlag AS Boolean

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

74 DJM

ADDITIONAL NOTES:

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 program’s 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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 75

ADDITIONAL NOTES:

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 self-

documenting and easier to read.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

76 DJM

ADDITIONAL NOTES:

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 (A–Z, a–z and 0–9) 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 LastName PostCode

TelephoneNumber WeightAtBirth TestScore

AverageHeight

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 strLastName strPostCode

strTelephoneNumber sglWeightAtBirth intTestScore

sglAverageHeight

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 77

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

78 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 79

ADDITIONAL NOTES:

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 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

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 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

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

80 DJM

ADDITIONAL NOTES:

Using subroutines

Candidates should be able to: 44. Create appropriately modularised programs (following a top-

down/modular design as produced in 3.2.1: Designing solutions to problems) making effective use of subroutines to improve maintainability.

COMMENTS TO BE ADDED

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 81

ADDITIONAL NOTES:

2.6 TESTING AND RUNNING A SOLUTION

Candidates should be able to: 47. Describe types of errors in programs (syntax, logic and run-

time 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).

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

82 DJM

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 83

ADDITIONAL NOTES:

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 Answer

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

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).

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

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.

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

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

84 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 85

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

86 DJM

ADDITIONAL NOTES:

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 Reason for test Kind of test data Expected outcome

6am to 7am Test that no charge is made between 5am to 8am

Valid data Free

9am to 11am Test that a charge of £3 per hour is applied between 8am and 5pm

Valid data Charge is £6

10am to 10:30am

Test that a charge of £3 is applied per part hour

Valid data Charge is £3

6pm to 7pm Test that no charge is made between 5pm to midnight

Valid data Free

3pm to 7pm Test the correct charge is applied when parking crosses from a £3 per hour period to a free period

Valid data Charge is £6

8am to 5pm Test the charge is correctly applied for the maximum possible parking period.

Borderline data Charge is £24

4pm to 5pm Test that the correct charge is applied up to 5pm

Borderline data Charge is £3

5pm to 6pm Test that the free period starts at 5pm

Borderline data Free

1am to 2am Test that there is no parking allowed between 12 midnight to 5am

Invalid data Data is rejected

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 87

ADDITIONAL NOTES:

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 Reason for test Kind of test data Expected outcome

3 and 7 Test that the procedure works with ordinary, common data

Valid data 7

–3 and –4 Test that the procedure works with negative values

Valid data –3

2 and 2.5 Test that the procedure works with real numbers

Valid data 2.5

3 and 3 Test what happens when the two inputs are equal

Valid data 3

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

88 DJM

ADDITIONAL NOTES:

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

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

DJM 89

ADDITIONAL NOTES:

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 programmer’s 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.

www.revision-notes.co.cc

CPT2: Programming Techniques and Logical Methods

90 DJM

ADDITIONAL NOTES:

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.

www.revision-notes.co.cc