You are on page 1of 51

Computer hard wares

Hard wares are physical parts of a computer system. They are tangible parts. They are classified into input
devices and output devices.
Input devices are:
a) Key board
b) Mouse
c) Scanner etc
Output devices are:
a) Printer
b) Monitor etc
Soft wares
These are sets of programs that are used to tell the computer hardware what to do and how to do it.
They are classified into:
a) System software
b) Application software
c) Programming languages
Types of structured programming languages.
a) Pascal
b) Structured C
c) Cobol
d) Fortran etc
History of programming languages

a. Machine languages

Consists of strings of digits or numbness that instructs the computer to perform a certain operation.

b. Assembly language

Close machine language other than human language. They are symbolic representation of machine
code.

c. High level language it close to human language or syntax. Allows a problem to be specified in a
human understandable and oriented manner. The grammer of high level language is close to human
vocabulary.

1 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


d. 4th generation language

They are languages that allow the user of a program to query a database. The syntax of 4 th generation
languages is natural and user friendly. Uses menus to prompt a non-specialist to retrieve data with
easy.

e. 5th generation languages

These are languages that will allow program developed to mimic and copy human characters. Most of
them are still under development. E.g. Expert systems and Artificial intelligence.
Programming paradigms

a. Procedural programming

It combines returning sequences of statements into one program. A procedure call is used to
invoke the procedure to return one or more values.

b. Modular programming

The procedures of common functionalities are grouped together into separate modules. The
program is then divided into several smaller modules which interact through procedure calls and
form a whole program.

c. Unstructured programming

A programming technique whereby statements in a program have a specified arrangements of


statements. A global statement can be called from any part of a program.

d. Structured programming

Statements in a program are arranged and executed in a specified order. One statement after
another are translated to machine code.

e. Object oriented programming

Techniques where objects communicate with one another while don’t know how they are
implemented.

f. Event driven programming

A technique where programs written respond to events.

2 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


g. Pseudo code

This is an artificial and informal language that helps programmers to develop algorithms. Pseudo
code programs are not executed in the computer. They help a programmer to think out a
problem/program before attempting to write on a computer programming language.

Assignment
Computer hardware and software consideration in structured programming.

a) Hardware requirements
b) Appropriate operating system

PROGRAM DEVELOPMENT AND DESIGN


Program development
The process of formulating codes in a computer program. Program development involves coding a given task
in a programming language
Program design
The activity of progressing from a specification of some required program to a description of the program
itself. The input to this phase is a specification of what the program is required to do. During the phase the
design decisions are made as to how the program will meet these requirements, and the output of the phase
is a description of the program in some form that provides a suitable basis for subsequent
Characteristics of a good Pascal program.
 Clarity
 Robustness
 Reliability
 Efficient
Program development cycle
c) Problem solving phase
i. Analysis and specification
Understand (define the problem and what the problem must be.
ii. General solutions(program)
Develop a logical sequence of steps to be used to solve the problem.
iii. Verify
Follow the steps exactly to see if the solution really does solve the problem.

3 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


d) Implementation phase
i. specification solution
Translate the algorithm into a programming language (code).
ii. Test
Have the computer follow instructions and then check the results. If you find errors, analyze
the program and the algorithm to determine their source and then make corrections.
e) Maintenance phase
i. Use the program. Let users use the program and see if it meets it needs.
ii. Maintain
Modify the program to meet changing needs from end-users, or correct
any routine errors that may show up in using it.

Program design tools

a) Flow chart
A flow chart is a graphical method of designing programs. A well-drawn flow chart is also very easy to read
since it basically uses just two symbols, two decision constructs and two iteration constructs.

4 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Flow chart symbols
 Oval - The start symbol.

Start

 The diamond - The decision symbol.

Decision

 Rectangle - The input symbol.

Input/process

 Parallelogram (Rhombus) – output.

Output

 The oval – stop symbols

Stop

 The Line - connector

5 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Example
Construct a flow chart that can be used to get the sum of two numbers.

Start

Enter values x and y

Sum = x + y
Sum

Stop

Some rules for flow charts


a) Every flow chart has a START symbol and a STOP symbol
b) The flow of sequence is generally from the top of the page to the bottom of the page.
c) Use arrow-heads on connectors where flow direction may not be obvious.
d) There is only one flow chart per page
e) A page should have a page number and a title
f) A flow chart on one page should not break and jump to another page
g) A flow chart should have no more than around 15 symbols (not including START and STOP)

b) Pseudo code

This is an artificial and informal language that helps programmers to develop algorithms. Pseudo code
programs are not executed in the computer. They help a programmer to think out a problem/program
before attempting to write on a computer programming language. Pseudo-Code is simply a numbered
list of instructions to perform some task.

6 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


c) Algorithms
This is a step by step process of solving a problem by executing a series of actions in a specific order. A
procedure of solving a problem in terms of actions to be executed and the order in which they are to be
executed. Algorithm is also an ordered sequence of unambiguous and well-defined instructions that performs
some task and halts in finite time
a) An ordered sequence means that you can number the steps
b) Unambiguous and well-defined instructions means that each instruction is clear, do-able, and can be
done without difficulty
c) Performs some task halts in finite time (algorithms terminate!)

Example 1
Computing Sales Tax of sugar in Fatuma’s shop
Fatuma sales sugar in her shop. The government requires her to pay sales tax after each sale. Design a
Pseudo-code that computes the final price of the sugar after tax has been deducted. Note the three types of
instructions: input (get), process/calculate (=) and output (display).
Solution
1. Get price of item
2. Get sales tax rate
3. Sales tax = price of time times sales tax rate
4 Final prince = price of item plus sales tax
5. Display final price
6. Halt
Example 2
Compute weekly wages of the workers in Kisii coffee Farm.
The pay rate for each worker is Kshs.100 per hour for 8 hours normal hours. The pay rate for overtime is
Kshs.200 per hour. Design a Pseudo-code for the task of computing gross pay given pay rate and hours
worked.
1. Get hours worked
2. Get pay rate
3. If hours worked less than or equal to 8 hours then
4. Gross pay = pay rate times hours worked
5. Else
6 Gross pay = pay rate times hours worked plus overtime hours times overtime pay rate
7. Display gross pay
8. Halt

7 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


d) Decision tables
A decision table is a tabular form that presents a set of conditions and their corresponding actions.

Condition Stubs
Condition stubs describe the conditions or factors that will affect the decision or policy. They are
listed in the upper section of the decision table.

Action Stubs
Action stubs describe, in the form of statements, the possible policy actions or decisions. They are
listed in the lower section of the decision table.

Rules
Rules describe which actions are to be taken under a specific combination of conditions. They are
specified by first inserting different combinations of condition attribute values and then putting X's in
the appropriate columns of the action section of the table.

Decision Table Methodology

1. Identify Conditions & Values Find the data attribute each condition tests and all of the attribute's values.
2. Compute Max Number of Multiply the number of values for each condition data attribute by each
Rules other.
3. Identify Possible Actions Determine each independent action to be taken for the decision or policy.
Fill in the values of the condition data attributes in each numbered rule
4. Enter All Possible Rules
column.
5. Define Actions for each Rule For each rule, mark the appropriate actions with an X in the decision table.
6. Verify the Policy Review completed decision table with end-users.
7. Simplify the Table Eliminate and/or consolidate rules to reduce the number of columns.

Example

A marketing company wishes to construct a decision table to decide how to treat clients according to three
characteristics: Gender, City Dweller, and Age group: A under 30, B between 30 and 60, C over 60. The
company has four products W, X, Y and Z to test market. Product W will appeal to female city dwellers.
Product X will appeal to young females. Product Y will appeal to Male middle aged shoppers who do not live
in cities. Product Z will appeal to all but older females.

1. Identify Conditions & Values


The three data attributes tested by the conditions in this problem are gender, with values M and F; city
dweller, with value Y and N; and age group, with values A, B, and C as stated in the question.

2. Compute Maximum Number of Rules

8 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


The maximum number of rules is 2 x 2 x 3 = 12

3. Identify Possible Actions


The four actions are: market product W, market product X, market product Y, market product Z.

4. Enter All Possible Rules


The top of the table would look as follows: Note that all combinations of values are present.

The format/structure of a Pascal Program

A structure is the order in which programs statement in Pascal must follow. Below is the basic structure that
every Pascal program must follow.

 Optional comments
Comments address solely the readers of a program. They provide an overview of a program or one of
its components. They also supply the extra information about why a program was constructed.
Comments are enclosed in curly brackets {}. Comments appear anywhere in the program other within
a string constant.
 Header
The header identifies the program and is terminated by a semicolon. The header must ahave the
name of the program. And the specification on how to this program interacts with the external data.
E.g.

Program sum (input, output);


 Declarations
Describes and identifies the objects used by the program. E.g.

Var x, y, z: integer;

Declarations can be extensive in programs that are larger or more sophicated. Declarations show and
specify the variables used by the program. It also specifies the dataytypes and constants.
 Body of the program
Specifies the actions to be taken when the program executes. Consists of a sequence of statements
separated the semicolons between keywords BEGIN and END.
Statements specify individual steps in computation. A period following the keyword END marks the
end a program.

PROGRAM ProgramName;

9 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Block
VAR declaration
VariableName: Variable dataType;
VariableName: Variable dataType;
Constants
Type definitions
Procedures and functions
Statement(s);
END.
Program elements
Pascal syntax and semantics
A programming language is a set of rules, symbols, and special words used to construct a program.
There are rules for both syntax (grammar) and grammar (meaning). Syntax refers to rules governing how
valid instructions (constructs) are written in a programming language. Semantics refers to a set of rules that
determine the meaning of instructions (constructs) written in a programming language. Syntax defines
exactly what combinations of letters, numbers and symbols can be used in a programming language.
Identifiers
Identifiers name things. It is a name associated with a process or objects and is used to refer to that process
or object.

Rules of using identifiers


 Must start with a letter
 They must have a meaning
 Can have both uppercase and lowercase
Keywords in Pascal
They are reserved words that are used to develop programs.
Examples
And
Do
Function
Program
Case
Type
etc

Operators in Pascal
An operator is a symbol that is used in a formula to carry out a calculation to get the result.
Types of operators
 Mathematical operators
Used to carry out arithmetic functions
 Plus (+)
 Subtraction (-)
 Division (/)
 Multiplication (*)

10 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


 Modulus (Mod)
 Caret (^)

 Logical operators
Use to compare two or more values in a program to return value.

 =
 <
 >
 <=
 >=
 <>

 Relational operators
Used to compare and relate two or more items in a program.
 AND
 OR
 BETWEEN
 IN
 LIKE

Data Types
The dataType specifies the kind of data stored by the variable declared. We have two categories of dataType
in Pascal:

 Built in dataType
 User defined datatype
There are five built in datatype in Pascal: INTEGER, REAL, CHAR, BOOLEAN, and STRING.

INTEGER A positive or negative whole numbers between a smallest (negative) and a largest number. In
general the smallest and largest number possible depends on the machine
smallest Integer: -32766
largest Integer: 32767
REAL Are decimal numbers. They have an integer part and a fractional part. Can contain a real number in
scientific or decimal notation. There is a limit on the size and accuracy of the real number that will
be covered later. Valid real numbers are, for example:
Decimal Notation: 1.234 or -34.5507
Scientific Notation: 5.0E-3 or -7.443E3
CHAR Describes the data consisting of one alphanumeric character such as letter, a digit or special
symbol such as ‘a’,’A’,’8”
BOOLEAN Has only two parts(values) true or false.
STRING A string is a collection of up to 255 characters enclosed in single quotes. For example: 'Bert' is a

11 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


string of 4 characters.

Expressions and assignments


An expression is a collection of operands joined together to perform an operation and return a value.
Assignment is equating a variable to a value in an expression. E.g.

Sum:= x+y+z;
Assignments for students

Describe the following datatype:


 Simple dataType
 Structured datatype
Program writing in Pascal
Example 1
Write a program that calculates the sum of three numbers
Solution
Program add(input, output);
Var x, y, z,sum:integer;
Begin
Writeln(‘enter the value of x,y,z’);
Readln(x,y,z);
Sum:=x+y+z;
Writeln(‘The sum is’,sum)’
End.
Example 2
Write a program that calculates the area of a circle given Pi =3.142.
Solution
Program circle(input,output);
Const pi: =3.142;
Var radius:real;
Var area:real;
Begin
Wrteln(‘Enter the radius of a circle’);
Readln(radius);

12 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Area:=pi*radius^2;
Writeln(‘The area of the circle is’,area);
End.
Pascal variables
These are identifiers whose values change during execution.
Pascal constants
These are items that don’t change during execution.

 Program Input/Output statements

The input data items must be placed in a separate file called input file before the corresponding is run. The
output data are transferred from the computer memory to output file. The data items are stored
sequentially in the order they were stored or written. the items will then be grouped into logical lines
which will be then correspond to physical lines of output when data I printed or displayed. E.g.

Program payroll(input,output);

 Read statement

Used to read data items from input file and assign them to an integer, real, char and Boolean type
variables. e.g

Read(x,y,z);

 Readln statement

Used to read data items from input file and assign them to an integer, real,

char and Boolean type variables. e.g

Readln(a,b,c);

The difference between the Readln and read is that the Readln causes the next

Read or Readln statement to begin by reading a new line of data. The read statement allows the next
read or Readln to begin on the same line.

 Write statement

Used to write data items to an output file.

13 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Write(‘The sum is ‘,sum);

Write(‘X’,’X’);

 Writeln statement

Identical to write except that the Writeln statements results in and of linedesignation being written
after the last data item.

Writeln(‘The area is’,area);

Program compiling

This involves a process of testing a program in structured programming to check if the program is
error free. It is a process of converting a program from course code to its object equivalent.

Program debugging

This is a process of correcting errors in a program. When a program executes in structured


programming, it must produce the expected results. If it doesn’t give the expected output then it has
errors. In this regard the programmers should start the process of debugging.

Testing programs in structured programming

This is a process of running (executing) programs to find errors (bugs). The process of finding bugs is
called debugging as mentioned above. Program testing is part of the procedure which ensures that
the program corresponds with original program specification and that it works in the intended
environment.

Test plan

These are the stages involved in testing the programs. They include the following.

1. Deskchecking

After writing the program the programmer goes through the program on a paper to eliminate
any error that might cause extra work later.

2. Translator system checking

After coding the program is checked using the compiler or translator to detect any syntax
error. The programmer corrects these errors and then resubmits the program to the compiler
until the errors are over.

3. Program run with test data

14 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


These re trial runs done with test data that includes all variations and extremes data including
data with errors to ensure that program does not grind to an halt if incorrect data is used.

4. Diagnostic procedures

For complex programs diagnostic procedures are used to find logical errors. A trace routine
print the results at each stage to enable errors detected quickly. If the trace routine is not
available, the programmer can insert instructions in the program to print out intermediate
results at key points.

5. System test with actual data (full-scale) system

Usually new systems are run parallel with existing system for a short period so that the results
are compared and adjustments made.

Test data

This is the information that is used to test the new system or program. The program tried and executed at
least once every routine through the program and the accuracy of the program is verified to meet the
original design specification.

Categories of test data

 Dummy data

This is the data input into a system for trial purposes. Used to test the system for correctness.

 Real data (normal data)

This includes the general data for which the system was designed.

 Exceptional data

Programs are designed to accept certain range of data. If illegal data is input it should be able to
detect and reject it rather than try to process it to avoid getting wrong results.

Types of errors structured programming

 Logical errors

This is a human error. A programming mistake that makes a program code to output wrong results.

 Syntax error

These are an error that violates rules and regulations or the syntax of a language.

 Runtime error

15 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


These are the undiscovered error in a program.

STRUCTURED PROGRAMMING CONTROL STRUCTURES


The operators
Symbols used to calculate some value and return results.
 Arithmetic operators
Used to perform mathematical operations.
Plus (+)
Multiplication (*)
Subtraction (-)
Division (/)
Modulus (mod)
 Logical operators
<
>
>=
<=
<>
 Relational operators
And
Or
Between
Not
Control structures are classified into three:
 Selection control structures
The user is given options to choose from among the alternatives.
 Iteration control structures
The statements repeat themselves until the condition is met.
 sequence control structures
The programs are executed in a specified order.

The While-Do statement

16 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


This is an iterative control structure that is used to carry out the conditional looping. The loop will be
executed so long as the Boolean expression remains true. It executes the condition to test their falsity.

Example 1
Using the While-Do statement write a program that prints 10 digits on the screen.

Program number (input, output);


Var x:integer;
begin
X:=1;
While x<=10 do
Begin
X:=x+1;
Writeln(x);
End;
End.

Example 2
Write a program using WHILE-DO iterative control structures that prints two numbers and gets their sum.
Program numbers(input, output);
Var x:integer;
Var sum:integer;
Begin
x:=1;
Sum:=0;
While x<=2 do
begin
x:=x+1;
Sum:=x+sum;
Writeln(sum);
End;
End.

Example 3
Write a program using WHILE-DO iterative control structures that prints six numbers and gets their average.
Program numbers(input, output);
Var x:integer;
Var sum:integer;
Average:real;
Begin
x:=1;
Sum:=0;
While x<=6 do
begin

17 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


x:=x+1;
Sum:=x+sum;
Average:=sum/6;
Wrteln(average);
End;
End.

False

Loop Conditio
n

True

Statements

a) Repeat until control structure


The repeat condition executes a Statement first. After the first execution of the Statement, it
examines the Condition. If the Condition is true, then it executes the Statement again. It will keep
executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the
looping (the execution of the Statement) would stop.
Repeats a sequence of statements repeatedly until a Boolean expression becomes false. The
sequence of statements will be executed at-least once since the Boolean expression is not tested until
the end of the control structure.

18 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


The Statement of a repeat…until condition can span as many lines as necessary. In this case, although
you can, you do not have to start the Statement with the begin keyword and then end it with the end
keyword.

Example 1
Write a program using REPEAT…..UNTIL iterative control structures that prints two numbers and gets
their sum.
Program numbers(input, output);
Var x:integer;
Var sum:integer;
Begin
x:=1;
Sum:=0;
Repeat
x:=x+1;
Wrteln(sum);
Until x<=10
Sum:=x+sum;
End.

Repeat………until loop flow chart

Start

False
Statements

Boolean
expression

True

19 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


b) The for Statement
The for statement is typically used to count a number of items. The count can perform in incremental
values or in decremental values.

For loop Syntax:


For Counter: = InitialValue to FinalValue do
Statement(s);
End;

Using this formula, you can count values from a stating value to an end. To do this, you must first
declare a variable that would hold the count. In our syntax, such a variable would be the Counter
parameter. The InitialValue is a value assigned to the Counter variable as the starting value. The to
keyword is required to proceed with the counting. The counting would stop with the value of the
FinalValue parameter. The value of InitialValue should be lower than that of FinalValue.

The do keyword is required and used to introduce the Statement. After one count, the for loop would
execute the Statement. After executing the Statement, the loop would check whether the count has
reached FinalValue. If it has not, then the InitialValue would be incremented by 1 and the Statement
would be executed again. This checking -> incrementing -> Statement executing would continue until
a new incremented value of InitialValue is equal to the value of FinalValue; in which case the loop
would stop.

Example 1
Program example2(input, output);
var Number: Integer;
sum:integer;
begin
for Number := 0 to 15 do
sum:=x+sum;
Writeln(sum);
Write(Chr(10), 'Press any key to continue...');
Readln;
end.

Example 2
Program example3(input, output);
var Number: Integer;
sum:integer;
average:real;
begin
for Number := 0 to 15 do
sum:=x+sum;

20 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


average:=sum/10;
Writeln(average);
Write(Chr(10), 'Press any key to continue...');
Readln;
end.

Start

True
x=1 to 10

Loop
Statements

False

Increment operator

21 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Selection/Conditional control structures
Conditional control structures allow action to be taken if the given logical condition has a specified value
either true or false.

If control structure
A conditional control structure that allow some action to be taken if the given logical condition has a
specified value either true or false. The statements wil be executed only if the Boolean expression is true. If
the Boolean expression is false the program ignores the line.

Example 1
program example2(input, output);
var Age : integer;
begin
Write('please enter your age: ');
Readln(age);
If age>=18 then
Writeln(‘You are an adult’);
If age <18 then
Writeln(‘You are young’);
End.

If…then…..else control structure


Use to give options incase the predecessor does not meet the criteria given. The if condition is used to check
one possibility and ignore anything else. In this case, you can use more than one if statement.

Example 1
Program example1(input,output);
Uses crt;
Var input:string;
Begin
Clrscr;
Writeln(‘Enter the password’);
Readln(input);
If(input=’pascal’) then
Writeln(‘pascal is the easiest structured language to learn!!!!!!!!!!!!!!!!!!’);
If(input=’basic’) then
begin
Writeln(‘basic is not very hard to hard’);
End;
If(input=’0’ then
Writeln(‘wrong password’);

22 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


End.
Example 2
Program example2(input,output);
USES CRT;
Var maths,english,kiswa:integer;
Var sum:integer;
Var average:real;
Begin
Clrscr;
Writeln(‘enter your marks’);
Readln(maths,English,kiswa);
Sum:=maths+English+kiswa;
Average:=sum/3;
If (average>=80) and (average<=’100’) then
Writeln(‘A’);
If(average>=70) and (average<=79) then
Writeln(‘B’);
If (average>=60) and (average<=69) then
Writeln(‘C’);
If (average>=50) and (average<=59) then
Writeln(‘D’);
If(average>=40) and (average<=49) then
Writeln(‘A’);
If(average>=1) and (average<=39) then
Writeln(‘E’);
If (average>=’0’) then
Writeln(‘You never sat for exams’);
End.

The case...of Statement


When defining an expression whose result would lead to a specific program execution, the case...of
statement considers that result and executes a statement based on the possible outcome of that expression.
The different outcomes are listed in the body of the case...of statement and each case has its own execution,
if necessary.

Case syntax:
Case Expression of
Case Choice1:
Statement1;
Case Choice2:
Statement2;
Case Choice-n:
Statement-n;
End.

23 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


The expression to examine can be an integer, a character, an enumeration type, or a predefined list of items.

Example1
Program example1(input,output);
Uses crt;
var Number: Integer;
Answer: Char;
Begin
Clrscr;
Write('Type a number between 1 and 3: ');
Readln(Number);
case Number of
1: Writeln('You typed 1');
2: Writeln('You typed 2');
3: Writeln('You typed 3');
Else
Writeln(‘you entered an invalid number…..’);
end;
Write(Chr(10), 'Press any key to continue....................');
Readln;
end.

24 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Introduction to Pascal subprograms
Subprograms refer to any set of statements forming part of a program used to perform a specific task. They
are instructions that are incorporated in the main program to do some task before passing control to the
main program. A properly constructed subprogram should be self contained, perform defined operations on
well defined data and have an internal structure that is independent of the program in which its contained.

Types of subprograms

Functions
A function is an assignment that must be performed to complete a program. Unlike a procedure, a function
must return a value. A self contained program structure that can be called to do an operation and return a
single value to finish execution. Its referenced by specifying the name within the expression as though it was
an ordinary simple type variable. The function name can be be followed by one or more actual parameters
enclosed in paranthesis and separated by commas

Function syntax:
Function FunctionName: ReturnType;
Begin

End;

Function sum : Integer;


begin
Result := 1250 + 48;
end;

Function Perimeter: Double;


begin

end;

The begin and end keywords are required because they would enclose the assignment performed by the
function. Between the begin and end keywords, do whatever the function is supposed to do(instructions).
After performing the assignment for function, you must specify what value the function is returning.

A function can return a either of the following:

 A character:
Function ShowSomeCharacter : char;
begin
Result := 'Z';

25 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


end;
 An integer:
Function Natural : Integer;
begin
Result := 228;
end;
 A floating number:
Function DecimalNumber : Double;
begin
Result := 12.55;
end;
 A Boolean value:
Function IsMarried : Boolean;
begin
Result := true;
end;
 A string:
Function CompleteName: string;
begin
Result := 'I showed you mine. Now show me yours';
end;

Function call
Once a function exists or is known, you can call it the same by simply typing its name where the function is
needed. A function returns a value and this can be any values of the dataytypes, but the value must be the
type stated by the ReturnType word.
Because a function returns a value, it can be passed to a Write or a Writeln procedure to display its return
value.

26 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Example 1
Program example1(input, output);
Function Addition: Integer;
begin
addition := 1250 + 48;
end;
begin
Writeln(Addition);
end.

Scope of variables
Variables can be declared in function. These variables belong to the functions in which they are declared.

 Local variables
Local variables are accessed anywhere between begin and the matching end keywords. These
variables are only important inside the function.

Example1
Program example1(input, output);
Var x,y:integer;
Function addition;
Var answer:integer;
Begin
Answer:=x+y;
Writeln(‘The answer is: ‘,answer);
End;
Begin
Writeln(‘Please enter the two numbers’);
Readln(x, y);
Addition;
End.

Global variables
Theses are variables declared for the entire program; that is within the block containing the function
declaration. Global variables can be utilized anywhere within the block whether inside or external to the
function.

27 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Example1
Program example1(input,output);
Var n,p,m:integer;
Function maximum;
Var max:integer;
Begin
If n>p then max:=n else max:=p;
If m> max then max:=m else max:=n;
Writeln(‘the maximum is: ‘,max);
End;
Begin
Readln(n,p,m);
Begin
Maximum;
Readln(n,p,m);
End;
End.

Procedures
A self contained program structure that can be called to do an operation and return a single value to finish
execution. The procedures make the program easy to debug, understand and use. They also make flexible
the use of parameters.

Procedure structure

Procedure compliment
Begin
Writeln(‘statement’);
Writeln(‘statement’);
End;

A procedure is referenced by its name followed by its optional parameters.

Example1

Program example1(input,output);
Var x,y,z:integer;
Procedure largest;
Var max:integer;
Begin
If x>y then max:=x else max:=y;
If x:=max then max:=z;

28 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Writeln(‘the highest is: ‘,max);
End;
Begin
Readln(x,y,z);
Begin
Largest;
End;
End.

Example1

Program example2(input, output);


Var x,y:integer;
Procedure addition:integer;
Var answer:integer;
Begin
Answer:=x+y;
Writeln(‘the answer is: ‘,answer);
End;
Begin
Writeln(‘please enter the two numbers’);
Readln(x,y);
Addition;
End.

Parameter passing
Parameters are those variables that are used to hold data to be passed to the calling statement or procedure.
The process of transferring these parameters is called parameter passing. Arguments are real or actual values
passed to calling statement or procedure.

Types of parameters

 Formal parameters
These are labeled memory blank areas that are to be used to store values to be used during execution. They
are identifiers rather than reserved words.

 Actual parameters
These are variables that replace the formal parameters when the procedure or function is called. They are
given the actual parameter list of procedure call.

29 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Classes of parameters
 Value parameters
Used to to supply information to the procedure but they cannot be used to get information out of a
procedure. Value parameter are declared by including their names and the corresponding datatypes within a
procedure header without any prefix VAR.

e.g.
program parameter(input,output);
var x,y:integer;
var z,m:integer;
procedure number(x:integer;y:real);
begin
end;
begin
number(3,x*(z+m)/y;
numner(2*(x+y),-0.5);
end.
Note: x and y are value parameter in a procedure.

 Variable parameter
Used in applications where binformation must be transferred in both directions between the procedure and
procedure reference. When the procedure containing a variable parameter is accessed the actual parameter
in the procedure refernce is substituted by the formal parameter within the procedure itself.

Assignment to students

 Procedure parameters

 Function parameters

30 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Data structures in structured programming
These are variables that hold data two or more elements together instead of one sinle element. A tool for
handling a group of logically related data items. They are user defined and provide a method for packing
together data of different typ0es.

Classification of data structures

 Static data structures


These are data structures which don’t change when the program executes.

 Dynamic data structures.


They are data structures that change when the program executes.

Types of data structures

1. Arrays
This is a consecutive group of memory location that all have the same name and datatype. This is a
list of variables all with the same name and datatype.

When we work with a single item, we only need to use one variable. However, if we a list of items
which are similar in type we need to declare an array of instead of using a variable for each item
variables.
Declaring arrays
Arrays are declared the same way we declare normal arrays except that you have to say how many elements
you have in the array.

e.g.

Var x:array[1..5] of integer;

Var names:array[1..10] of string;

 One dimensional array(1D arrays )

This is an array that consists of one row.

31 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Example1
A program that prints an array of five names on the screen.
Program array(input,output);
Var names:array[1..5] of string;
Var x:integer;
Begin
For x:=1 to 10 do
Readln(names[x]);
Writeln(names[x]);
End.

Example 2
A program that prints an array of ten numbers on the screen.
Program array(input,output);
Var x:array[1..10] of integer;
Var i:integer;
Begin
For i:=1 to 5 do
Readln(x[i]);
Writeln(x[i]);
End.

Example3
A program that prints an array of ten numbers on screen and calculates their sum.
Program arrays(input,output);
Uses crt;
Const students=5;
Var numbers:array[1..5] of integer;
Var total,count:integer;
Var average:real;
Begin
Clrscr;
Total:=0;
For count:=1 to students do
Readln(numbers[count]);
Writeln(numbers[count]);
Total:=total+numbers[count];
Writeln(‘The total is ‘,total);
Average:=total/students;
Writeln(‘The average is ‘,average);
End.

32 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Two dimensional arrays (2D arrays)
These are arrays that have both rows and columns.

Declaring two dimensional arrays

Type multi = ARRAY [1..10, 1..10] of integer;


Var numbers:array[1..4] of integer;
Var names:array[1..4] of integer;

Example 1

Given the following marks achieved in a test, and that the pass mark is the average of all the marks, write a
program to calculate the total marks, average marks and list all those students who have passed.

FRED 21 GEORGE 56
ANNE 52 MARY 89
ROBERT 71 ALFRED 71
CECIL 33 MIKE 54
JENNIFER 41 PAULINE 48

Program example1(input, output);


Uses crt;
Const noofstudents = 10;
Var names:array[1..10] of string;
Marks: array[1..10] of integer;
Total, count: integer;
Average: real;
Begin
Clrscr;
name[1] := 'FRED '; marks[1] := 21;
name[2] := 'GEORGE '; marks[2] := 56;
name[3] := 'ANNE '; marks[3] := 52;
name[4] := 'MARY '; marks[4] := 89;
name[5] := 'ROBERT '; marks[5] := 71;
total:= 0;
for count:= 1 to noofstudents do
total := total + marks[count];
writeln('The average mark was ',total);
average:=total / noofstudents;
writeln('The average marks is ',average);
writeln('The students who passed the test are ');

33 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


for count := 1 to maxstudents do
if mark[count] >=50 then
writeln(name[count]);
writeln;
end.

Trees
Trees these are hierarchal data structure constructed using rule of precedence for data items using
alphabetical or numerical sequence. The elements of a tree are called nodes and each element consists of a
datum and at least two pointers.

56 42 89 65 48

Left pointer Datum Right pointer

56 is the first datum placed I the tree. Its node is therefore called parent node or root node. We add 42 to
the tree next using rule of precedence; lower number to the left and higher number to the right.

Start

56

42 89

-1 48 -1 -1 65 -1

34 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


A
S
B D
S C

E A
S S J
E H
F

M Q
P
S
K
S

QUEUES
This a chain of of data items in the computer memory awaiting execution. Queues use FIFO, first datum in is
the first datum out.

Characteristics of queues
 Data is entered to the end but removed from the front.
 The term FIFO is used to describe queues because first datum in is the first datum out.
 Each data stays in the storage location until its turn comes thereby reducing time spent in data
movement.

STACKS
They are used too temporarily store information or data. Related to queues but data is removed and added
differently. Data is added at the top and removed from top using LIFO.

Next removal pointer


Location of address 101 102 103 104 105 106 107 108 109 110
Contents 20 4 19 12 16
Order of arrival 1 2 3 4 5
Order of removal 5 4 3 2 1

Pointers

These are variables that stores memory addresses. They point to a particular address that can be used to
store data items. There are two types of pointers:
 Typed pointers

35 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


They point to variables such as integers.
 Typed pointers
They appoint to any type of variable.

Typed pointers
You declare typed pointers using ^ in front of he variable type which you want to point to. The @ symbol can
also be used in front of a variable to get its memory address. This memory address can be stored in a pointer
because pointers store memory addresses.

e.g.

program pointers;
var x:integer;
p:^integer;
begin
p:=@i;
end.

If you change the value stored at the memory address pointed at by a pointer you must first deference the
pointer variable using ^ after the pointer name.

e.g.

program pointers;
var i:integer;
var p:^integer;
begin
i:=1;
p:=@i;
p^:=2;
writeln(i);
end.

You can allocate new memory to a typed pointer using new command. The new command gets the memory
that is the size of the variable type of the pointer and then sets the pointer to point to a memory address of
it. When you finish using the pointer use dispose command to free the memory that was allocated to the
pointer.

Program pointers;
Var p:^integer;
Begin

36 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


New(p);
P^:=3;
Writeln(p^);
Dispose(p);
End.

Untyped pointers
To declare the untyped pointers you must use the variable type called pinter. To allocate memory to an
untyped pointer you must use the Getmem command instead of new command. You must also use Freemem
command instead of dispose command to free the memory. The Getmem command have a second
parameter which is the size in bytes of the amount of memory which must be allocated to the pointer. You
can either use a number for the size or sizefuction to get the size of a specific variable type.

e.g.

program pointers;

var p:pointer;
begin
getmem(p,sizefunctionof(integer));
freemem(p,sizefunctioof(integer));
end.

Linked lists
Lists are flexible ways of handling data items in order. For example:

Alex Does Not Like Cakes

Each word in the sentence is a data item, which is linked to the next data item by a pointer. Datum plus a
pointer make a node or element of a list. The last item in the list is a terminator. This may be stored in an
array of records. Each row of an array is one element in the list. A start pointer saying where the first datum
is stored and a free storage pointer saying where the next datum can go.

37 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


ROW NO DATUM POINT TO THE NEXT NO COMMENT
Start pointer 1 “ALEX” 2 NEXT DATUM
2 “DOES” 3 NEXT DATUM
3 “NOT” 4 NEXT DATUM
4 “LIKE” 5 NEXT DATUM
5 “CAKES” -1 LAST DATUM
6 EMPTY
Free storage pointer 7 EMPTY

Types of linked lists


 Single linked lists
The element of the record has only one pointer.

Head Address 1 Address 2 Address 3

 Double linked lists


The element of the record has two pointers, one pointer for giving the address of the following
record another for giving the address of the proceeding record.

Head

 Circular linked lists


The pointer of the last record gives the address first record thus this form a circular or ring of
records.

Address 1 Address 2 Address 3

38 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Introduction to Strings

In order to understand strings, one has to keep in mind that a string is made up of an array of characters. The
string data type is an in-built data type that is an array of 256 characters (Type String = Packed Array[0..255]
of Char). When stored in memory, the processor should know where the string starts and where it finishes.
In order to know where the string finishes, in Pascal, the 0th element of a string is defined as the length of
the string. So, if you try to access character 0 of a string, the number of characters stored in that array is
returned, thus letting the processor to know where the string finishes.

Example 1

Program example1(input,output)

Var myString: String;

Begin
myString := 'Hey! How are you?';
Writeln('The length of the string is ',byte(myString[0]));
Write(myString[byte(myString[0])]);
Write(' is the last character.');
End.

I have used an automatic data-type conversion, normally referred to as data type-casting. When type-casting
from one data type to another, all that is happening is simply a conversion from one data type to another
based on the data type in subject and the wrapping data type to which the old data type is being converted.

39 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


In our case, the array variable myString has a special 0th element storing the number of characters in that
array in string format. This value is an ASCII value, so trying to display it without converting it into a number;
the alternative ASCII character is displayed. So you have to change the character value to an ordinary number
by wrapping the variable by another data type, in our case a byte data type (why use integer? - its all waste
of memory and memory consumption). Note that myString[myString[0]] without having data-type casting
around myString[0] will lead to a compiler error because myString[0] is a character and not an integer.

String Functions
There are some basic Pascal functions that have to do with string operations.

 Function Pos(SubString : String; S : String) : Byte;


This function will search for the string SubString within the string S. If the sub-string is not found,
then the function would return 0. If on the other hand the sub-string is found, then the index integer
value of the first character of the main string that matches the character of the sub-string is returned.

Example 1

Program example1(input,output);
Var S: String;
Begin
S:= 'Hey there! How are you?';
Write('The word "How" is found at char index ');
Writeln(Pos('How',S));
If Pos('Why',S) <= 0 then
Writeln('"Why" is not found.');
End.

 Function Copy(S : String; Index : Integer; Count : Integer ) : String;


This function will copy some characters from string S starting from character index Index and copies
as much as Count. The copied string is then returned.

Example 1

Program example1(input,output);
Var S : String;
Begin
S := 'Hey there! How are you?';
S := Copy(S, 5, 6); { 'there!' }
Write(S);

40 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


End.

 Procedure Delete(var S : String; Index : Integer; Count : Integer );

Deletes a specified number of characters from the string S. The starting position of deletion is from
character index Index. The number of characters that will be deleted is specified through Count. The
new string is passed back through the variable parameter S.

Example 1

Program example1(input, output);

Var S: String;
Begin
S:= 'Hey Max! How are you?';
Delete(S, 4, 4); {‘Hey! How are you?’}
Write(S);
End.

 Procedure Insert(Source : String; var S : String; Index : Integer);


This function will insert a string of any length into a source string starting from an index character. The
string S will be inserted into string Source starting from the index character Index. No characters will
be deleted from the front except if the resulting string is longer than 255 characters. In this case, the
front characters will be truncated as to fit a 255-character string.

Example 1
Program example1(input, output);
Var S: String;
Begin
S: = 'Hey! How are you?';
Insert(S, ' Max', 4);
Write(S);
{‘Hey Max! How are you?’}
End.

 Function Concat(s1 [, s2, s3...sn] : String) : String;


Concatenates 2 or more strings depending how long is the argument expression. Try to make sure not
to exceed the limit of 255 characters when concatening strings as it will result in truncation. This
function can also be obtained by using the plus (+) operator between strings that need to be
concatenated.

41 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Example 1
Program example1(input, output);
Var S1, S2: String;
Begin
S1:= 'Hey!'
S2:= ' How are you?';
End.

Example 2

Program example2(input, output)’


Var S1, S2: String;
Begin
S1:= 'Hey!'
S2:= ' How are you?';
Write(S1 + S2); {‘Hey! How are you?’}
End.

 Function UpCase(C : Char) : Char;


Converts the character C to uppercase and returned. If the character is already in uppercase form or
the character is not within the range of the lower case alphabet, then it is left as is.

Example 1

Program example1(input, output);


Var S: String;
Var i: Integer;
Begin
S: = 'Hey! How are you?';
For i: = 1 to length(S) do
S[i]:= UpCase(S[i]);
Write(S); {‘HEY! HOW ARE YOU?’}
End.

42 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


 Procedure Str(Val : Integer / LongInt / Real; var S : String);
Converts an integer or a decimal value to a string. The value parameter Val is converted into a string
and passed through the variable parameter S.

Example 1

Program example1(input, output);


Var
S: String;
i: Real;
Begin
i := -0.563;
Str(i, S);
Write(S);
End.

 Procedure Val(S : String; var Val; Code : Integer);


Converts a string to its corresponding numeric value. The string parameter S is converted into a
numeric value and passed back through the variable parameter Val. If the string to be converted is
not a correct numeric value, an error occurs and is returned via Code. If the conversion is correct then
Code is 0.

Example 1

Program example1(input, output);


Var
S: String;
Error: Integer;
R: Real;
Begin
S: = '-0.563';
Val(S, R, error);
If Error > 0 then
Write('Error in conversion.')
Else
Write(R);
End.

43 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


FILES HANDLING IN STRUCTURED PROGRAMMING

A file is a collection of related records on some items of interest.

File concepts

Bit

Byte
(Bits)

Character
(Collection of byte)

Data
(Collection of characters)

Field
(Collection of data)

Record
(Collection of fields)

File
(Collection of related records)

Database
(Structured collection of files)

44 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


ASSIGNMENT TO THE CLASS
EXPLAIN THE VARIOUS TYPES OF FILES USED IN COMPUTER.

Types of files
There are different types of files:
 Master file
 Transaction file
 Backup file
 Sort file
 Etc

FILE ORGANIZATION TECHNIQUES


These are the methods involved in storing files in a computer memory.

Objectives of file organization


 Increase processing speed
 Easy accessibility
 To increase security of data
 For easy references

 Sequential file organization


Files are arranged serially in a sequence, one after another. Files are accessed in the same order they
were stored.
Advantages
 Simple to understand and follow
 Relatively inexpensive
 No gap between the records
 Simple to create
 Fast to process data.
Disadvantages
 No backup facility
 Mandatory sorting
 Data redundancy is high
 Linking of records impossible

45 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


 Random file organization
There is no order in the storage of files. Files are stored randomly in the memory.
Advantages
 Easy to access files
 Easy and quick to update
 Sorting is not mandatory
 Immediate processing
Disadvantages
 Expensive
 Not suitable for all storage media
 Low speed
 Requires special security measures

 Indexed sequential file organization


Files are stored sequentially but directly accessed using an index.
Advantages
 Immediate access
 No need to sort the input
 Flexible
 Easy to update
 Linking of records is possible
Disadvantages
 Requires additional storage space.
 No backup facility
 Expensive

FILE DESIGN
To create a file you first declare a variable of that file. After declaration you should assign the file a name
using a command. To create an empty file use rewrite command. To read from an existing file we use reset
command. Use readln to read lines of text from the file. You will also need to use while loop that repeats
until it comes to the end of the file.

46 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Append command is also used to let you add more text to the end of the file. Use close command to close a
file when you have finished using it. Uses rename command to change the file name. final you can also use
erase command to erase command to delete a file.

Creating and writing to a text file

Example 1
Program textfile(input, output);
Var Fname, txt: string[10];
Userfile:text;
Begin
Fname:=’textfile’;
Assign(userfile,’c:\’+Fname+’.txt’);
Rewrite(userfile);
Writeln(userfile,’This is structured programming’);
Writeln(userfile,’It is easy to learn and understand’);
Writeln(userfile,’If you did not understand’);
Writeln(userfile,’Please send a mail to my inbox’);
Writeln(userfile,’kenny@yahoo.com’);
Readln(txt);
Writeln(userfile,’’);
Writeln(userfile,’the user entered this text’);
Writeln(userfile,txt);
Close(userfile)
End.

Reading from a file

Example 1

Program file;
Var userfile: text;
Fname: textfile: string;
Begin
Writeln(‘Enter the name of the file’++(with its full path)of the text file:’);
Readln(Fname);
Assign(userfile,Fname+’.textfile’);
Reset(userfile);

47 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Repeat
Readln(userfile,textfile);
Writeln(textfile);
Until EOF(userfile);
Close(userfile);
Readln;
End.

Creating data files

Program files;
Type studentrecords=record
Name: string;
Admno: integer;
Gender: string;
Age: integer;
End;
Var student: text;
Students: studentrecords;
Begin
Assign(student,’c:\student.txt’);
Rewrite(student);
Students.name:=’John Karani’;
Students.admno:=’1234’;
Students.gender:=’Male’;
Students.age:=22;
Writeln(‘name:=students.name’);
Writeln(‘admno:=students.admno’);
Writeln(‘gender:=students.gender’);
Writeln(‘age:=students.age’);
Writeln(students);
Readln;
End.

48 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


PROGRAM DOCUMENTATION
Program documentation describes information that helps users, managers and people involved that must
interact with the system. Explains the use and technical operation of the system.

Importance of documentation
 Reduces downtime costs.
 Speeds maintenance costs.
 Supports system users
Types of program documentation
 System documentation
Describes system function and how they are implemented. This includes data dictionary, flowcharts,
data flow diagrams, object oriented models, screen layout and source documents.
 Operational documentation
Contains all the information needed for processing and distributing online and printed output. It
includes: system analyst, programmer and system identification. Input files, scheduling information
for printed output and emails and report distributing lists.
 User documentation
Consists of instructions and information to the system end-users who will interact with the system. It
includes: user manuals, help screens and tutorials.

Writing a program documentation

 User manuals
The styles and formats used in user manuals include the following.
Headings
Marks he key contents
Lists
Use numbered and bulleted lists to help the user scan information quickly.
Special notices
Use notices and warning to alert user to some potential problems.
Instructional design
Use standard design of instructions.
Graphics
Shows readers key components of the objects they will be working with.

49 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


Tables
Provides statistical information and easy to access.

Components of a user manual


 Front and back covers
 Title
 Edition notice
 Trademarks
 Disclaimers.
 Warranties
 Licence agreements
 Safety notice
 Preface
 Appendices
 Glossary
 Index

50 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL


51 PASCAL TUTORIALS PREPARED BY: KABA N. DANIEL

You might also like