You are on page 1of 27

Information Technology PRPROGRAM IMPLEMENTATION

Revision notes  Page| 89


Information Technology PRPROGRAM IMPLEMENTATION

On completion of this unit, students should have an understanding of how to convert algorithms to programs using structured
programming techniques.

Section A: Programming languages

Section B: Program implementation

Revision notes  Page| 90


Information Technology PRPROGRAM IMPLEMENTATION

3.1.1: Low-level programming languages

A low-level language is a programming language


that is machine dependent. A machine dependent
language runs on only one particular type of
3.1: Computer Programs and computer. Two types of low-level languages are
machine languages and assembly languages.
Programming languages.
High-level languages often are machine
This section distinguishes between low-level and high level
programming languages. independent. A machine-independent language can
run on many different types of computers and
A computer program is a series of instructions operating systems.
that directs a computer to perform tasks. A
computer programmer, often called a developer,
creates and modifies computer programs. To create Machine language
a program, programmers sometimes write, or code,
a program’s instructions using a programming Machine language, known as the first generation
language. A programming language is a set of of programming languages, is the only language the
words, abbreviations, and symbols that enables a computer directly recognizes. Machine language
programmer to communicate instructions to a instructions use a series of binary digits (1s and 0s)
computer. Other times, programmers use a program or a combination of numbers and letters that
development tool to create a program. Two types of represents binary digits. The binary digits
languages are low-level and high-level. correspond to the on and off electrical states.

Coding in machine language is tedious and time-


consuming.

Assembly language

With assembly language, the second generation of


programming languages, a programmer writes
instructions using symbolic instruction codes.

Symbolic instruction codes are meaningful


abbreviations. With this language, a programmer
writes abbreviations such as A for addition, C for
compare, L for load, and M for multiply.

Assembly languages also use symbolic addresses. A


symbolic address is a meaningful name that
identifies a storage location.

Revision notes  Page| 91


Information Technology PRPROGRAM IMPLEMENTATION

Assembly languages can be difficult to learn. In


addition, programmers must convert an assembly 3.2: The generation of
language program into machine language before the programming languages.
computer can execute, or run, the program. That is,
the computer cannot execute the assembly source This section distinguishes among the different generation of
programming languages.
program. A source program is the program that
contains the language instructions, or code, to be Computer programs are written in accordance with
converted to machine language. To convert the the rules and statements of a particular
assembly language source program into machine programming language. Many programming
language, programmers use a program called an languages have been developed throughout the
assembler. years. These languages are classified into:
One assembly language instruction usually equates
 First generation
to one machine language instruction. In some cases, Low-level languages
however, the assembly language includes macros.
 Second generation
An assembly language macro generates many
machine language instructions for a single assembly  Third generation
language instruction. Macros save the programmer
time during program development.  Fourth generation High-level languages
Today, assembly languages primarily are used to
 Fifth generation
increase the performance of critical tasks or to
control hardware.
3.2.1: First Generation
3.1.2: High level programming languages Programs that are written in the first-generation
language consist of a series of 0s and 1s. This
The disadvantages of machine and assembly (low-
generation has advantages as well as disadvantages.
level) languages led to the development of
procedural languages (high-level). In a procedural
language, a programmer uses a series of English- Advantages
like words to write instructions.

As with an assembly language program, the  Fast: Programs written in machine language
3GL code (instructions) is called the source takes shorter time in execution.
program. Programmers must convert this source
program into machine language before the  Translator free: Programs are directly
computer can execute the program. This translation understood by the computer; no translator is
process often is very complex, because one 3GL needed to interpret the code.
source program instruction translates into many
machine language instructions. For 3GLs,  Efficient use of main memory
programmers typically use either a compiler or an
interpreter to perform the translation.

Revision notes  Page| 92


Information Technology PRPROGRAM IMPLEMENTATION

by mnemonics, and memory addresses in


Disadvantages
machine languages are replaced by variable
names which are easier to remember.
 Machine dependency: Programs written for
one type of computer will not work on another
computer. Disadvantages

 Complex Language: The programmer has to


 Machine Dependent: Programs written for
remember the binary code for all Operations,
one type of computer will not work on another
and the addresses of all the data items, it is
computer.
very difficult task. Programmers had to have a
detailed knowledge of the internal operations  Less Efficient: A program written in assembly
of the specific type of CPU they were using. language takes more execution time compared
to machine language.
 Tedious: Any modification in machine
language results in series of changes, in other   Translator Required: An extra program
words modification in machine language is a assembler is required for assembly language to
difficult task. convert onto machine language.

 Error-Prone: It requires a super human effort


to keep track of the logic of the problem and, 3.2.3: Third generation
therefore results in frequent programming
errors. Programming errors are difficult to find The high-level languages were developed in order
and correct (‘debug’). to overcome the platform-specific problem and
make programming easier. The high-level
3.2.2: Second generation languages are English-like and easy to learn. There
are over one hundred high-level languages. The
Programs that are written in the first-generation popular languages used today are:
language consist of a series of 0s and 1s. This
generation has advantages as well as disadvantages.  COBOL (COmmon Business Oriented
Second-generation language is called assembly Language)
language.
  FORTRAN (FORmula TRANslation)
Advantages
  BASIC (Beginner’s All-purpose Symbolic
Instructional Code)
 Easier to maintain: Assembly languages are
easy to modify.   Pascal (named for Blaise Pascal)

 Less error-prone: Less error is made,


if introduced easier to find.
  Ada (named for Augusta Ada Lovelace
 Easy to understand and use: Operation codes the first lady programmer)
in machine language are replaced
Revision notes  Page| 93
Information Technology PRPROGRAM IMPLEMENTATION

 Machine Independent: These languages are


  C (whose developer designed B first) machine independent.

 Visual Basic (Basic-like visual language  Built-in Functions: Libraries of subroutines


developed by Microsoft) are incorporated and used in many other
programs.
  Delphi (Pascal-like visual language developed
by Borland)  Easy Documentation: They provide better
documentation.
  C++ (an object-oriented language, based on C)
 Low Development Cost: More than one low-
Each of these languages was designed for a specific level language instructions are reduced to
purpose. single high-level language instruction.

A program written in a high-level language is called  Readability: The writing of source code in
source code. Since a computer cannot understand HLL does not require the knowledge of the
source code, a program called a compiler or internal working of the computer.
interpreter is used to translate the source program
into a machine language program called an object
program. The object program is often then linked Disadvantages
with other supporting library code before the object
can be executed on the machine.  Less Efficient: The HLL are less efficient as
far as computation time is concerned.
The figure below shows the process of compiling,
linking, and running a program.  Poor Control on Hardware: Programmers do
not have to know the internal architecture of
computer. As a result program written in HLL
cannot completely use the internal structure.

3.2.4: Fourth generation

Fourth generation languages are simply English like


syntax rules, commonly used to access databases.
Advantages These languages are non-procedural languages. The
non-procedural method is simply to state the needed
 Easy to Learn: These are easier to learn than output instead of specifying each step one after the
assembly language. These require less time to other to perform a task. In other words, the
write. These have extensive vocabulary, computer is instructed what it must do rather than
symbols and sentences. how a computer must perform a task.
4GLs have minimum number of syntax rules.
 Easier to Maintain: As compared to LLL Hence, common people can also use such languages
these languages are easier to maintain. to write application programs. This saves time and
allows professional programmers to solve

Revision notes  Page| 94


Information Technology PRPROGRAM IMPLEMENTATION

more complex tasks. The 4GLs are divided into


three categories:

 Query Languages: They allow the user


to retrieve information from databases by
following simple syntax rules. 3.3: Implementing a program
 Repot Generators: They produce customized This section lists the sequence of steps associated with
report using data stored in database. implementing a program

 Application Generator: With application The steps associated with implementing a program
generators, the user writes programs to allow is broken into:
data to be entered into database.
4GLs are designed to be user friendly and 1. Creating source code
interactive, and to help you quickly develop an
application package. In general such products 2. Compiling
are marked by:
3. Linking and executing,
 Non-procedural programming code;
4. and maintaining program.
 A simple query language;

 Centered around database.
3.3.1: Creating source code (using Pascal)

The source code should be written by the language


3.2.5: Fifth generation which is interpreted by the assembler or the
compiler. When using MPASM, an assembly
These languages have capability to process natural language is used. When you write a source code
language. The computer will be able to accept, with the C language, the compiler of the C language
interpret, and execute instructions in a native or is necessary.
natural language of the end-users. The users will be
free from learning any programming language to The source code file can be created using any
communicate with the computers. Programmers ASCII text file editor.
simply type the instructions or tell the computer by
the way of microphones what it needs to do. These C++, COBOL, Pascal, BASIC, and other
languages are closely linked to artificial programming languages are English-like; a
intelligence and expert systems. computer only understands machine language. In
order for a computer to "execute" or "run" a
program, the program must be translated into the
machine language. There are several ways of doing
this, including assembling, interpreting, and
compiling.

Revision notes  Page| 95


Information Technology PRPROGRAM IMPLEMENTATION

The Pascal programming language is a high level The var Segment


language that has its own syntax rules and grammar
rules. As you go along with the lessons, you must The reserved word var marks the start of the
note what you can do and what you cannot do in segment which defines all the variables which will
writing a Pascal program. be used within the program. A variable is a place
where PASCAL will put a piece of information we
A Pascal program is broken up into several
are interested in. This information may be changed
segments; broadly speaking first you define the
as the program runs, depending on the information
form of the data you are going to use and then you
which is being processed at the time. We do not
write the program which works on it: for example:
need to worry how the variable is stored, PASCAL
looks after all that.
Program Lesson1_Program1;
Var Variable Names
number : integer;
Begin The name of a variable can contain digits, letters or
Readln(number) ; the "_' character and it must begin with a letter, i.e.
X28 is a valid variable but 28X and NoOf\ are not.
number := number * 2;
In the above example the variable number has the
Writeln(number); type integer which is one of the standard types
Readln; which PASCAL provides.

End.
The Instructions Segment
PASCAL recognizes particular reserved words in
The instructions segment tells PASCAL what to do
certain positions in the program, according to the
syntax of the language. You have to be careful with the data structures. It starts with the reserved
when writing your program that you do not use word begin. The first thing that the program does is
reserved words in the wrong context, for example call Readln. Readln is a standard procedure which
consider the implications of a program with the is built into PASCAL. Note that Readln is not a
name begin! reserved word; it simply shows that the writers of
the PASCAL system have recognized that users
need a way of getting information into and out of
The Program Heading
programs. Instead of building this into the PASCAL
standard a number of procedures have been defined
The program heading gives the program a name and which do the donkey work.
tells the PASCAL system what communication it
will have with the world outside. You can pick
whatever name you want, obviously you will
choose one which reflects what the program does.

Revision notes  Page| 96


Information Technology PRPROGRAM IMPLEMENTATION

Another very simple program is shown below:  changes to the source code and correct errors in the
program.

Program Lesson1_Program2; A compiler translates an entire program before


Begin executing it. An interpreter, by contrast, translates
Write('Hello World.'); and executes one statement at a time.

Write('Prepare to learn PASCAL!!');


An interpreter reads a code statement, converts it to
Readln; one or more machine language instructions, and
End. then executes those machine language instructions.
It does this all before moving to the next code
statement in the program. Each time the source
The above program is now written in a Pascal
program runs, the interpreter translates and executes
programming language.
it, statement by statement. An interpreter does not
produce an object program.

3.3.2: Compiling

A compiler is a separate program that converts the


entire source program into machine language before
executing it. The machine language version that
results from compiling is called the object code or
object program. The compiler stores the object
code on storage media for execution later. While it
is compiling the source program into object code,
the compiler checks the source program for errors.
The compiler then produces a program listing that
contains the source code and a list of any errors.
This listing helps the programmer make necessary

Revision notes  Page| 97


Information Technology PRPROGRAM IMPLEMENTATION

3.3.3: Linking and executing the program.  Dry run: This is a form of testing where the
programmer goes through the program,
Successful compiling does not guarantee either statement by statement doing each operation
correct logic (necessary to get correct "answers") or by hand as it would be done by the computer.
nice input/output. It's the programmer's This is a long process but is a good method of
responsibility to check these matters. detecting logical errors in a program.

The screen below shows the running program after  Debugging: This is the process of testing,
execution. locating and correcting mistakes by running
the program.

 Syntax errors: These are errors reported by


the compiler, interpreter or assembler when
the rules of the programming language are not
obeyed. All language has its rules and
regulations and must be strictly obeyed.

 Logical errors: This error occur when the


3.3.4: Maintaining the program. expected results of a program is not met.
This is the program is not producing the
A compiler is a separate program that converts the correct result.
entire source program
3.4.2: Terms associated with running a
program
3.4: Commonly used terms and
 Source Code: These are programs written in
concepts in programming either high-level or assembly language.
This section explains the commonly used terms and concepts
in programming  Object Code: A machine code program is
called object code (programming instruction
in the form of 1 and O's)
3.4.1: Terms associated with testing data
 Loading: The process of transferring programs
 Testing: This is the process of checking a
and data from secondary storage to
program for errors.
primary memory. When you run/execute a
 Test data: This is data that is used for input program it is loading into primary
into a program to ensure that the program is memory/RAM which is also called main
producing the correct result or to assist in memory.
detecting logical errors. Test data should
 Compiler: This is a set of system software
include all variation and should test all logical
programs written to translate high-level
paths in a program.
language to machine codes. The entire program
is compiled before any execution takes
Revision notes  Page| 98
Information Technology PRPROGRAM IMPLEMENTATION

place. Each language has its own compiler. At 2147483647


the end of compilation an object code is String A combination of characters
produced and saved. Thus a program once
compiled does not need to be compiled each
time it is run.

 Interpreters - is a set of system software 3.6: Variables and constants


programs that is design to translate and execute
high-level languages. It translates and execute This section explains the elementary data types
one statement before translating and
executing the next statement. No object code is Variables are defined within the var segment of the
produced as a result it must perform the program. All variables must be declared before they
translation process each time the program is are used. If, during a program, you refer to a
run. variable which does not exist - perhaps because you
misspell it - the PASCAL compiler will detect this
 Assembler - is a set of programs used to and flag an error.
translate a program written in assembly
language to machine. Apart from variables, there are also items in the
program which are referred to as 'constants'. Unlike
 Run-time error - These errors occur as the variables, constants keep their value or string
program compiles or 'run'. Usually due to unchanged for the whole program.
unexpected events such as division by zero, or
lack of memory for the computer to
manipulate the data.
3.6.1: Declaration of variables and
constants
3.5: Elementary data types Declaration statements are used to announce the
Variables and Constants that are to be used in the
This section explains the elementary data types program as well as the appropriate Data Type
format they will take.
Data Range of values which the variable
type is capable of storing
1. Declaration of variables
Integer Whole numbers from -32768 to 32767
Byte The integers from 0 to 255
Floating point numbers from 1E-38 to var
Real
1E+38 Identifier1, Identifier2 : Data Type ;
Can only have the value TRUE or
Boolean Identifier3 : Data Type ;
FALSE
Any character in the ASCII character
Char
set
Shortint The integers from -128 to 127
Word The integers from 0 to 65535
Longint The integers from -2147483648 to
Revision notes  Page| 99
Information Technology PRPROGRAM IMPLEMENTATION

Example 3.6.1: Declaration of variables


End.

Program Dec_Variables;
var
3.6.2: Assign initial values
value, counter, quantity : integer;
unit_price, total_amount : real; Assignment statements in programming are used
letter, symbol : char ; to give a value to a variable/constant. The
assignment statement can also change the value of a
first_name, las_name : string;
variable or constant.
Begin
variable_name := value;
End.
or
The ";" at the end of each declaration marks the end
variable_name := expression;
of it, and separates it from the next declaration (if
any).
Example 3.6.3: Assigning values
Note that you do not necessary have to declare all
the variables of a particular type in the same Program Assign_Values;
declaration statement.
Var
number: real;
Declaration of constants
Begin
number := 385.385837;
const
number := number + 467.8;
  Identifier1 = value1;
End.
  Identifier2 = value2;
  Identifier3 = value3;

Example 3.6.2: Declaration of constants

Program Dec_Constants;
Var
surname: String;
Const 
name = 'Victor';
age = 15;
Begin

Revision notes  Page| 100


Information Technology PRPROGRAM IMPLEMENTATION

Example 3.7.2: Arithmetic operation


3.7: Data manipulation
This section explains how to manipulate data; reading from Program Arithmetic_Operation;
and writing to variables, and arithmetic operations.
Var
Num1, Num2, Sum : Integer;
3.7.1: Use of Readln Begin
The readln statement is another reserved word for Readln(Num1);
input purposes, which enables the user to input a Readln(Num2);
number or text only i.e.: using the keyboard.
Sum := Num1 + Num2; {addition}
Example 3.7.1: Reading data into a variable End.

Program Inputting_data;
Var
3.7.3: Use of Write and Writeln
Num1, Num2 : Integer; In Pascal Programming, the write statement, when
Begin used, leaves the cursor where it is after output is
complete.
Readln(Num1); {inputting}
Readln(Num2); {inputting} In contrast, the writeln statement for output, the
compiler returns the cursor to the next line on
End.
screen.

3.7.1: Arithmetic operations Example 3.7.3: Outputting data.

The arithmetic operators in Pascal are: Program Outputting_Data;


Var
Operator Operation Operand Result Num1, Num2, Sum : Integer;

Real or
Begin
+ Addition Real or integer
integer Readln(Num1);
Subtraction or Real or
‒ negation
Real or integer
integer Readln(Num2);
Real or
* Multiplication Real or integer
integer Sum := Num1 + Num2;
/ Real division Real or integer Real Writeln(Sum); {outputting}
div Integer division integer integer Readln;
mod remainder integer integer End.

Revision notes  Page| 101


Information Technology PRPROGRAM IMPLEMENTATION

Example 3.7.4: Using screen prompts

Program Lesson1_Program3;
Var
Num1, Num2, Sum : Integer;
Begin {no semicolon}
Write('Enter the first number: '); {prompt}
Readln(Num1);
Writeln('Enter the second number: ');
{prompt}
Readln(Num2);
Sum := Num1 + Num2;
Writeln(Sum);
Readln;
End.

Example 3.7.5: Putting all together.

Program Lesson1_Program1;
Var
firstname, surname: string;
Begin
Write('Enter your name:');
Readln(firstname);
Write('Enter your surname:');
Readln(surname);
Writeln;{new line}
Writeln;{new line}
Writeln('Your full name is: ',firstname,'
',surname);
Readln;
End.

Revision notes  Page| 102


Information Technology PRPROGRAM IMPLEMENTATION

3.7.2: Logical operations


The three logical operators are AND, OR and NOT.
The operator NOT is applied first, followed by
AND and then NOT - again the order of application
can be modified by the use of parenthesis.

3.8: Control structures


This section explains the control structures.

Up until now all the programs written run in a very


simple way, i.e. they start at the first line and then
obey every single line up until the end. However
the real power of a computer program is that it can
change the way it executes according to the data
which it processes. PASCAL provides a number of
constructions which allow you to modify the way
programs run. These are:

  Decision making statements:


 IF-THEN
 IF-THEN-ELSE
 CASE

 Loop statements:
 WHILE
 REPEAT-UNTIL
 FOR

These general programming constructs are common


in every programming language.

Revision notes  Page| 103


Information Technology PRPROGRAM IMPLEMENTATION

3.8.1: Conditional branching Example 3.8.1: Demonstrating the if ‒ then

(decision making)
program If_Demo;
Most programs need to make decisions. var
The RELATIONAL OPERATORS, listed below, number, guess : integer;
allow the programmer to test various variables begin
against other variables or values.
number := 2;

Symbol Meaning writeln('Guess a number between 1 and


10');
= Equal to
readln( guess );
> Greater than
if number = guess then
< Less than
writeln('You guessed correctly!');
<> Not equal to
if number <> guess then
>= Greater than or equal to
writeln('Sorry, you guessed wrong.');
<= Less than or equal to
end.

The IF – THEN control There are times when you want to execute more
than one statement when a condition is true (or false
The format of IF-THEN control is as follows: for that matter). Pascal makes provision for this by
allowing programmers to group blocks of code
if condition_is_true then together by the use of the BEGIN and END
execute_this_program_statement; keywords.

Whether a semi-colon follows the end keyword


depends upon what comes after it. When followed
by another END (or END.), then it needs no semi-
colon.

Consider the following portion of codes:

Example 3.8.2: Demonstrating the if ‒ then

program If_Demo2;
var number, guess : integer;
begin
number := 2;

Revision notes  Page| 104


Information Technology PRPROGRAM IMPLEMENTATION

writeln('Guess a number between 1 and


10');
readln( guess );
if number = guess then
begin
writeln('Lucky you. It was the correct
answer.');
writeln('You are just too smart.')
end;
if number <> guess then
writeln('Sorry, you guessed wrong.');
end.

Example 3.8.3: Demonstrating the if ‒ then

program If_Demo3;
var
number, guess : integer;
begin
number := 2;
writeln('Guess a number between 1 and
10');
readln( guess );
if number = guess then
begin
writeln('Lucky you. It was the correct
answer.');
writeln('You are just too smart.')
end
end.

Revision notes  Page| 105


Information Technology PRPROGRAM IMPLEMENTATION

The If – then – else control begin


writeln('You guessed correctly. Good
The IF statement can also include an ELSE
on you!');
statement, which specifies the statement (or block
or group of statements) to be executed when the writeln('It may have been a lucky
condition associated with the IF statement is false. guess though')
end{no semi-colon if followed by an
Example 3.8.4: Demonstrating the if ‒ then ‒ else
else }
else
program If_Else_Demo;
begin
var
writeln('Sorry, you guessed wrong.');
number, guess : integer;
writeln('Better luck next time')
begin
end; {semi-colon depends on next keyword }
number := 2;
writeln('Guess a number between 1 and
10');
The CASE statement
readln( guess );
if number = guess then
The case statement allows you to rewrite code
writeln('You guessed correctly. Good which uses a lot of if else statements, making the
on you!') program logic much easier to read.
else
Consider the following code portion written using if
writeln('Sorry, you guessed wrong.') else statements,
end.

if operator = '*' then result := number1 *


program If_Else_Demo2;
number2
var
else if operator = '/' then result :=
number, guess : integer;
number1 / number2
begin
else if operator = '+' then
number := 2;
result := number1 + number2
writeln('Guess a number between 1 and
else if operator = '-' then result
10');
:= number1 - number2
readln( guess );
else invalid_operator = 1;
if number = guess then

Revision notes  Page| 106


Information Technology PRPROGRAM IMPLEMENTATION

Rewriting this using case statements, SELF TEST 3.8.1:

What is displayed when the following program is


case operator of
executed?
'*' : result:= number1 * number2;
'/' : result:= number1 / number2; program IF_THEN_ELSE_TEST (output);
'+' : result:= number1 + number2; var a, b, c, d : integer;
'-' : result:= number1 - number2; begin
otherwise invalid_operator := 1 a := 5; b := 3; c := 99; d := 5;
end; if a > 6 then writeln('A');
if a > b then writeln('B');
The value of operator is compared against each of
if b = c then
the values specified. If a match occurs, then the
program statement(s) associated with that match are begin
executed. writeln('C');
writeln('D')
If operator does not match, it is compared against
end;
the next value. The purpose of the otherwise clause
ensures that appropriate action is taken if b <> c then writeln('E')
when operator does not match against any of the else writeln('F');
specified cases. if a >= c then writeln('G')
You must compare the variable against a constant; else writeln('H');
however, it is possible to group cases as shown if a <= d then
below,
begin
writeln('I');

case user_request of writeln('J');

'A' : end

'a' : call_addition_subprogram; end.

's' :
'S' :
call_subtraction_subprogram;
end;

Revision notes  Page| 107


Information Technology PRPROGRAM IMPLEMENTATION

3.8.2: Loops XL := 2 * PI * Frequency *

The three logical operators are AND, OR and Inductance;


writeln('XL at ',Frequency:4:0,'
hertz = ', XL:8:2 );
The WHILE ‒ DO loop
Frequency := Frequency + 100.00
The structure of the WHILE statement is: end
while condition_is_true do end.
begin
program statement;
program statement
The REPEAT‒ UNTIL loop
end; {semi-colon depends upon next keyword}

or, if only a single program statement is to be The REPEAT‒UNTIL statement is similar to the
executed, while loop, how-ever, with the repeat statement, the
conditional test occurs after the loop. The program
while condition_is_true do statement(s) which constitute the loop body will be
program statement; executed at least once. The format is:
The program statement(s) are executed when the
condition evaluates as true. Somewhere inside the repeat
loop the value of the variable which is controlling program statement;
the loop (ie, being tested in the condition) must until condition_is_true; {semi-colon depends on
change so that the loop can finally exit. next keyword}

There is no need to use the begin/end keywords to


Example 3.8.5: Demonstrating the WHILE-DO group more than one program statement, as all
statements between REPEAT and UNTIL are
program WHILE_DEMO (output); treated as a block.

const
The FOR loop
PI = 3.14;
var
The most common loop in Pascal is the FOR loop.
XL, Frequency, Inductance : real The statement inside the FOR block is executed a
begin number of times depending on the control
condition.
Inductance := 1.0;
Frequency := 100.00;
while Frequency < 1000.00 do
begin

Revision notes  Page| 108


Information Technology PRPROGRAM IMPLEMENTATION

The format's for the FOR command is,

FOR var_name := initial_value TO final_value DO


program_statement;

FOR var_name := initial_value TO final_value DO


begin
program_statement; {to execute more than one
statement in a for }
program_statement; {loop, you group them using the
begin and }
program_statement {end statements }
end; {semi-colon here depends upon next keyword }

FOR var_name := initial_value DOWNTO


final_value DO program_statement;

Example 3.8.6: Demonstrating the FOR-DO

program CELSIUS_TABLE ( output );


var
celsius : integer; fahrenheit : real;
begin
writeln('Degree''s Celsius Degree''s
Fahrenheit');
for celsius := 1 to 20 do
begin
fahrenheit := ( 9 / 5 ) * celsius + 32;
writeln( celsius:8, '
',fahrenheit:16:2 )
end
end.

Revision notes  Page| 109


Information Technology PRPROGRAM IMPLEMENTATION

Example 3.8.7: Demonstrating the FOR-DO

program FOR_TEST ( output );


var
s, j, k, i, l : integer;
begin
s := 0;
for j:= 1 to 5 do
begin
write( j );
s := s + j;
end;
writeln( s );
for k := 0 to 1 do
write( k );
for i := 10 downto 1 do
writeln( i );
j := 3; k := 8; l := 2;
for i := j to k do writeln( i + l )
end.

Revision notes  Page| 110


Information Technology PRPROGRAM IMPLEMENTATION

holds a single integer. The next step is to create a


3.9: Manipulate data in a list working variable to be of the same type, eg,
This section explains how to work with ARRAYS; declaring
arrays, reading from and writing to arrays, traversing arrays, var
searching from arrays. numbers : intarray;

3.9.1: Arrays
Each element of the numbers array is individually
An array is a structure which holds many variables, accessed and updated as desired.
all of the same data type. The array consists of so
many elements, each element of the array capable
Writing to an array
of storing one piece of data (ie, a variable).

To assign a value to an element of an array, use


Declaring an array
numbers[2] := 10;

An array can be defined as a type, then a working This assigns the integer value 10 to element 2 of
variable created as follows: the numbers array. The value or element number
(actually it’s called an index) is placed inside the
type
square brackets.
array_name = ARRAY [lower..upper] of
data_type;
var Reading from an array
myarray : array_name;
{this creates myarray which is of type array_name }
To assign the value stored in an element of an array
or by using a var statement as follows: to a variable, use

var number1 := numbers[2];


myarray : ARRAY [1..100] of integer;
This takes the integer stored in element 2 of the
array numbers, and makes the
Lower and Upper define the boundaries for the
integer number1 equal to it.
array. Data_type is the type of variable which the
array will store, eg, type int, char etc. A typical
declaration follows, Example 3.9.1: Demonstrating ARRAYS

type program ARRAY;


intarray = ARRAY [1..20] of integer; type
int_array = ARRAY [1..10] of integer;
This declares an array of integers called intarray,
which has 20 separate locations numbered from 1 to var
20. Each of these positions (called an element), numbers : int_array;

Revision notes  Page| 111


Information Technology PRPROGRAM IMPLEMENTATION

counter : integer; for counter := 1 to 10 do {print out each


begin element}

writeln('Please enter in up to ten writeln('word1[',counter,'] is


integers.'); ',word1[counter] );
{reading the ten numbers into each element} writeln('Word1 array contains ',
for counter := 1 to 10 do word1 ) {print out entire array}
readln( numbers[counter] ); end.
writeln('The contents of the array is ');
{ print out each element }
for counter := 1 to 10 do 3.10: Checks and tests on
writeln('numbers[',counter:2,'] is programs to verify
',numbers[counter] ) correctness
This section explains how to verify programs correctness
end.
3.10.1: Testing Programs
Example 3.9.1: Demonstrating ARRAYS When programs are written they must be tested to
ensure that they are producing the correct result.
program CHARRAY; Testing programs involve manually checking the
program and also running the program oh.
type
word = PACKED ARRAY [1..10] of Compiler, interpreters and assemblers are equipped
char; with error checking systems which detect error
made in the program. This allows the programmer
var
to find and correct these errors. The process of
word1 : word; testing, locating and correcting mistakes by running
counter : integer; a program is called Debugging.
begin
writeln('Please enter in up to ten 3.10.2: Executing/running a program
characters.');
When a program is written it has to be run/executed to;
readln( word1 ); {this reads ten characters check that it works, for the user to interact with the
directly from the standard input device, placing program and/or for it to carry out the desired task. When
each character read into subsequent elements of programs are written in other languages than machine
language they must be converted to machine languages.
word1 array}
Running a program converts the instructions to machine
writeln('The contents of word1 array is language.
');

Revision notes  Page| 112


Information Technology PRPROGRAM IMPLEMENTATION

Revision notes  Page| 113


Information Technology PRPROGRAM IMPLEMENTATION

3.11: Write documented


programs
3.11.1: Write documented
programs
Documentation is an important part of the software
design process. Several different types are produced
during the process.

System documentation

System documentation is written by the technical


team for technical people and is concerned with
how the program works. This involves features
such as mnemonics used, use of comments,
indentations, and effective use of white spaces.

User documentation
User documentation is written for the end user and
is concerned with what the program does and how
the end user uses the program.

In Pascal comments are placed in the program by


using the "//" in front the statement or by enclosing
the statement in brackets. Comments are included
so that other persons can read a program and
understand what it is suppose to do.

Revision notes  Page| 114


Information Technology PRPROGRAM IMPLEMENTATION

Revision notes  Page| 115

You might also like