resourcescsecit.weebly.com file · Web viewObjective 3.1: Distinguish between low-level and...

26
Section 3: Program Implementation Objective 3.1: Distinguish between low-level and high-level programming languages. Content Machine language, Assembly language, Pascal, C, etc. Low-level languages These are languages that are machine dependent. Different brands of computers use different program codes. The program code written for a particular brand of CPU will not run on another brand of CPU as the codes are written with the internal operations and architecture of a particular CPU in mind. Examples of low-level languages are Machine language and Assembly language. High-level languages These are languages that are machine independent. They are not specifically written for any one brand of computer. The program code written on a particular machine is not limited to execution on that machine only but can also run on other similar machines. Examples of high-level languages are Pascal, BASIC, C, etc. Objective 3.2: Distinguish among the different generations of programming languages. Content Characteristics of first through to fifth generation languages First Generation Languages (1GL) These are low-level languages. They are called machine language and are written using 1’s and 0’s i.e. binary code. It is the only program code that the CPU understands and can obey or execute directly without the need to translate it. E.g. of code 1101 1101 1011 1011 Characteristics of 1GLs It is the fastest to execute because it is already in the language that the computer understands. It is difficult to decipher It is easy to make mistakes in the sequence of 1’s and 0’s It is time consuming or tedious to write 1

Transcript of resourcescsecit.weebly.com file · Web viewObjective 3.1: Distinguish between low-level and...

Section 3: Program Implementation

Objective 3.1: Distinguish between low-level and high-level programming languages.

Content Machine language, Assembly language, Pascal, C, etc.

Low-level languagesThese are languages that are machine dependent. Different brands of computers use different program codes. The program code written for a particular brand of CPU will not run on another brand of CPU as the codes are written with the internal operations and architecture of a particular CPU in mind. Examples of low-level languages are Machine language and Assembly language.

High-level languagesThese are languages that are machine independent. They are not specifically written for any one brand of computer. The program code written on a particular machine is not limited to execution on that machine only but can also run on other similar machines. Examples of high-level languages are Pascal, BASIC, C, etc.

Objective 3.2: Distinguish among the different generations of programming languages.

Content Characteristics of first through to fifth generation languages

First Generation Languages (1GL)These are low-level languages. They are called machine language and are written using 1’s and 0’s i.e. binary code. It is the only program code that the CPU understands and can obey or execute directly without the need to translate it.

E.g. of code 1101 1101 1011 1011

Characteristics of 1GLs It is the fastest to execute because it is already in the language that the computer

understands. It is difficult to decipher It is easy to make mistakes in the sequence of 1’s and 0’s It is time consuming or tedious to write It is machine dependent Programming becomes more difficult as the complexity of the program increases

Second Generation (2GL)These are also low-level languages. They are called Assembly language and are written using mnemonic codes- short codes that suggest their meaning and are therefore easier to remember. These codes represent operations, addresses that relate to main memory and storage registers of the computer.

1

E.g. of code LDA A, 20ADD A, 10STO B, ANOP

Characteristics of 2GLs It is easier to write than machine language It is machine dependent It is easy to decipher

Third Generation Languages (3GL)These are high-level languages. This generation of languages was designed so that it is even easier for humans to understand. They are procedural languages which use simple instructions, written in English, to tell the computer step by step how to solve a problem. A compiler is used to convert the English–like statements to machine language.

Characteristics of 3GLs It uses English words and symbols, and is even easier to write It is machine independent

Examples of 3GLs are Pascal, BASIC (Beginner’s All-purpose Symbolic Instruction Code), C, C++, FORTRAN (Formulator Translator), COBOL (Common Business Oriented Language) and Java.

Fourth Generation (4GL)These are also high-level languages. Unlike 3GLs, these are non-procedural languages which let you perform computer operations without having to specify all the steps involved. They have built-in methods that can achieve certain goals. 4GLs must be selected to fit a particular application, whereas 3GLs tend to be more general purpose. They are usually applied in the following types of jobs:

Database creation and programming Report generation GUI creation

Some examples of 4GLs are Visual Basic, PowerBuilder, Delphi, and SQL.

Fifth Generation (5GL)These are high-level languages. This generation is essentially 4GLs with a knowledge base. They are designed to build programs that help the computer solve specific problems based on constraints and conditions. They are applied in expert systems, artificial intelligence research and natural language systems. Examples of 5GLs are Prolog, OPS5 and Mercury.

Objective 3.3: List the sequence of steps associated with implementing a program.

Content Create source code, compile, linking, executing, maintain program

2

Steps in Implementing a Program:

Create source code Compile source code Link the modules Run/execute program Maintain program

1. Creating the source code involves:

The translation of the algorithm into a programming language

This process is done manually on paper

The resulting Pascal program is entered into the computer using a suitable text editor

The source code is then stored in a file with the appropriate extension (.pas)

At the completion of this process, a complete Pascal program is ready for compilation.

2. Compiling the source code involves:

The process of translating the source code into object code.

Object code is the machine language equivalent of the source code.

During the compilation process the syntax of the source code is checked to ensure conformity with the rules of the language.

If syntax errors are found, these are reported. Syntax errors result in incomplete compilation. The errors must be corrected and the program must be re-compiled. This process is repeated until the code is free of syntax errors.

The primary purpose of the compiler is to translate the source code into object code.

3. Linking the Modules

This is where special operations code is added to the object code.

A compiled object program is not executable by itself. It needs to be combined with other system modules to form an executable image that can be loaded into memory.

The process of linking the module is done by a link editor or link-loader.

The resulting executable module is then loaded into memory where it can then be executed.

4. Program Execution

3

This is when the instructions in a program get carried out.

The program is dispatch to the CPU and the control unit interprets each instruction and pass it to the appropriate unit for execution

During execution, if any run –time errors are detected, the program will terminate prematurely.

5. Maintaining the program involves:

Making periodic modifications to the program when the requirements change. For example, if the hourly rate for an employee changes, due to pay increase, then such a program would have to be modified to reflect the change in the hourly rate.

A program written in any programming language is called the source code. The source code has to be translated into machine code before it can be executed. A translator is needed for this purpose. The machine code is saved as an executable file. The executable program file is called the object code.

A diagram Outlining the Compilation Process

There are two types of computer translators:

1. Interpreters

2. Compilers

Difference Between an Interpreter and a Compiler

An interpreter translates and executes one instruction at a time as it is encountered.

Advantages It translates one instruction at a time, therefore it uses a minimum amount of the

computer’s memory

It is also helpful in the debugging process, as the interpreter can relate error messages to the instruction being executed.

4

Source Code Compiler Object Codes

Disadvantage The interpreter takes longer to run a program as time is spent interpreting the source

code every time the program needs to be run.

CompilerA compiler translates the entire program (source code) to machine code, and then the machine code is executed. The translated codes are known as object codes.

Advantage It can be executed faster than when using an interpreter, as the object codes are saved

and can be run at any time

Disadvantage

As the entire program is translated to object code, it uses much more of the computer’s memory.

Objective 3.4: Explain commonly used terms and concepts in programming.

Content Loading, testing, debugging, syntax errors, logic errors, run-time errors, dry run,

test data.

Commonly Used Terms and Concepts in Programming

Loading – is reading a program from the hard disk into main memory (RAM)

Testing - a completed program must be tested for errors to prevent crashing or stalling. The programmer must make sure the program works for any correct input data that the user gives it. The testing phase is to detect any problems in the program. Dry runs and computer testing could reduce the chance of error, before releasing the program to its final users.

Dry runs/Manual testing - a manual traversal of the logic of a program. After the development of a program the programmer should examine the code to see how it would run.

A dry run is carried out when the action of an algorithm is examined with a set of input values.

A trace table is a useful tool for a dry run, to check how the program would behave.

Test Data – a wide range of data should be used to test a program. This data should include normal data values and extreme values e.g. large, small and negative numbers. Using this wide range would help detect which values might cause a program to fail.

Debugging – is the process of correcting or removing errors from a program before it is put into operation.

Program Errors – A program error is a mistake/error in a program and is also known as a bug.

5

During program development, three types of errors may be encountered as followed:

1. Logic errors

2. Syntax errors

3. Run-time errors

1. Logic errors – arise when the sequence of the instructions is not correct and there are flawed comparisons and selection statements.

For example, let’s suppose we wanted to print the names of all girls who are under the age of 18 and we wrote the following program:

.

.If (gender = F) and (age <= 18) then

Writeln(name);

This code would result in the printing of the names of girls who are 18 as well as those who are under 18. This is because in the if statement, we used <= instead of = . This is a common error in the logic that will give undesirable results.

2. Syntax errors – occur when the source code has not been written in accordance with the rules of the programming language. For example, if we omit to terminate an assignment statement with a semi-colon. The following statement would result in a syntax error during compilation:

total:=total + X

or

if we used a reserved word incorrectly, such as in:

var := a + b;

Syntax errors can be easily located and corrected as the compiler usually issue messages which identify the location and cause of the errors.

3. Run-time errors – are generated during execution of the program. They result when the processor encounters an instruction that violates the processing rules. For example, if we had an instruction that attempts to divide by 0, such as:

Number:=1;Number:= Number - 1;Answer := total/Number; {illegal}

6

The last statement would generate a run-time error as an attempt is being made to divide by a value of 0.

Writing a Pascal Program

A Basic Pascal Program Layout

Reserved words

Keywords with a special meaning and purpose in Pascal.

List of reserved words:

7

program <program name>;

const <constant name> = <value>;

var <variable name>: <data type>;

Begin

End.

Program header

Declaration of variables

Declaration of constants

Program body

absolute and array asm begin case const constructor destructor div do downto else end

file for function goto if implementation in inherited inline interface label mod nil not

object ofon operator or packed procedure program record reintroduce repeat self set shl shr string

then to type unit until uses var while with xor

8

Data types used in Pascal: Integer: for storing whole numbers Real: for storing decimal numbers String: for storing a set of characters Boolean: for storing ‘true’ or ‘false’ Char: for storing characters

Identifiers

Names made up by the programmer for variables etc. The rules for naming identifiers are:

It must start with a letter or underscore e.g. R, sum , _total They can be made up of any combination of letters, digits or underscore e.g. _xyz,

turns_per_game The length of an identifier cannot exceed 31 characters Spaces are not allowed in an identifier Reserved words cannot be used as an identifier

Suggestions for Naming Identifiers

Write variable names in lowercase Begin constants with an uppercase letter If identifiers consist of more than one word, start second or subsequent words with an

uppercase e.g. numberOfThrows

Objective 3.5: Declare elementary data types.

Objective 3.6: Declare variables and constants.

Declaring constants

Constant declarations must come immediately after the program heading and before the

variable declarations. Constants are declared in Pascal by specifying the keyword const

followed by an identifier, an equal sign (=), a constant value (numeric, character, string, or

Boolean) and a semicolon. If more than one constants need to be declared, do not repeat the

keyword const, simply list each identifier and assign the constant value to them.

E.g. const pi = 3.142;

ans =’TRUE’;

val =’A’;

Declaring variables and their data types

Variables must always be declared in the variable declaration section. Variables are declared in

Passcal by specifying the keyword var followed by an identifier, a colon and the data type.

Variables of the same type can be listed in the same line separated by commas. Variables of

different data types are to listed on separate lines E.g.

9

var num1, num2 : integer;

average : real;

ans : char;

Punctuation

Every Pascal statement (except begin) is terminated by a semi-colon. The last statement in the

program (that is the end statement) is terminated by a period (full stop).

BEGIN and END delimiters

The BEGIN/END keyword pair is used to delimit the body of the program as well as logical

blocks within the program. For example, when multiple statements are to be executed within a

while loop. N.B. For every BEGIN in a program, there must be corresponding END statement.

Objective 3.7: Manipulate data.

Arithmetic Operators

+ add div divide (throws away the remainder in result)

- subtract mod remainder

* multiply

/ division

Precedence of operators

Same as in Math; multiplication and division before addition and subtraction. When two operators have the same precedence evaluate from left to right unless specified otherwise by brackets.

The assignment statement (:=)

There is no space between the colon and equal sign. It is used as:

10

<variable := <value>

Or

<variable>:= <calculation statement>

Writeln and write

Used to produce output.

Writeln prints output and the cursor moves to the next line. Write produces the output and the cursor stays on the same line. Write is suitable when prompting the user for data as the program waits on the same line for the user to type in the data requested.

Readln and read

Used to get data entered by the user.

When the read and readln commands are executed, the computer anticipates the variables in the order listed and the types declared. If an incorrect type is entered an error message is displayed. E.g.

The computer expects that and integer would be entered first and a decimal number next.

read and readln differ in where the data pointer is place after a data item is read. The read command places the pointer in the space just after the data item whereas readln places the data pointer on a new line. Therefore be careful how readln is used. Consider the following data entries and statements:

11

writeln(<variable name>);

write(<variable name>);

Or

writeln(<variable with string constant> );

write(<variable with string constant>);

readln(<variable name>);

read(<variable name>);

or

readln(<variable name>, <variable name>););

read(<variable name>, <variable name>););

Var num:integer;

Total:real;

Read( num, total);

4000 7.99 8

3575 10 44

5600 25.0 1

Readln(item);

Readln(price);

Readln(quantity);

The intention is to store 4000 in item, 7.99 in price and 8 in quantity and so on. Based on the sequence of statements above this will not happen. Instead item will store 4000, price will store 3575 and quantity will store 5600.

To do what was intended, either of the following is required:

Read(item);

Read(price);

Read(quantity);

Or

Readln(item, price, quantity); (repeated three times)

Objective 3.8: Use control structures.

Selection statements/Conditional branching

In Pascal, the IF…THEN construct is written as follows

IF (condition) THEN e.g. IF (num > 20) THEN

<statement>; ans := num/5;

OR

IF (condition) THEN e.g. IF (age > 18) THEN

BEGIN BEGIN

<statement>; status:= ‘adult’;

<statement>; admit:= TRUE;

END; END;

12

Repeat or Looping Statements

These use the FOR, WHILE and REPEAT..UNTIL constructs. These constructs allow us to repeat certain parts of a program a number of times without having to write them several times. For each of these constructs it is necessary to keep a count of how many times the instructions are repeated. The counting or iterations involves increasing the value of a counter variable by a fixed number every time the instructions are repeated.

Loops

The group of statements/instructions to be repeated is called a loop. There are two (2) types:

1. A finite loop – where the number of times a repetition is to be made is known.

2. An infinite loop – where the instructions are repeated an unspecified number of times.

To exit a loop a sentinel, terminal or end-of-data value is used. A sentinel value is a lookout value such that if the data being entered ever becomes equal to the sentinel value, the computer exits the loop. This value can be entered by the user or the computer can be programmed so that a certain condition can be met to trigger the end of the loop.

WHILE loopThis construct is used when you do not know beforehand how many times a statement within a block needs to be repeated. In this loop the computer executes the instruction to be repeated for as long as a given condition is TRUE. It checks the conditions first and will loop while the condition is true and ends when it is false.

Syntax:

13

While (<condition>) DoBegin

<statement(s) to be carried out if condition is TRUE>;

End;

e.g.

Counting in a WHILE loop

To keep a count in a WHILE loop the following syntax is used:

When a count is being kept, the counter variable MUST be initialized (set) to a starting value, usually zero (0), before the instructions are executed.

Syntax to initialize a variable:

14

Program Read100Nums;Uses wincrt;Var

number: integer;Begin

Write(‘Enter a number’);Read (number);While( number<=100) DoBegin

Write(‘Enter a number’);Read (number);

End;Write(‘Over the limit’);

End.

<counter variable>: = <counter variable> + < increment value>

<counter variable>: = 0;

E.g. This program uses a counter to write “Hello” five (5) times

FOR loop

This construct is used when the number of times a set of instructions has to be repeated is known.

Syntax:

e.g

If more than one statement has to be repeated, a BEGIN & END must be use to mark the beginning and end of the block of code.

15

Program hello5;

Uses wincrt;

Var

Count: integer;

Begin

Count := 0;

While (count<5) Do

Begin

Writeln(‘Hello’);

Count:= Count +1;

End;

Readkey;

End.

FOR <counter variable> :=<start value>To <end value or end variable> Do

<statement to be carried out if condition is TRUE>;

FOR num := 1 To 5 Do

Writeln(‘Hello’);

Syntax:

E.g.

The FOR loop can be used to count in descending order. To do so, the reserved word DOWNTO is used instead of TO

Syntax:

E.g.

N.B. It is possible to increment or increase the counter variable by more than 1 for each repetition. To do so, the reserved word STEP is used.

16

FOR <counter variable> :=<start value>To <end value or end variable> DoBEGIN

<statement 1>;<statement 2>;<statement 3>;

END;

FOR count := 1 To 5 DoBEGIN

Sum := count + count;Writeln(count, ‘ + ’, count, ‘ = ‘,sum;

END

FOR count := 5 DOWNTO 1 Do

Writeln(count);

FOR <counter variable> :=<start value>DOWNTO <end value or end variable> Do

<statement to be carried out if condition is TRUE>;

Syntax:

E.g.

Repeat .. Until Loop

This construct is similar to the WHILE loop, in that, it can be used when you do not know beforehand how many times a statement within a block needs to be repeated. The difference between the WHILE and the REPEAT..UNTIL is that, the computer executes the instruction(s) to be repeated for as long as a given condition remains FALSE and ends when it becomes TRUE. Because of this, the instruction(s) to be repeated is/are always executed at least once. Therefore, be very careful when using it. Syntax:

N.B. The reserved words REPEAT and UNTIL replaces the BEGIN and END used in the other loops.

17

FOR <counter variable> :=<start value>To <end value or end variable> Step <increment value>Do

<statement to be carried out if condition is TRUE>;

FOR even_No := 2 To 20 STEP 2 Do

Write(even_No);

Repeat

<statement(s) to be carried out if condition remains FALSE>;

Until (<condition>) ;

e.g Problem:

Write a program to allow a user to enter numbers. When his total crosses 100 display “over the limit”.

18

Program overTheLimit;

Uses wincrt;

Var

number , Total: Integer;

BeginTotal:=0;Repeat

Write(‘Enter a number ‘);Readln( number);Total := Total + number;

Until (Total >100);Write(‘Over the limit’);

End.

Objective 3.9: Manipulate data in a list.

ArraysArrays are used to store values of the same type as one variable e.g. the names of 100 countries. If we did not have arrays we would have to create a 100 variables to store each name. This is very tiring, cumbersome to manipulate and time consuming.

An array is a single variable with multiple locations. Each location stores one element/value. To refer/access an element a subscript is used. For example, country[5]. 5 is the subscript and country[5] allows the program to refer to the country name stored in that location.

Declaring an arrayJust like regular variables and constants, an array must be declared before it is used.

Syntax: var <arrayName> : array[1..<no. of values to be stored>] of <data type>;

e.g. var country : array[1..100] of string;

Referring to a value in an array

Syntax:<arrayName>[<subscript>]

E.g. country[1] refers to the 1st valuecountry[2] refers to the 2nd valuecountry[3] refers to the 3rd value

::

country[99] refers to the 99th valuecountry[100] refers to the 100th value

N.B. it is an error to refer to a subscript that is out of the range e.g. country[105]

A subscript can be a constant e.g. 6, a variable e.g. max, or an expression n + 1

Storing values in an array

If a value has to be set to a specific location in an array, the following methods can be used:

Method #1

Syntax:

<arrayName>[<subscript>] := <value>;

19

E.g. country[1] := ‘Trinidad and Tobago’;

country[2] := ‘St. Kitts’;

:

:

Country[100] := ‘Guyana’;

This method is very time consuming, therefore it is better to use the following method:

Method #2

This method uses a variable for the subscript and a FOR loop to increment the value of the variable.

Syntax:

For <counterVariable> := 1 to <no. of values to be stored> Do

Read (<arrayName>[< counterVariable >]);

E.g. For count:= 1 to 100 Do

Read (country[count]);

Writing from an array

To write a value store in a specific location the following syntax is used:

Syntax:

Write(<arrayName>[<subscript>]);

E.g. Writeln (country[6]);

If you need to print all values in an array use the following syntax:

For <counterVariable> := 1 to <no. of values to be stored> Do

writeln(<arrayName>[< counterVariable >]);

E.g.

For count:= 1 to 100 Do

writeln (country[count]);

Problem: Write a program to print the name of a day, given the number of the day.

20

Solution:

Program nameOfDay;

Uses wincrt;

Var day: array[1..7] of string;

Num: integer;

Begin

Day[1] := ‘Sunday’;

Day[2] := ‘Monday’;

Day[3] := ‘Tuesday’;

Day[4] := ‘Wednesday’;

Day[5] := ‘Thursday’;

Day[6] := ‘Friday’;

Day[7] := ‘Saturday’;

Write(‘Enter a day from 1 to 7: ‘);

Readln(num);

Writeln(‘Today is ‘, Day[num];

Readkey;

End.

Traversing an array

Traversing an array involves accessing all elements in the array from first to last, one by one. This is accomplished using the FOR loop.

Syntax:

For( <counterVariable> := 1 to <final location in array> )Do

<statement(s)>;

E.g. For (index: = 1 to 6) Do

write (num [index]* num [index]);

Searching an array (linear search)

Searching an array involves traversing the array until you find the location of the element you require and retrieving it.

A linear search requires that each element of the array is compared with the given item to be searched for, one by one.

21

E.g. index: = 0;

found: = ‘no’;

Repeat

index: = index + 1;

If (names [index] = ‘Roger’) then

found: = ‘yes’;

until (found = ‘yes’);

Objective 3.10: Perform checks and tests on programs to verify correctness.

Testing and Debugging Techniques

Once a program is developed or written, the next step is to check that it is doing what it was designed to do, and is doing so correctly. There are two types of testing:

Manual testing/dry running: executing the program manually by using input values for variables and recording what takes place after each instruction is executed.

Computer testing: using the computer to run the program with suitable test data (correct and incorrect) to deal with all possible kinds of conditions. The results generated by the computer are then compared with the expected solutions. If the expected and actual results do not match, then the program has a logic error.

Objective 3.11: Write documented programs.

Documenting a Program

Documentation is the written guidelines that help program users to operate the program.

Once Comments in Pascal

Single line comments can be put in opening and closing brackets with opening and closing asterisk e.g.

(* This is a single line comment. *)

or

(* EndFor*)

Multiple line comments are enclosed in opening and closing curly brackets e.g.

{These are multiple

line comments.

N.B. Always remember to close comments.}

22