cs110 Notes2

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 71

Introduction to Programming

THE COPPERBELT UNIVERSITY


SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

INTRODUCTION
A computer is a device that accepts data, processes the data in accordance with a stored program,
generates results, and usually consists of input, output, storage, arithmetic, logic, and control units. It
can also be defined as a functional unit that can perform substantial computation, including numerous
arithmetic operations or logic operations, without human intervention during a run.
Note 1: This definition, approved by the Customs Council, distinguishes a computer from similar
devices, such as hand-held calculators and certain types of control devices.
Note 2: Computers have been loosely classified into microcomputers, minicomputers, and main-frame
computers, based on their size. These distinctions are rapidly disappearing as the capabilities of even
the smaller units have increased. Microcomputers now are usually more powerful and versatile than
the minicomputers and the main-frame computers were a few years ago.

A computer is an electronic machine or digital machine that

1) takes in data and instructions (input)


2) works with the data (processing)
3) puts out information (output)

Computers are made of HARDWARE

 input devices like the keyboard and mouse


 the CPU and memory

 storage devices like hard drives

 output devices like printers and monitors

NB: Input devices and Output devices are collectively called Peripheral Devices

And SOFTWARE
(the instructions that tell the computer what to do)

 system software
 programs (application software)

Hardware is a comprehensive term for all of the physical parts of a computer, as distinguished from
the data it contains or operates on, and the software that provides instructions for the hardware to
accomplish tasks. The boundary between hardware and software is slightly blurry - firmware is
software that is “built-in” to the hardware, but such firmware is usually the province of computer
programmers and computer engineers in any case and not an issue that computer users need to concern
themselves with.
By Serah Beza Mbewe 1
Introduction to Programming

A typical computer (Personal Computer, PC) contains in a desktop or tower case the following parts:
 Motherboard which holds the CPU, main memory and other parts, and has slots for expansion
cards
 power supply - a case that holds a transformer, voltage control and fan
 storage controllers, of IDE, SCSI or other type, that control hard disk , floppy disk, CD-ROM
and other drives; the controllers sit directly on the motherboard (on-board) or on expansion
cards
 graphics controller that produces the output for the monitor
 the hard disk, floppy disk and other drives for mass storage
 interface controllers (parallel, serial, USB, Firmware) to connect the computer to external
peripheral devices such as printers or scanners

Software is a generic term for organized collections of computer data and instructions, often broken
into two major categories: system software that provides the basic non-task-specific functions of the
computer, and application software which is used by users to accomplish specific tasks.

System software is responsible for controlling, integrating, and managing the individual hardware
components of a computer system so that other software and the users of the system see it as a
functional unit without having to be concerned with the low-level details such as transferring data
from memory to disk, or rendering text onto a display. Generally, system software consists of an
operating system and some fundamental utilities such as disk formatters, file managers, display
managers, text editors, user authentication (login) and management tools, and networking and device
control software.

Application software, on the other hand, is used to accomplish specific tasks other than just running
the computer system. Application software may consist of a single program, such as an image viewer;
a small collection of programs (often called a software package) that work closely together to
accomplish a task, such as a spreadsheet or text processing system; a larger collection (often called a
software suite) of related but independent programs and packages that have a common user interface
or shared data format, such as Microsoft Office, which consists of closely integrated word processor,
spreadsheet, database, etc.; or a software system, such as a database management system, which is a
collection of fundamental programs that may provide some service to a variety of other independent
applications.

Software is created with programming languages and related utilities, which may come in several of
the above forms: single programs like script interpreters, packages containing a compiler, linker, and
other tools; and large suites (often called Integrated Development Environments) that include editors,
debuggers, and other tools for multiple languages.

Classification of Computers
Mainframe Computers
Minicomputers
Microcomputers
Supercomputers

Mainframe computers are very large, often filling an entire room. They can store enormous of
information, can perform many tasks at the same time, can communicate with many users at the same
By Serah Beza Mbewe 2
Introduction to Programming

time, and are very expensive. . The price of a mainframe computer frequently runs into the millions of
dollars. Mainframe computers usually have many terminals connected to them. These terminals look
like small computers but they are only devices used to send and receive information from the actual
computer using wires. Terminals can be located in the same room with the mainframe computer, but
they can also be in different rooms, buildings, or cities. Large businesses, government agencies, and
universities usually use this type of computer. This computer is also commonly used in big hospitals,
air line reservations companies, and many other huge companies prefer mainframe because of its
capability of retrieving data on a huge basis. This is normally too expensive and out of reach from a
salary-based person who wants a computer for his home.

Minicomputers are much smaller than mainframe computers and they are also much less expensive.
The cost of these computers can vary from a few thousand dollars to several hundred thousand dollars.
They possess most of the features found on mainframe computers, but on a more limited scale. They
can still have many terminals, but not as many as the mainframes. They can store a tremendous
amount of information, but again usually not as much as the mainframe. Medium and small
businesses typically use these computers.
Microcomputers are the types of computers we are using in your classes at Floyd College. These
computers are usually divided into desktop models and laptop models. They are terribly limited in
what they can do when compared to the larger models discussed above because they can only be used
by one person at a time, they are much slower than the larger computers, and they can not store nearly
as much information, but they are excellent when used in small businesses, homes, and school
classrooms. These computers are inexpensive and easy to use. They have become an indispensable
part of modern life. Examples are Personal computers and Notebook computers.

Super computers are the biggest in size, the most expensive in price than any other is classified and
known as super computer. It can process trillions of instructions in seconds. This computer is not used
as a PC in a home neither by a student in a college. Governments specially use this type of computer
for their different calculations and heavy jobs. Different industries also use this huge computer for
designing their products. In most of the Hollywood’s movies it is used for animation purposes. This
kind of computer is also helpful for forecasting weather reports worldwide.

Machine Language
A machine language is a (programming) language in which the instructions are in a form that allows
the computer to perform them immediately, without any further translation being required. It is the
fundamental language of the computer and first programs were written in this language
Instructions in machine language are in the form of a binary code (l s and 0s), also called machine
code, and are called machine instructions. Each instruction tells control unit what to do, length and
location of data fields that are involved in operation. Typical operations are to read, add, subtract, and
write. Each different computer design has its own unique machine codes, for example: machine code
for IBM System/370.

By Serah Beza Mbewe 3


Introduction to Programming

Binary representation of data


There are two standard binary representations of data in widespread use. The EBCDIC (extended
binary coded decimal interchange code) representation is used on IBM machines (except personal
computers) and equipment made to interface with them. The ASCII (American standard code for
information interchange) representation is used by almost all other manufacturers as well as on the
IBM PC range, and has been adopted (almost entirely) as an international standard.
Here are some examples of ASCII character codes.
0001000 backspace 0100110 &
0001101 carriage return 1000000 @
1000001 A 1100001 a
1010100 T 1110100 t
0110110 6 1111111 delete

Hexadecimal code
Programs and data are held within the computers as bit patterns (binary code). While this format is
eminently suited to a machine, it is quite unsuited to human perception. The strings of 1s and 0s are
virtually incomprehensible, and trying to count the correct number of each tends to induce dizzy
spells. For convenience hexadecimal code (or hex for short) is used. In hex each group of four bits is
replaced by a hex digit according to the following table.
Bit pattern Hex digit Bit pattern Hex digit
0000 0 1000 8
0001 1 1001 9
0010 2 1010 A
0011 3 1011 B
0100 4 1100 C
0101 5 1101 D
0110 6 1110 E
0111 7 1111 F

There are sixteen different hex digits. A byte can be written as a pair of hex digits. Hex codes are of
no interest to a computer, but they do serve as a useful guide to humans trying to understand what is
going on inside the processor. Although we use hex code for convenience in representing binary
patterns, it must be emphasised that the actual representation within the computer is as sequences of
bits.
ASCII character codes may be expressed in hexadecimal notation. Each binary string is padded out
with a leading zero so that the bits can be blocked off in groups of four. Thus, the ASCII code for ‘T’

By Serah Beza Mbewe 4


Introduction to Programming

is 0101 0100, which is written 54 in hex notation. Since some hex codes look like ordinary decimal
numbers, a tag is sometimes used to avoid confusion -for example, &54 or 5416.
Binary codes may be converted to octal or hex to make them more manageable.

Functional Elements of the Computer

The functional elements of a computer are the

 central processing unit (CPU),


 memory, and
 input/output to external devices (I/O).

Figure 1:  A typical computer design showing two multi-wire buses, an internal bus connecting
functional units within the CPU and an external bus for connecting additional computer subsystems.

Central Processing Unit

The sub-units of the CPU are

 instruction decode and CPU control,


 control of addressing for memory and I/O ports,
 data transfer control,
 data and address registers and
 arithmetic logic unit.

To keep track of the CPU steps, the processor maintains a special register, known as the program
counter. The program counter points to (contains the address of) the next instruction to be executed.
The instruction itself specifies

 the operation to be performed,


 the processor registers to be used and
 possibly data (or a pointer to data in memory).
By Serah Beza Mbewe 5
Introduction to Programming

The CPU will typically perform the following execution cycle:

use the program counter to fetch the next instruction.


decode the instruction and fetch data from memory into internal registers as required,
perform the instruction and put the result in another internal register and
set status bits in the status register as required.

The various functional units of the computer are connected by one or more multi-wire digital buses
which pass data, addresses, and control information between the units as shown in figure 1

MEMORY

There are two types of memory. These are random-access memory and read-only memory.

Random Access Memory

The random-access memory (RAM) supports both read and write operations. Integrated circuit RAM
comes in two main types:

static RAM in which a single bit of memory is simply a digital flip-flop and requires only
continuous power to maintain its state.
dynamic RAM in which a bit of memory is a storage capacitor in either the charged or discharged
condition. The term dynamic refers to the need to periodically renew or refresh the slowly
discharging capacitor.

Compared to dynamic memory, static memory has the following advantages. It is simpler to use, about
ten times faster and more reliable. On the other hand, it is more expensive, consumes more power and
requires more physical space. Because of power consumption in an IC the largest static RAM is 16K
bits. The largest dynamic RAM is 260K and hence is used for normal applications while the static
RAM is used for special fast applications within the same computer. Both types of RAM are volatile,
meaning that stored information is lost when power is removed from the chip. Some computer designs
provide a limited amount of non-volatile read/write RAM storage by using special low-power (and
slower) dynamic memories powered by re-chargeable batteries.

Read-Only Memory

Another form of non-volatile random access storage is the read-only memory (ROM). Here a single
memory bit is nothing more than a connection that is either open or closed. The most common ROM
types are known as field-programmable (as opposed to factory programmable). This programming
process consists of stepping through all the bits and setting the necessary ones by burning open the
fuse-like material associated with that bit.

There are many varieties of field-programmable ROM units:

PROM - programmable read-only memory,


EPROM - erasable PROM (using ultraviolet light), and
EEPROM (E PROM) - electrically erasable PROMs.
By Serah Beza Mbewe 6
Introduction to Programming

The most common uses of ROM memory in a computer are to provide initialization such as memory
tests and disk bootstrapping.

I/O Ports

Input and output ports are the pathways by which the CPU communicates with the world outside the
computer. The pathway may be either

 1-bit wide (bit-serial),


 8-bit wide (byte-serial), or
 16- to 32-bit wide (word-serial).

Control of the Bus

The information flow on the computer bus is time-multiplexed to allow different functional units to
use the same bus lines at different times. We will assume that only one device tries to write (drive) a
given bus line at any time. A special unit, known as a bus master, has the responsibility for controlling
the other units, which are correspondingly known as the bus slaves. If several units are capable of
becoming bus masters these units must arbitrate amongst themselves to determine which is to have
control of the bus for a given interval of time. Often a direct memory access (DMA) unit is allowed to
communicate with a slave memory without going through the CPU bus master. This allows memory
access at a higher speed than having to go through the intermediate CPU bus master.

Microprocessor and Microcomputer

The key element of a microcomputer is the LSI microprocessor chip, whose circuitry can acquire,
interpret, and execute a sequence of logical and arithmetic instructions. Although most computer
programming is done in a high level language, the processor itself deals only with binary numbers that
represent operation codes (move data, add, subtract, compare, jump, etc.) and addresses (routing
information for the data flow) of registers, memory locations or input/output data ports.

Beside the microprocessor, a complete computer requires a power supply, memory, interface circuits
to provide ports to external devices, and input/output devices such as a keyboard, display, DACs and
ADCs, and magnetic or other (optical) data storage.

MICROCHIP
A microchip (sometimes just called a “chip”) is a unit of packaged computer circuitry that has been
manufactured from a material such as silicon at a very small scale. Microchips are made for program
logic (logic or microprocessor chips) and for computer memory (memory or RAM chips). Microchips
are also made that include both logic and memory and for special purposes such as analog-to-digital
conversion, bit slicing, and gateways.

By Serah Beza Mbewe 7


Introduction to Programming

THE COPPERBELT UNIVERSITY


SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

INPUT/OUTPUT DEVICES

When using a computer the text of programs, commands to the computer and data for processing have
to be entered. Also information has to be returned from the computer to the user. This interaction
requires the use of input and output devices.

The most common input devices used by the computer are the keyboard, the mouse scanners and
microphones. The keyboard allows the entry of textual information while the mouse allows the
selection of a point on the screen by moving a screen cursor to the point and pressing a mouse button.
Using the mouse in this way allows the selection from menus on the screen etc. and is the basic
method of communicating with many current computing systems. Alternative devices to the mouse are
tracker balls, light pens and touch sensitive screens.

The most common output device is a monitor which is usually a Cathode Ray Tube device which can
display text and graphics. If hard-copy output is required then some form of printer is used.

Some devices can be used for both input and output, such as floppy disks and hard drives.

STORAGE DEVICES AND MEDIA

Backing storage:
The difference between internal memory and backing storage:

Backing storage (also known as secondary storage) means data storage that retains its contents when
the computer is switched off.  It can be used to hold both programs and data.

When you run a program or load a file they are copied from the backing store into the internal
memory.

When you save a file it is copied from the internal memory to the backing store.

It is always slower to access data from backing storage than from internal memory.
Data stored in backing storage is permanent so it is NOT lost when the computer is turned off.
Data stored in internal memory is lost when the computer is turned off.

Categories of storage media:

Backing storage can be divided into two main categories:

Magnetic media which stores the binary data on a disk or tape coated with a material that can be
magnetised differently, depending on whether a 0 or 1 is stored.
Optical media which stores the binary data in a surface that reflects laser light differently,
depending on whether a 0 or 1 is stored.
By Serah Beza Mbewe 8
Introduction to Programming

Magnetic media - Hard discs:

Data is stored by magnetising the surface of flat, circular plates


called platters which have a surface that can be magnetised.
They constantly rotate at very high speed. A read/write head
floats on a cushion of air a fraction of a millimetre above the
surface of the disc. The drive is inside a sealed unit because even
a speck of dust could cause the heads to crash.

Programs and data are held on the disc in blocks formed by


tracks and sectors. These are created when the hard disc is first
formatted and this must take place before the disc can be used.
Disc are usually supplied pre-formatted.

For a drive to read data from a disc, the read/write head must move in or out to align with the correct
track (the time to do this is called the seek time). It must wait then until the correct sector rotates round
until it underneath the the read/write head.  

Uses:
The hard disc is usually the main backing storage media for a typical computer or server. It is
used to store:
The operating system (e.g. Microsoft® Windows)
Applications software (e.g. word-processor, database, spreadsheet, etc.)
Files such as documents, music, video etc.
A typical home/school microcomputer would have a disc capacity of over 100 gigabytes.
Advantages:
Very fast access to data. Data can be read directly from any part of the hard disc (random
access). The access speed is about 1000 KB per second.
Disadvantages:
Non really!  It can however be a real disaster when they eventually fail because few home users
have the data on their home computer hard drive backed up.

Magnetic media - Floppy discs:


These can be found on most microcomputers and accept the usual 3.5 inch floppy discs. High density
discs for a PC hold 1.44 MB of data (enough to store about 350 pages of A4 text). A floppy disc needs
to be formatted before it can be used but most discs are now sold already formatted for PC’s.
Uses:

Floppy discs are useful for transferring data between computers and for keeping a back-up of
small files.
Advantages:
They are very cheap to buy and floppy disc drives are very common.
Disadvantages:

By Serah Beza Mbewe 9


Introduction to Programming

They are easily physically damaged if unprotected and magnetic fields can
damage the data.
They are relatively slow to access because floppy discs rotate far more slowly
than hard discs, at only six revolutions per second, and only start spinning when
requested. The access speed is about 36 KB per second.

Magnetic media - Magnetic Tape:

Just like the tape in a tape-recorder, the data is written to or read from the tape as it passes the
magnetic heads.

Uses:
Magnetic tapes are often used to make a copy of hard discs for back-up reasons. This is
automatically done overnight on the KLB network and the tapes are kept in a safe place away from
the server. 
Advantages:
Magnetic tape is relatively cheap and tape cassettes can store very large quantities of data
(typically 26 GB).
Disadvantages:
Accessing data is very slow and you cannot go directly to an item of data on the tape as you can
with a disc. It is necessary to start at the beginning of the tape and search for the data as the tape
goes past the heads (serial access).

Optical Media - CD-Rom: 


CD-ROM - means Compact Disc - Read Only Memory. This means you can only read from the disc,
not write or store data onto it.

They are also known as optical discs because the data is read by a laser beam reflecting or not
reflecting from the disc surface.

Like a floppy disc, a CD-ROM only starts spinning when requested and it has to spin up to the correct
speed each time it is accessed. It is much faster to access than a floppy but it is currently slower than
a hard disc.

Uses:
Most software programs are now sold on CD-Rom.
Advantages:
CD-ROM’s hold large quantities of data (650 MB).
They are relatively tough as long as the surface does not get too scratched.
Disadvantages:
You cannot save files to a CD-Rom (although CD-R and CD-RW discs now exist which can be
written to)
Comparing storage devices:

By Serah Beza Mbewe 10


Introduction to Programming

Storage 1 CD-ROM (650 MB) = 451 Floppy discs (1.44 MB)


capacity
1 DVD (4.7 GB) = 7 CD-ROM’s (650 MB)
Access Harddrive CD-ROM Floppy disc
speed 1000 KB/s 100 KB/s 36 KB/s

DATA AND INFORMATION

In computer science theory there is a clear distinction between data and information, where data is a
measurement that can be disorganized and when the data becomes organized it becomes information.
Data can be about reality or fiction such as a fictional movie. Data about reality consist of
propositions. A large class of practically important propositions are measurements or observations of a
variable. Such propositions may comprise numbers, words, or images. In the context of data
processing, data are defined as numbers or characters that represent measurements from observable
phenomena. A single datum is a single measurement from observable phenomena. Measured
information is then algorithmically derived and/or logically deduced and/or statistically calculated
from multiple data. (evidence). Information is defined as either a meaningful answer to a query or a
meaningful stimulus that can cascade into further queries. Information is the result of processing,
manipulating and organizing data in a way that adds to the knowledge of the receiver. In other words,
it is the context in which data is taken

DATA PROCESSING

Data processing is any computer process that converts data into information or knowledge. The
processing is usually assumed to be automated and running on a computer. Because data are most
useful when well-presented and actually informative, data-processing systems are often referred to as
information systems to emphasize their practicality. Nevertheless, both terms are roughly
synonymous, performing similar conversions; data-processing systems typically manipulate raw data
into information, and likewise information systems typically take raw data as input to produce
information as output. More generally, the term data processing can apply to any process that converts
data from one format to another.

DATA PROCESSING MODEL

The data processing model outline the stages that are needed to trasform data into infromation. These
stages are Input stage, Process stage, Output or Storage Stage.The data to be processed has to be
captured by an input device like the keybourd, mouse or microphone. That is, its loaded in Main
momery. Then it is processed by the CPU. After being processed, it is either output using the either the
monitor or speaker, or it is stored on a permanent storage meduim.

Processing
Data By CPU Information

Loaded in Main Memory Output/Stored

By Serah Beza Mbewe 11


Introduction to Programming

DATA PROCESSING METHODS


The data processing methods are Real-Time, Batch, Online, Time-sharing, Distributed Processing
Distributed computing is a method of computer processing in which different parts of a program run
simultaneously on two or more computers that are communicating with each other over a network.
Distributed computing is a type of parallel computing. But the latter term is most commonly used to
refer to processing in which different parts of a program run simultaneously on two or more processors
that are part of the same computer. While both types of processing require that a program be
parallelized—divided into sections that can run simultaneously, distributed computing also requires
that the division of the program take into account the different environments on which the different
sections of the program will be running. For example, two computers are likely to have different file
systems and different hardware components.

A batch processing system is one where programs and data are collected together in a batch before
processing starts. Each piece of work for a batch processing system is called a job. A job usually
consists of a program and the data to be run. Jobs are stored in job queues until the computer is ready
to process them. There is no interaction between the user and the computer while the program is being
run. Computers which do batch processing often operate at night. Example: Payroll - when a
company calculates the wages for its workforce and prints pay slips.

Realtime or real-time as a general concept refers to a system that responds to events or signals as fast
as possible, or as they happen; Real-time operating systems are designed to respond to an event within
a predetermined time. These types of operating systems are found within environments where
computers are responsible for controlling systems. For Example: Robotics, manufacturing, special
military applications
Time-share Processing involves the CPU allocating individual slices of time to a number of users on
the computer system. As the number of users increases the response time for each terminal declines.
The speed of the CPU compared to that of the VDU and terminal is so much faster that it gives the
user the impression that they are the sole user of the system.

Online Transaction Processing (or OLTP) is a class of programs that facilitate and manage
transaction-oriented applications, typically for data entry and retrieval transaction processing.The term
Online Transaction Processing is somewhat ambiguous: some understand “transaction” as a reference
to computer or database transactions, while others (such as the Transaction Processing Performance
Council) define it in terms of business or commercial transactions. This is the type of processing that
is used by most of the applications found on the internet. Example are signing in your email account,
online-applications for a place at a particular university, and online shopping, where you can buy a
book on the internet.

FILE ORGANIZATION
A file is an organized collection of related records. A record is a collection of related fields. A field is
a single data item. A master file is the main file for an application - a large file of semi-permanent
data. A transaction file is a temporary file used to store data which will be used to update the master
file.
Example. The diagram shows a small part of a school database which stores information about its
pupils.

By Serah Beza Mbewe 12


Introduction to Programming

NUMBER SURNAME FORENAME YEAR FORM DOB


92013 JONES Sidney 12 B 23/04/78
92107 LAIDLAW Lorraine 12 Y 12/11/79
92114 MERRITT Mandy 12 G 08/03/79
92167 NASH Natasha 12 B 19/08/78

There are 4 records displayed. Each record has 6  fields. The key field is the field which uniquely
identifies each record. The key field in the example is NUMBER

If this wasn’t done a mix up could occur and, for example, the wrong parents could get the wrong
reports. One or more fields could be used to keep records in a certain order (e.g. alphabetical) in
which case the file is said to be ordered.

FILE ACCESS METHOD

There are two main ways of storing data on backing store are sequential-access and direct-access and
random-access.

Sequential access

The record are stored in sequence, e.i. one after the other. Records in a file opened for sequential
access can be accessed only in the order in which they were written to the file. A sequential file may
consist of either formatted or unformatted records.

Direct access (Indexed)

Each new record is placed at the end of the file in the first unoccupied slot. The value of the record’s
primary key and the record’s location are then added to the index file. Direct access would be used
when the computer needs to locate an item quickly by moving directly to its record. Direct access
requires some kind of index to be held on the medium (the material storing the data). Thus records can
be ordered or unordered and accessed sequentially (one at a time); the required record will be
identified by the key field.

Random Access (Hashed)

In hashed files, each new record is placed at the record number calculated by the hash function. The
record is then stored in that calculated slot. This method should be used for RMS files that are static in
nature and in which few additions and deletions of records need to be made. The record can be
retrieved using the calculated hash function.
COMPUTER SECURITY
Computer security is the effort to create a secure computing platform, designed so that agents (users or
programs) can only perform actions that have been allowed. This involves specifying and
implementing a security policy. The actions in question can be reduced to operations of access,
modification and deletion. Computer security can be seen as a subfield of security engineering, which
looks at broader security issues in addition to computer security.

By Serah Beza Mbewe 13


Introduction to Programming

THE COPPERBELT UNIVERSITY


SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

PROGRAMMING

Programming can be broadly defined as


Instructing a computer to do something for you with the help of a programming language.
The process of translating the system specifications prepared during the design stage into
program code.
A program can be defined as a set of instructions that is written in a programming language. It is a
complete statement of a solution to a problem capable of being executed on a computer.
There are two types of programming languages; namely:
 Low- Level Languages (Machine and Assembly Languages)
 High Level Languages (general purpose and special purpose)

LOW-LEVEL LANGUAGES
In computing a programming language designed for a particular computer and reflecting its internal
machine code. Low-level languages are therefore often described as machine-oriented languages.
They cannot easily be converted to run on a computer with a different central processing unit, and they
are relatively difficult to learn because a detailed knowledge of the internal working of the computer is
required.

All computers operate by following machine language programs, a long sequence of instructions
called machine code that is addressed to the hardware of the computer and is written in binary
notation (see numeration), which uses only the digits 1 and 0. First-generation languages, called
machine languages, required the writing of long strings of binary numbers to represent such
operations as “add,” “subtract,” “and compare.” Later improvements allowed octal, decimal, or
hexadecimal representation of the binary strings.

Low-Level Languages are machine-oriented languages in which each instruction corresponds to or


resembles a machine instruction. An Assembly Language is a low-level language; it uses symbolic
operation code to represent machine operation code. It is a symbolic representation of machine code
instructions on a 1:1 basis:- one assembly language instruction is substituted for one machine-code
instruction
Each computer manufacturer normally devises an Assembly Language that corresponds closely to the
particular machine language used by that manufacturer.Groups of letters (symbols) are used by the
programmer when writing his program. These codes are usually MNEMONIC, which means that their
sound suggests their meaning, eg, LDA might stand for the function LoaD Accumulator.
It is usual to describe the function code as mnemonic and addresses or labels as symbolic.

By Serah Beza Mbewe 14


Introduction to Programming

Example. “LDA N” means “LoaD Accumulator with contents of address N”. LDA is a mnemonic
opcode (function code) and N is a symbolic address.
Mnemonic Meaning
LDA Load accumulator
STA Store contents of accumulator (in memory location)
ADC Add with carry
JMP Jump (to address)
BEQ Branch if equal to zero
CLC Clear carry flag

E.g. AP, ADD, or plus sign may indicate addition step.


A special program called an Assembler may be provided, which will convert a program in symbolic
and mnemonic form into machine code. The mnemonic and symbolic program (written in Assembly
Language) is called the source program for the assembler and the machine code produced by the
assembler is called the object program

Common features of low-level languages.


a. MNEMONIC codes are used in place of machine codes, eg, using LDA 5 in place of
0000000000000101.
b. Symbolic addresses are frequently used instead of actual machine addresses, eg, using LDA N
where N stands for the address, 4hich can be assigned a numerical value at a more convenient
time.

Advantages and disadvantages of Assembly Language over Machine code


There are two obvious advantages of symbolic code over machine code:
1 It is easier to learn and to use a mnemonic such as AP than to learn and use “11111010” to
cause two decimal fields to be added.

2 It is easier to locate, correct, and/or modify instructions written with mnemonics and symbolic
field names.

Two disadvantages of machine code are not solved by using assembler. These are:
 Instructions are still being written at the machine-code level - that is, one assembler
instruction is substituted for one machine-code instruction.
o Assembler-level languages are said to be machine-oriented because the
programmer must be aware of particular machine’s characteristics and
requirements as program is written.
o If computer design requires that data be in particular format, it is
programmer’s responsibility to make sure that data are in required format or
to write instructions to convert those data to required format.
 Assembly languages are usually unique to particular computer
series.
o The only case in which assembler code is compatible with different computer series
is one in which computer manufacturer has chosen mnemonic operation codes that
match those of another manufacturer
o This requires similar hardware characteristics, and it is not common occurrence
By Serah Beza Mbewe 15
Introduction to Programming

o Change in computer CPU still requires learning new language and converting of all
existing programs - a very expensive undertaking.

HIGH-LEVEL LANGUAGES
These are a type of advanced computer programming languages that isn’t limited by the type of
computer or for one specific job and is more easily understood. Today, there are dozens of high-level
languages; some commonly used high-level languages are BASIC, C, FORTAN and Pascal. They are
used to write programs that are more or less independent of a particular type of computer. Such
languages are considered high-level because they are closer to human languages and further from
machine languages. In contrast, assembly languages are considered low-level because they are very
close to machine languages.

The main advantage of high-level languages over low-level languages is that they are easier to read,
write, and maintain. Ultimately, programs written in a high-level language must be translated into
machine language by a compiler or interpreter. The lack of portability between different computers
also led to the development of high-level languages-so called because they permitted a programmer to
ignore many low-level details of the computer’s hardware.

SPECIAL PURPOSE HHL

These are programming languages that were developed to be used in solving one particular problem or
to be used in a particular field of interest. The follow are some examples:

 FORTRAN [FORmula TRANslation], was developed for scientific and engineering


applications about 1956 by John Backus.
 • LISP [LIST Processing], programming language that handled recursive algorithms
better. It was developed by John McCarthy at the Massachusetts Institute of Technology in the
early 1950s; implemented in 1959, it has become the standard language for the artificial
intelligence community.

 COBOL [COmmon Business Oriented Language], the first language intended for commercial
applications, is still widely used; it was developed by a committee of computer manufacturers
and users under the leadership of Grace Hopper, a U.S. Navy programmer, in 1959.

 ALGOL [ALGOrithmic Language], developed in Europe about 1958, is used primarily in


mathematics and science

 PL/1 [Programming Language 1], developed in the late 1960s by the IBM Corp., and ADA [for
Ada Augusta, countess of Lovelace, biographer of Charles Babbage], developed in 1981 by the
U.S. Dept. of Defense, are designed for both business and scientific use.

GENERAL PURPOSE HHL

These are programming languages that can be used to develop any kind of program. They can be used
to develop programs to solve mathematical problems, business problems, recursive problems,
scientific problems and so on. The languages have in them the ability that allows the programmer to
develop any type of program depending on the requirements given to her/him. Examples are
By Serah Beza Mbewe 16
Introduction to Programming

PASCAL, BASIC, C, C++ and so on. The general programming languages can be either structural or
modular or both.

structured programming
Structured programming is a subset of procedural programming that enforces a logical structure on the
program being written to make it more efficient and easier to understand and modify. Certain
languages such as Ada, Pascal, and dBASE are designed with features that encourage or enforce a
logical program structure.

Structured programming frequently employs a top-down design model, in which developers map out
the overall program structure into separate subsections. A defined function or set of similar functions
is coded in a separate module or submodule, which means that code can be loaded into memory more
efficiently and that modules can be reused in other programs. After a module has been tested
individually, it is then integrated with other modules into the overall program structure.

Program flow follows a simple hierarchical model that employs looping constructs such as “for,”
“repeat,” and “while.” Use of the “Go To” statement is discouraged.
Therefore structured programming can be defined as a technique for organizing and coding computer
programs in which a hierarchy of modules is used, each having a single entry and a single exit point,
and in which control is passed downward through the structure without unconditional branches to
higher levels of the structure. Three types of control flow are used: sequential, test, and iteration.

MODULAR PROGRAMMING

Modular programming is subdividing your program into separate subprograms such as functions and
subroutines. For example, if your program needs initial and boundary conditions, use subroutines to
set them. Then if someone else wants to compute a different solution using your program, only these
subroutines need to be changed. This is a lot easier than having to read through a program line by line,
trying to figure out what each line is supposed to do and whether it needs to be changed. And in ten
years from now, you yourself will probably no longer remember how the program worked.

Subprograms make your actual program shorter, hence easier to read and understand. Further, the
arguments show exactly what information a subprogram is using. That makes it easier to figure out
whether it needs to be changed when you are modifying your program. Forgetting to change all
occurrences of a variable is a very common source of errors.

Subprograms make it simpler to figure out how the program operates. If the boundary conditions are
implemented using a subroutine, your program can be searched for this subroutine to find all places
where the boundary conditions are used. This might include some unexpected places, such as in the
output, or in performing a numerical check on the overall accuracy of the program.

Subprograms reduce the likelihood of bugs. Because subprograms can use local variables, there is less
change that the code in the subroutine interferes with that of the program itself, or with that in other
subprograms. The smaller size of the individual modules also makes it easier to understand the global
effects of changing a variable.

Perform your output using a subprogram. You tend to become more careless when programming a ‘no
critical’ program part such as output. Also, output often requires additional variables not of interest to
By Serah Beza Mbewe 17
Introduction to Programming

the rest of the program. The code for output tends to be lengthy; hence your program will become
shorter and easier to read if you move output to a subroutine.

Use the correct type of subprogram. For example, if your program uses an exact solution, cast it into
the form of a function subprogram, not a subroutine. Clarity and ease of use improve.

THE PROGRAM DEVELOPMENT PROCESS


The program development process outlines the stages that are required to follow in order to come with
a program that will be able to solve the problem without missing the main purpose of developing the
program in the first place. The stages to follow when developing a program are as follows: Problem
Definition, Analysis and Design, Coding, Testing, Documentation and Maintenance.
To effectively get the stages, we will develop a program that adds two numbers and outputs the result.

1. Problem definition

In this stage, we have to effectively establish what exactly the problem is. In our case the problem is
to develop a program that should add two numbers and display the result so that the user of the
program can view it.

2. Analysis

Broadly speaking, the analysis will define the inputs, processing and outputs required. A good analysis
will normally specify what processing is needed by giving the exact relationship between outputs and
the inputs from which they are derived rather than prescribing how the program should be written. In
out case, we should specify the input, which is the two numbers (denoted A and B) to be add; the
output which is the result (denoted C) obtained after the two number are add. We also have to establish
the process required to obtain the result which is addition.
3. Design: Plan and develop the solution to the problem.
Find a logical sequence of precise steps that solve the problem, called an algorithm. Depending upon
the extent of the task, the program preparation may be shared amongst many programmers. Such co-
operation requires an overall plan. Large programs may require each programmer to write a separate
part of the program. These separate parts are often called modules or segments. The modules may be
prepared and tested separately, then linked together to be tested as a whole, a process known as
integration.
Modern approaches to programming recognize the fact that complicated problems can be solved most
easily if they are broken down into simpler, more manageable tasks in a step-by- step fashion. At each
step the problem is broken down further and consideration of details is put off as long as possible. This
general approach is known as top down programming by stepwise refinement. In out case we can
come up with the following design:

Step 1
Input A and B

Step 2
C= A+B

By Serah Beza Mbewe 18


Introduction to Programming

Step 3

Display C
This completes the design needed to solve our problem. And this is called an Algorithm.

DESIGN TOOLS
FLOWCHARTS
One of the most powerful facilities available in programming languages is the ability to perform
operations selectively under certain conditions. A flowchart is logic diagram that describes each step
that the program must perform to arrive at the solution and how the steps relate to each other. It is a
popular logic tool used for showing an algorithm in graphics form
Programmer prepares flowchart before coding. They are not used very often today because of newer
superior methods. Most common Flow chart symbols are

Direction Start / End Input / Output Decision Process Connector


(Flow line and
Arrowhead)
The most important point: it is vital to be quite clear precisely under what conditions operations are to
be carried out by a program. These conditions must be expressed as program instructions in the
simplest and clearest manner possible. In its most general sense, a conditional operation implies a
choice between two alternatives, with a condition for making the choice.

For example
If the weather is fine then go fishing
else watch television.

If the condition (the weather is fine) is true, then the first action (go fishing) is carried out. If the
condition is false, then the second action (watch television) is carried out.
The following figure illustrates this process in terms of flow diagram symbols.

By Serah Beza Mbewe 19


Introduction to Programming

pseudo codeCS110 NOTES.ppt


Pseudo means imitation. So pseudo code is an imitation of actual computer instructions. It is a notation
for program design using keywords from a programming language mixed with natural language (e.g.
English) which outlines the task to be performed. It is also called Program Design Language (PDL). It
has no formal syntactical rules. The principal aim is to allow the programmer to express his
understanding of the problem and its proposed solution; he must write down a sequence of
successively more detailed descriptions of the problem and its solution which can be read and
understood by a human being (perhaps another programmer) and so checked for correctness. The
flowchart only emphasizes logical steps (detailed plan) for a program; pseudocode emphasizes both
logical steps and a top-down structure for a program.

FLOWCHARTS AND PSEUDOCODES FOR MAIN PROGRAM CONTROL STRUCTURES

1 SELECTION

a) If statement
An If block allows a program to decide on a course of action based on whether
a certain condition is true or false. A block of the form
If condition Then
Action l
Else
action 2
End If
causes the program to take action 1 if condition is true and action 2 if condition is false. Each action
consists of one or more Visual Basic statements. After an action is taken, execution continues with the
line after the If block.

By Serah Beza Mbewe 20


Introduction to Programming

Flowchart:

Pseudocode:
If condition is true Then
Processing step(s) 1
Else
Processing step(s) 2
End If

b)Select Case

Flowchart:

Pseudocode:
Select Case selector
Case valuelist1
Action 1
Case valuelist2
Action 2
:

Case valuelistn
Action n
By Serah Beza Mbewe 21
Introduction to Programming

Case Else
Action of last resort
End Select

2 LOOPS
A loop, one of the most important structures in Visual Basic, is used to repeat a sequence of statements
a number of times. At each repetition, or pass, the statements act upon variables whose values are
changing.

a) Do Loops
The Do loop repeats a sequence of statements either as long as or until a certain condition is true. A
Do statement precedes the sequence of statements, and a Loop statement follows the sequence of
statements. The condition, along with either the word While or Until, follows the word Do or the word
Loop. When Visual Basic executes a Do loop of the form
Do While condition
statement (s)
Loop
it first checks the truth value of condition. If condition is false, then the statements inside the loop are
not executed, and the program continues with the line after the Loop statement, if condition is true,
then the statements inside the loop are executed. When the statement Loop is encountered, the entire
process is repeated, beginning with the testing of condition in the Do While statement. In other words,
the statements inside the loop are repeatedly executed only as long as (that is, while) the condition is
true.

Flowchart:

Pseudocode:

Do While condition is true


Processing step(s)
Loop

b) For … Next
When program execution reaches a For….Next loop, such as the one shown previously, the For
statement assigns to the control variable i the initial value 1 and checks to see whether i is greater than
the terminating value n. If so, then execution jumps to the line following the Next statement. If i <= n,
the statements inside the loop are executed. Then, the Next statement increases the value of i by 1 and
checks this new value to see if it exceeds n. If not, the entire process is repeated until the value of i
exceeds n. When this happens, the program moves to the line following the loop.

By Serah Beza Mbewe 22


Introduction to Programming

For i = 1 to n
Processing step(s)
Next i

Desk Checking
The process of testing the flowchart with different data as input, and checking the output. The test data
should include nonstandard data as well as typical data.
A number of different relations used in a condition are:
= equal
< less than
 greater than
<= less than or equal to
>= greater than or equal
<> not equal to

Purpose of Flowcharting:
• An aid in developing the logic of a program.
• Verification that all possible conditions have been considered in a program.
• Provides means of communication with others about the program.
• A guide in coding the program.
• Documentation for the program.

Flowchart has two major disadvantages:


Any modification in the program requires new flowchart to be drawn.
b) Does not emphasize top-down structure of program.

By Serah Beza Mbewe 23


Introduction to Programming

Pseudo-code (or Structured English)


Pseudo means imitation. So pseudocode is an imitation of actual computer instructions. It is a notation
for program design using keywords from a programming language mixed with natural language (e.g.
English) which outlines the task to be performed. It is also called Program Design Language (PDL). It
has no formal syntactical rules.
The principal aim is to allow the programmer to express his understanding of the problem and its
proposed solution; he must write down a sequence of successively more detailed descriptions of the
problem and its solution which can be read and understood by a human being (perhaps another
programmer) and so checked for correctness. The flowchart only emphasizes logical steps (detailed
plan) for a program; pseudocode emphasizes both logical steps and a top-down structure for a
program.

Basic pseudocode structures are


 sequence logic (top to bottom,.),
:
process 1
process 2
:
 decision logic (IF THEN ELSE),
:
IF condition (THEN)

Process 1
(ELSE
Process 2)

ENDIF
:
 logic to produce loops No : Yes DOWHILE condition

process 1
process 2

ENDDO
:
DO UNTIL condition
process 1 no
process 2
yes
ENDDO
Advantages of pseudocode:
a) It structures the program into a sequence that is easy to convert to a programming
language and a structure that is easy to follow logically and / or to modify.
By Serah Beza Mbewe 24
Introduction to Programming

b) It is easy to write and redo in order to reflect program modifications. It has only few
rules to follow, allowing programmer to concentrate on logic of program.

Considering the example in previous section,


If the weather is fine then go fishing
else watch television
pseudo-code can be written as
IF the weather is fine THEN
go fishing

ELSE
watch television.

ENDIF
Another Example of Pseudocode:
Determine the average grade of a class:
1 Initialize Sum to zero
2 Do while there are more data
2.1 Input next Grade
2.2 Add Grade to Sum
2.3 Increment Counter
2.4 Loop
3 Compute average = Sum / Counter
4 Display average

Several advantages can be gained from using this formal notation for program specifications:
a. Potential ambiguities can be identified and eliminated from the specification at an early stage
in development.

b. It simplifies the overall task by separating concerns about what is required from matters of how
to achieve it.

c. It avoids placing unnecessary and undesirable restrictions upon how the implementation is
done.

d. It is at a sufficiently high level that it may serve as a specification for more than one
implementation. For example, the specification may first be used for a simple, quick, low-cost
but inefficient implementation that may later be replaced by a higher - quality alternative.

4. Code: translate the algorithm into a programming language.

This may be regarded as the last step in stepwise refinement. Coding is the technical word for writing
the program. The instructions written in pseudo code are written in a programming language, like
Pascal and entered into the computer. For our example, the program would appear as follows:

Program Adding_Two_Numbers;

By Serah Beza Mbewe 25


Introduction to Programming

Var
A,B,C: integer;

Begin

Writeln(‘Enter first Value’);


Readln(A);
Writeln(‘Enter Second Value’);
Readln(B);

C:=A+B;
Writeln©
Readln;

End.

5. Test and debug: Locate and remove any errors in the


program
Testing is the process of finding errors in the program and debugging is the process of correcting
errors that are found. (An error in a program is called a bug.) As the program is typed, VB points out
syntax types of program errors; logical errors, resulting from flaws in the algorithm, will be detected
when you run the program.
This can be quite a lengthy, and expensive, process. Careful and thorough design in the early stages of
programming will help to minimise these errors. The later an error is discovered the more expensive
and troublesome it will be to eliminate it.
There are several stages of testing:
a. Unit testing, this involves testing the separate components as they are produced.
b. Integration testing, this involves testing the separate components as they are put together.
c. System testing, which involves testing the whole program once it is in the final form in
which it is to be used.
d. User acceptance testing, which involves the user of the program (possibly the customer)
testing the program to see that it is what is required.

6. Complete the documentation: organize all the material that describes the program
It is very important that the work of the programmer in producing a finished program is fully
documented to allow another person at a later date to understand the program. This documentation will
include a statement of the problem (system specification), remarks in a program which point out
purposes of various parts of the program (internal documentation), pseudo code, flowcharts, hierarchy
charts, test data and results. Producing these documents should be done as part of each stage in
programming and not as an afterthought. If this is done the documentation will aid the maintenance of
the program during its lifetime.

By Serah Beza Mbewe 26


Introduction to Programming

GOOD QUALITIES OF A PROGRAM


External qualities: What the user cares about.
 Usefulness — does it do what the user wants?
 Performance — is it fast enough and can it fit in my computer? (Speed, size).
 Correctness — does it meet its specification? (Assumes precise specification)
 Reliability — does it do what the user wants most of the time?
 Robustness — does it respond well to error/failures of other systems?
 Usability — is it easy to use?
 Interoperability — does is conform to relevant standards/formats etc.?
 User documentation.

Bottom up methods
It is clear that many problems that occur in programming, and system design, are too large to be
solved all at once. The answer is to try to solve such problems in stages. But where should one begin?
If the problem is different from anything met before, it may be necessary to set about solving a part of
the problem that is understood, and then, as other parts of the problem become clearer, solving them
until the whole problem is solved. Such an approach in which the whole situation is built up by joining
together the completed parts is called a “bottom up” approach. In this approach one start from what
output is needed from the system, then they go on to determine what input and process will produce
the output needed.

Top down methods


There is one severe danger inherent in the bottom up approach; the various parts may not fit together
properly, and, in some cases, considerable effort may be necessary to overcome this problem. “Top
down” methods attempt to avoid such problems by starting with the general concept of what is
required, breaking the whole into component parts, and then tackling the component parts in the same
manner. The interrelationships between components are decided upon before the components are
created so that the final integration of the parts into the whole should be more straightforward. A
number of methods in use today may be described as top down.
THE COPPERBELT UNIVERSITY
SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

BOOLEAN ALGEBRA
One of the primary requirements when dealing with digital circuits is to find ways to make them as
simple as possible. This constantly requires that complex logical expressions be reduced to simpler
expressions that nevertheless produce the same results under all possible conditions. The simpler
expression can then be implemented with a smaller, simpler circuit, which in turn saves the price of
the unnecessary gates, reduces the number of gates needed, and reduces the power and the amount of
space required by those gates.
One tool to reduce logical expressions is the mathematics of logical expressions, introduced by George
Boole in 1854 and known today as Boolean Algebra. The rules of Boolean Algebra are simple and
straight-forward, and can be applied to any logical expression. The resulting reduced expression can
then be readily tested with a Truth Table, to verify that the reduction was valid.
By Serah Beza Mbewe 27
Introduction to Programming

The rules of Boolean Algebra are:.

AND Operations (·)


Value for A Value for B Result of A.B
False False False
True False False
False True False
True True True

Or in digital form this will be represented as follows:


0·0 = 0 A·0 = 0
1·0 = 0 A·1 = A
0·1 = 0 A·A = A
1·1 = 1 A·A’ = 0

OR Operations (+)
Value for A Value for B Result of A+B
False False False
True False True
False True True
True True True

Or in digital form this will be represented as follows:


0+0 = 0 A+0 = A
1+0 = 1 A+1 = 1
0+1 = 1 A+A = A
1+1 = 1 A+A’ = 1

NOT Operations (‘)


Value for A Result of ‘A
False True
True False

Or in digital form this will be represented as follows:


0’ = 1 A” = A
1’ = 0

Associative Law
(A·B)·C = A·(B·C) = A·B·C
(A+B)+C = A+(B+C) = A+B+C

By Serah Beza Mbewe 28


Introduction to Programming

Distributive Law

A·(B+C) = (A·B) + (A·C)

A+(B·C) = (A+B) · (A+C)


Commutative Law

A·B = B·A
A+B = B+A

Precedence

AB = A·B
A·B+C = (A·B) + C
A+B·C = A + (B·C)

DeMorgan’s Theorem
(A·B)’ = A’ + B’ (NAND)
(A+B)’ = A’ · B’ (NOR)

BOOLEAN VARIABLES
Let’s take a look at a boolean type variable, which is only allowed to take on two different values,
TRUE or FALSE. This variable is used for loop controls, end of file indicators or any other TRUE or
FALSE conditions in the program. Variables can be compared to determine a boolean value. A
complete list of the relational operators available with Pascal is given in the following list.
= equal to
<> not equal to
 greater than
< less than
>= greater than or equal to
<= less than or equal to
These operators can be used to compare any of the simple types of data including integer, char, byte,
and real type variables or constants, and they can be used to compare boolean variables.

WHERE DO WE USE THE BOOLEAN VARIABLES


We will find many uses for the boolean type variable when we study the loops and conditional
statements soon, but until then we can only learn what they are. Often, in a conditional statement, you
will want to do something if both of two things are true, in which case you will use the reserved word
and with two boolean expressions. If both are true, the result will be true.

By Serah Beza Mbewe 29


Introduction to Programming

SHORT CIRCUIT OR COMPLETE EVALUATION


Suppose you have several boolean expressions “and”ed together, and when evaluation starts, the first
expression results in a FALSE. Since the first expression is FALSE, it is impossible for the following
expressions to ever allow the final result to be TRUE because the first FALSE will force the answer to
be FALSE. It seems like a waste of execution time to continue evaluating terms if the final result is
already known, but that is exactly what standard Pascal will do because of the language definition.
This is known as complete evaluation of a boolean expression. If the system is smart enough to realize
that the final result is known, it could stop evaluation as soon as the final result is known. This is
known as short circuit evaluation of a boolean expression, and could also be applied if a term of an
“or”ed boolean expression resulted in a TRUE, since the result would always be TRUE.
TURBO Pascal versions 5.0 and later, allows you to choose between complete evaluation or short
circuit evaluation. The default for these compilers is the short circuit form but it can be changed
through the Options menu when you are using the integrated environment, or through use of a
compiler directive.

EXERSICE ONE

Given that a=7, b=5, c=-9 and d=-88. Are the following
expressions true or false?
Not((a>b) or (a<>d))
((c<a) and (Not(c=d))) or (c<d)
((2<a) or (7>c)) and (b<d)

By Serah Beza Mbewe 30


Introduction to Programming

THE COPPERBELT UNIVERSITY


SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

HOW TO USE PASCAL


Opening and Saving files in Pascal

Opening and closing your files in Pascal follows the usual method of:
* File Menu
* Open (or Save)
* Select the File (or type in the file name)
* Click Open (or Save)

This is exactly the same as you would do in any word processing program. Alternatively you can press
F2 to save your program. It is a good idea to save your work regularly.

Exiting Pascal

To exit Pascal:

• File Menu
* Exit

Alternatively you can press Alt-x to exit.

Compiling and Running Your Program

It is VERY important that you know how to do this so make sure you remember it.

Compiling:

When you compile your program, Pascal checks it for errors. If there are any errors Pascal tells you. If
you don’t understand what the error means then look up the error in the help. To compile your
program press F9 or you can select Compile from the Compile menu.

Running Your Program:

To run your program press Ctrl+F9, or select Run from the Compile menu. This command compiles
your program. Then if the compilation was successful your program will be run.

By Serah Beza Mbewe 31


Introduction to Programming

PROGRAM STRUCTURE
Pascal is a structured programming language which as such follows a particular structure that has to be
followed for the program to run. The Pascal programming language has several important words in it.
These are called keywords1. In example programs keywords will be displayed in bold. We shall look at
some basic keywords and structure of your Pascal programs.
Program Heading

Declaration

Main Program

A program must begin with the keyword ‘Program’, followed by your program name. This keyword is
useful. It lets you identify what the program does quickly and easily(Program Heading).

After this comes the keyword ‘var’. This is followed by any variables you wish to use in your
program. If you are not using any variables then you do not need the ‘var’ keyword. Pascal will report
an error if you try to use the ‘var’ keyword without any variables (Declaration).

After this comes the keyword ‘begin’. This indicates the beginning of the main part of your program.
After this comes your program code. The end of the program is indicated by the keyword ‘end.’. Note
the full stop after the word ‘end’(Main Program).

It is a good idea to comment your code so you can understand what it is doing if you look at it later. It
is also important so that other people can understand it also. In Pascal you can comment your code in
two different ways. Either {to start the comment and} to end the comment or (* to start the comment
and *) to end the comment. For example:
Program Add;     {Program Heading}
Var
a,b,c:integer; {Declaration}
Begin
Writeln(‘Enter value for a: ‘);
Read(a); (*Main Program*)
Writeln(‘Enter value for b: ‘);
Read(b);
c:= a+b;
writeln(‘a + b =’,c);
End.

This program allow the use to enter the value in memory location a and memory location b, the adds
the two values and assigns them to memory location c. then finally displays the result.

There are also several other keywords, which are optional and must come before ‘var’. Some of these
are ‘type’, ‘const’ and ‘uses’. ‘Const’ declares any constant values to use throughout your program.
These are anything which is always the same, such as the number of days in the week. Alternatively if
1
Keyword
A word, reserved by Pascal, for special use.Such as the program keyword which is reserved for declaration of the program
name. Keywords cannot be used for any other purpose. They are also sometimes called reserved words.

By Serah Beza Mbewe 32


Introduction to Programming

you use a set value throughout your program, it is a good idea to make this a constant value so that it
can easily be changed if you later decide to do so. The type keyword will be discussed later.

The ‘Uses’ keyword allows your program to use extra commands. These extra commands are stored
together in what is called a module or library. These modules have names such as CRT, or GRAPH.
Each module contains several extra commands. These commands will be related in some way. For
example GRAPH contains extra commands to do with graphics. CRT contains many general
commands. (Even though CRT stands for Cathode Ray Tube - ie. the screen)

eg.
uses crt, graph;    {This means pascal allows you to uses the extra commands in
the crt and graph modules}
const
    InchesInFoot = 12;     {These are some constants you might use}
    DaysInWeek=7;
    e = 2.1718281828;
type
    {Type definitions go here - don’t worry about these yet}
var (*variables are declared here*)
begin

end.

DECLARATIONS
When writing a program you might have to declare variables, constants, types, or any other ordinal
types. Hence you need to know how to declare them. And when declaring data in your program you
have to determine their data-types. There several data-types that are used in programming, but for now
you only need to know the following.

THE SIMPLE PASCAL DATA TYPE


Data Type defines the type of data that will be stored in a variable. A type in Pascal, and in several
other popular programming languages, defines a variable in such a way that it defines a range of
values which the variable is capable of storing, and it also defines a set of operations that are
permissible to be performed on variables of that type. TURBO Pascal has eight basic data types which
are predefined and can be used anywhere in a program provided you use them properly. This chapter
is devoted to illustrating the use of these eight data types by defining the allowable range of values that
can be assigned to them, and by illustrating the operations that can be done to variables of these types.
The eight types and a very brief description follows;
integer Whole numbers from -32768 to 32767
byte The integers from 0 to 255
real Floating point numbers from 1E-38 to 1E+38
boolean Can only have the value TRUE or FALSE
char Any character in the ASCII character set
shortint The integers from -128 to 127
word The integers from 0 to 65535
longint The integers from -2147483648 to 2147483647
Please note that four of these types of data (char, shortint, word, and longint) are not a part of the
standard Pascal definition but are included as extensions to the TURBO Pascal compiler.
In addition to the above data types TURBO Pascal version 5.0 and later has the following data types
available;

By Serah Beza Mbewe 33


Introduction to Programming

single Real type with 7 significant digits


double Real type with 15 significant digits
extended Real type with 19 significant digits
comp The integers from about -10E18 to 10E18

Pascal also has variable of type ‘Boolean’. These can have the values of either true or false. Variable
type named after George Boole who invented the representation of data with either true or false (or 0s
and 1s). A boolean can therefore take on the value of either true or false. Conditional statements are
boolean expressions. A boolean variable b may be filled thus (among other ways):
b := (y = 2);

If y is 2 then b will become true, otherwise b will be false.

integer
Integer variables store whole numbers, ie, no decimal places. Examples of integer variables are,
34 6458 -90 0 1112
char
Character variables hold any valid character which is typed from the keyboard, ie digits, letters,
punctuation, special symbols etc. Examples of characters are,
XYZ 0ABC SAM_SAID.GET;LOST [ ] { } = + \ | % & ( ) * $
boolean
Boolean variables, also called logical variables, can only have one of two possible states, true or false.
real
Real variables are positive or negative numbers which include decimal places. Examples are,
34.265 -3.55 0.0 35.997E+11

Here, the symbol E stands for ‘times 10 to the power of’


Types integer, char and boolean are called ORDINAL types. This is because they have a limited,
specified range of values.

CONSTANT
A value set at design time. It cannot be changed during program execution. It may be use for things
such as the number of feet in a mile, to make your code more readable. For example:
Program Add;     
Const
a=3;
b=4;
Var
c:integer; {Declaration}
Begin
c:= a+b;
writeln(‘a + b =’,c);
End.
In this program ‘a’ and ‘b’ are two constants and note the way they are declared. ’c’ can not be a
constant because it value is only obtained after the calculation is carried out. The constants in the
program are declared before the variables can be declared (structured programming)

By Serah Beza Mbewe 34


Introduction to Programming

BASIC VARIABLES
A variable is an expression which represents a value. A variable is named such because it can have any
value - its value is variable. There are many different types of variables. For the moment we will say
that a variable can store a word or a number.

There are two ways of storing data in variables: they come in from:
outside (through the keyboard or from disk), or
values can be assigned from within the program e.g.
number := 99;

In Pascal, variables are declared at the beginning of the program or procedure. They must be declared
after the keyword ‘var’. Variables are declared in two parts. First is then name of the variable - how it
will be referred to in your program. This is followed by a colon. Then is the type of variable, eg
Integer, Byte. This is followed by a semicolon.

eg.
var
myInt : Integer;
aRealNumber : Real;
thisIsAString : String[30];
booleanVariable : Boolean;

This will create the folling variables:


myInt - This will be an Integer.
aRealNumber - This is a Real number.
thisIsAString - This is a sequence of letters with a maximum length of 30 characters.
booleanVariable - This contains a true or false value.

It is interesting to note that ‘string’ is a keyword. This is because it is different to other variable types,
as it contains a sequence or ‘Array’ of characters. We will study Arrays in depth in a latter lesson.

Variable names
Names must be single words, but can normally be of any length. An ideal name is one that shows
clearly what it is used to store, but is reasonably short and easy to type. You cannot use reserved
words- those that have a special meaning to Pascal- or numbers as variable names. If the name needs
two or more words, you can run them all together, separate them by underlines or capitalize the start of
each – just do not use spaces or punctuation.
Exercise: Identify acceptable and unacceptable variable names and provide reasons if unacceptable i.e.
reserved word, number value, punctuation, space, meaningless –can be forgotten.
a). total b). begin c). x d). 12 e). a1

f). Taxable.Amount g). FirstName h). Pen i). VatToPay j). poiuyt
colour

INPUT AND OUTPUT STATEMENTS

The Write statement
By Serah Beza Mbewe 35
Introduction to Programming

So, lets get started with the first pascal lesson. Start up pascal and create a new empty document. Type
in the following program exactly as you see it:

Program PrintOut;
begin
  Write (‘Hello World!’);
end.

Run your program by selecting Run from the File-menu. You will notice that the screen is blinking
and then you are back in the editing environment again. To see the output of your first program, click
at the debug-menu and select user screen. You can also use the keyboard-combination ALT+F5. You
will see that the words Hello World have been printed on the screen. You have just written your first
pascal-program!
 All pascalprograms begin with the word Program followed by a word defining the name of the
program, in this case PrintOut.
 The words begin and end followed by a dot (end.) indicates where the program begins and
end.
 The word Write prints a text on the screen. What is written is whatever you write within the
write-statement (between the two ‘-characters).
 Semikolon (;) indicates how long the compiler is supposed to translate before beginning with
the next statement.
 Program-names:
Program-names must not include any country specific characters, the - character or begin with
a number. The program-name must be unique and must not be used as a variable name, label,
constant, datatype, procedure or function.

The   WriteLn   statement


Lets look at another version of Write, the WriteLn-statement:

Program PrintOut2;
begin
  WriteLn (‘This is yet another’);
  WriteLn (‘Pascal programming test!’);
end.
This program will print the following on the screen:

This is yet another


Pascal programming test!

In the program above, we’ll find the statement WriteLn. Just like Write this command prints text on
the screen, but with WriteLn, the cursor is moved down one line (ln is shorthand for line) If the
program looked like this instead:

Program PrintOut2;
begin
  Write (‘This is yet another’);
  Write (‘Pascal programming test!’);
end.
By Serah Beza Mbewe 36
Introduction to Programming

The field width parameter


This sets the width of the space that the data is to be displayed in. The parameter is written
immediately after the data item, separated by a colon (:).The width is measured in characters, and the
data is aligned to the right of the field. e.g. writeln(’Centre stage’:46)

This will set ‘Centre stage’ on screen with the final ‘e’ at column 46— effectively centering the text
on an 80-column screen.

Decimal place parameter


This can only be used on real numbers. It makes the display into the more readable digits, decimals
pattern, and specifies how many decimal places to show. This is always the second parameter - you
must therefore set a field width value first. e.g. writeln(1 23.4567:10:2)
displays
123.46
with the final 6 at the 10th column.
If you want the number to be aligned to the left, or appear directly after a piece of text, set the field
width to 0. e.g.
writeln(The answer is ‘42.1834:0:3)
This produces:
The answer is 42.183

Read and Readln


Like write and writeln, read and readln are almost but not quite identical.
In theory, readln waits for the [Enter] key to be pressed before passing data, while read passes data
into the variable immediately. In practice, what happens depends more upon your system.
program reading;
var
c:char;
name: array[0..9] of char;
begin
write (‘Enter your first initial:’);
readln©;
writeln(’Enter your name: );
readln(name);
writeln(’Hello ‘,c,’‘,name);
write(’Enter your initial and name: ‘);
read©; {Don’t wait for [Enter]}
readln(name); {Wait for [Enter]}
writeln(’lnitial = ‘,c);
writeln(’Sumame ‘,name);
end.

By Serah Beza Mbewe 37


Introduction to Programming

Control statements
 ‘Program flow’ refers to the order in which a program’s instructions are carried out. So far, all the
example programs have run straight through a sequence, and then stopped. There are few practical
uses for such simple programs.

The addition of loops and branches makes programs far more useful and powerful.

By Serah Beza Mbewe 38


Introduction to Programming

THE COPPERBELT UNIVERSITY


SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

OPERATORS, RESERVED WORDS AND CALCULATIONS

Pascal contains symbols and reserved words that can be used by a programmer to carryout different
operations using a Pascal program. Below is a few of the symbols and reserved words.

Pascal symbols are reserved symbols used by the compiler for performing operations and calculations
(see Table I below).

(PLUS) Binary arithmetic addition; unary arithmetic identity; set union.


+
(MINUS) Binary arithmetic subtraction; unary arithmetic negation; set difference.
-
(ASTERISK) Arithmetic multiplication; set intersection.
*
(SLASH) Floating point division.
/
(EQUAL) Equality test.
=
(LESS THAN) Less than test.
<
(GREATER THAN) Greater than test.
>
(LEFT BRACKET) Delimits sets and array indices.
[
(RIGHT BRACKET) Delimits sets and array indices.
]
(PERIOD) Used for selecting an individual field of a record variable. Follows the final END of a
. program.
(COMMA) Separates arguments, variable declarations, and indices of multi-dimensional arrays.
,
(COLON) Separates a function declaration with the function type. Separates variable declaration
: with the variable type.
(SEMI-COLON) Separates Pascal statements.
;

(LEFT PARENTHESIS) Group mathematical or boolean expression, or function and procedure arguments.
(
(RIGHT PARENTHESIS) Group mathematical or boolean expression, or function and procedure arguments.
)

By Serah Beza Mbewe 39


Introduction to Programming

(LESS THAN/GREATER Non-equality test.


<> THAN)
(LESS THAN/EQUAL) Less than or equal to test; Subset of test.
<=
(GREATER THAN/EQUAL) Greater than or equal to test; Superset of test.
>=
(COLON/EQUAL) Variable assignment.
:=
(PERIOD/PERIOD) Range delimiter.
..

Table I: Pascal Special Symbol

Additionally, the following tokens are Pascal comment delimiters. When placed around text, they
indicate text that is not meant for compilation.

{ and }, (* and *)

Pascal reserved words used by the compiler for performing operations and calculations (see Table II
below).

AND Boolean conjunction operator


ARRAY Array type
BEGIN Starts a compound statement
CASE Starts a CASE statement
CONST Declares a constant
DIV Integer division
DO Follows WHILE and FOR clause, preceding action to take
DOWNTO In a FOR loop, indicates that FOR variable is decremented at each pass
ELSE If the boolean in the IF is false, the action following ELSE is executed
END Ends a compound statement, a case statement, or a record declaration
FILE Declares a variable as a file
FOR Executes line(s) of code while FOR loop variable in within range
FUNCTION Declares a Pascal function
GOTO Branches to a specified label
IF Examine a boolean condition and execute code if true
IN Boolean evaluated to true if value is in a specified set
LABEL Indicates code to branch to in a GOTO statement
MOD Modular integer evaluation
NIL Null value for a pointer
NOT Negates the value of a boolean expression
OF Used in CASE statement after case variable
OR Boolean disjunction operator

By Serah Beza Mbewe 40


Introduction to Programming

PROCEDURE Declares a Pascal procedure


PROGRAM Designates the program heading
RECORD Declares a record type
REPEAT Starts a REPEAT/UNTIL loop
SET Declares a set
THEN Follows the boolean expression after an IF statement
TO In a FOR loop, indicates that FOR variable is incremented at each pass
TYPE Defines a variable type
UNTIL Ends a REPEAT/UNTIL loop
VAR Declares a program variable
WHILE Executes block of code until WHILE condition is false
WITH Specifies record variable to use for a block of code

Calculations with variables

Variables can be used in calculations. For example you could assign the value to a variable and then
add the number 1 to it. Here is a table of the operators that can be used:

+ Add
- Subtract
* Multiply
/ Floating Point Divide
div Integer Divide
mod Remainder of Integer Division

The following example shows a few calculations that can be done:

program Variables;
 
var
   Num1, Num2, Ans: Integer;
 
begin
   Ans := 1 + 1;
   Num1 := 5;
   Ans := Num1 + 3;
   Num2 := 2;
   Ans := Num1 - Num2;
   Ans := Ans * Num1;
end.

Strings hold characters. Characters include the the letters of the alphabet as well as special characters
and even numbers. It is important to understand that integer numbers and string numbers are different
things. You can add strings together as well. All that happens is it joins the 2 strings. If you add the
strings ‘1’ and ‘1’ you will get ‘11’ and not 2.

program Variables;
 
var

By Serah Beza Mbewe 41


Introduction to Programming

   s: String;
 
begin
   s := ‘1’ + ‘1’;
end.

You can read vales from the keyboard into variables using Readln and ReadKey. ReadKey is from the
crt unit and only reads 1 character. You will see that ReadKey works differently to Readln

program Variables;
 
var
   i: Integer;
   s: String;
   c: Char;
 
begin
   Readln(i);
   Readln(s);
   c := ReadKey;
end.

Printing variables on the screen is just as easy. If you want to print variables and text with the same
Writeln then seperate them with commas.

program Variables;
 
var
   i: Integer;
   s: String;
begin
   i := 24;
   s := ‘Hello’;
   Writeln(i);
   Writeln(s,’ world’);
end.

By Serah Beza Mbewe 42


Introduction to Programming

THE COPPERBELT UNIVERSITY


SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

TYPES OF PASCAL STATEMENTS

In Pascal there are two types of statements. These are as follows:

1. Simple statement: this type of statements provides a single instruction to the computer.

Eg writeln(‘hi there’); This simple statement instructs the computer to print the words hi
there on the screen.

2. Compound statement: This type of statements provides more than one instruction to the computer.
They are bracketed between the words begin and end;. The end is followed by a semi-colon.

e.g if weather=’fine’ then


begin
writeln(‘I will go fishing’);
writeln(‘Might see you on Monday’);
end;

The two instructions (writeln(‘I will go fishing’);, writeln(‘Might see you on Monday’);) make up the
compound statement that should be executed if the weather is fine.

PROGRAM CONTROL

This lesson will cover:

   The If Statement
 If..Then..Else 
 Nested If Statements               
   The Repeat-Until Loop     
   The For Loop   
 Nested For loops
 While-Do Loop
Now, it is time to learn the most important rules of programming: the if statements - decision making,
for loops and the repeat-until loop. Almost, these 3 general programming constructs are common in
every programming language and you have to make sure that when you have finished reading this
lesson, make sure that you have practiced them enough before continuing with learning pascal because
they are of outmost importance. If you fall in doubt about these programming constructs, then try to
use the forums, describing your problem

The If Statement

The ‘if statement’ executes a the proceeding statement(s) conditionally. This means that if an action
comes to be true, then the statement(s) proceeding the if statement are executed, else these statements
are skipped. It works like this:
By Serah Beza Mbewe 43
Introduction to Programming

If this happens(action), then do this(reaction, if action is true).


OR:
If this happens(action), then do this(reaction, if action is true), else do this(reaction, if action is false).
In Pascal, the ‘if statement’ should be written as follows:
If conditional expression then code ... ;{if one action}
OR:
If conditional expression then Begin instructions ... End; {if more than one action is required}
Note that you should not use an assignment statement in the ‘if’ construct, otherwise the compiler will
raise a syntax error. I.e.:
Wrong:
If x := 20 then x := x + 1; {the underlined character must be excluded}
Correct:
If x = 20 then x := x + 1; {only an equal sign is used for comparison}

A program is shown below as an example of how the ‘if statement’ works:

Program lesson4_Program1;
Uses Crt;
Label 1; {this is used with a goto statement}
Var Sel: String;
N1,N2, Total : Real;
YN : Char; {this is a character variable type,
which holds single characters ONLY}
Begin
1:Clrscr;
Total := 0; {always initialise integer/real variables}
GotoXy(4,3);
Writeln(‘1.Addition’);
GotoXy(4,4);
Writeln(‘2.Subtraction’);
GotoXy(4,5);
Writeln(‘3.Exit’);
GotoXy(6,8);
Write(‘Select: ‘);
Sel := Readkey;
If Sel = ‘1’ {action} then
Begin {more than one statement}
ClrScr;               
Write(‘Input No.1:’); 
Readln(N1);           
Write(‘Input No.2:’); 
Readln(N2);           
Total := N1 + N2;    
Writeln(‘Addition: ‘,N1:2:3,’ + ‘,N2:2:3,’ = ‘,Total:2:3); 
Write(‘Press any key to continue...’); 
Readkey;
Goto 1;{this leads back to the beginning of the program,
otherwise the program terminates}
End; {Closing the if statement(begin)}
If Sel = ‘2’ then
{note that the assignment statement
is not used within an if statement}
Begin
ClrScr;
Write(‘Input No.1:’);
Readln(N1);
By Serah Beza Mbewe 44
Introduction to Programming

Write(‘Input No.2:’);
Readln(N2);
Total := N1 - N2;
Write(‘Subtraction: ‘);
Write(N1:2:3,’ - ‘,N2:2:3,’ = ‘,Total:2:3);
Write(‘Press any key to continue...’);
Readkey;
Goto 1;
End; {Closing the if statement}
If Sel = ‘3’ then
Begin
ClrScr;
Write(‘Are you sure?(Y/N)’);
YN := Readkey;
If YN = ‘y’ then Halt; {1 action, so no need of Begin..End}
If YN = ‘n’ then Goto 1; {the goto statement is not
recommended for excessive use}
End;

End. 

If..Then..Else

In a normal if statement, the ‘reaction’ cannot be performed if the condition is not true. But in an
if..then..else statement, there is at least one set of statements to be performed. Let’s take a look at the
example below:

writeln(‘Who has discovered the land of America?’);


Readln(ans);
If (ans = ‘Christopher Colombus’) then
score := score + 1    {if this is false,}
ELSE
writeln(‘sorry, you”ve got it wrong!’); {then this is true}
Note that if the ‘else’ term is included with an if statement, then there should be no semi-colon before
the ‘else’ term; just as seen in the above example.

Nested If statements

The previous program have already shown an example of nested if statements. I.e.:

If Sel = ‘3’ then


Begin
ClrScr;
Write(‘Are you sure?(Y/N)’);
YN := Readkey;
If YN = ‘y’ then HALT;  {Nested if statement}
If YN = ‘n’ then Goto 1;{Another Nested if statement} 
End;

A nested if statement, is in the form:

If (this happens) then        {if 1}


    If (this happens) then    {if 2}
        (do this) etc...
    Else (do this)            {if 2}
  Else (do this) etc...       {if 1}
By Serah Beza Mbewe 45
Introduction to Programming

A nested if statement is an if statement within another if statement, as shown above.

The Repeat-Until Loop

This loop is used to repeat the execution of a set of instructions for at least one time. It is repeated until
the conditional expression is obeyed. The following example, shows the model of the ‘repeat-until’
loop:

Repeat
..(code)
..(code)
..(code)
Until conditional statement;
Here’s an example:
Uses Crt;
Var YN : String;

Begin
Writeln(‘Y(YES) or N(NO)?’);
Repeat {repeat the code for at least one time}
YN := Readkey ;
If YN = ‘y’ then Halt; {Halt - exit}
If YN = ‘n’ then Writeln(‘Why not? Exiting...’);
Delay(1800); { wait a second plus 800 milliseconds }
Until (YN = ‘y’) OR (YN = ‘n’);
End.

See? It’s very simple! In the above program, there is a Boolean expression in the 10th line (or). This
will be described later on

The For Loop

The for loop is a sort of repeat-until loop. The for loop, repeats a set of instructions for a number of
times. The for loop is in the form:

• If used for only one action:


for {variable}* := {original value} to/downto {final value} do
{code...(for one action)}
• If used for more than one action:
for {variable}* := {original value} to/downto {final value} do Begin
{code...}
{code...}

End;

*Generally, this variable is called the ‘loop counter’.

Now, an example of the for loop is shown below, but firstly, you should have an idea of the usefulness
of the for loop. Consider the following example:

Without for loop:

By Serah Beza Mbewe 46


Introduction to Programming

Program lesson4_Program2a;
Uses Crt;

Begin
Writeln(‘for loop’); {somewhat boring writing all this!!!}
Writeln(‘for loop’);
Writeln(‘for loop’);
Writeln(‘for loop’);
Writeln(‘for loop’);
Writeln(‘for loop’);
Writeln(‘for loop’);
Readln;

End.

Nested for loops

A nested for loop is similar to that of the nested if statements. A nested for loop is in the form:

for {loop counter} := {original value} to {final value} do {Begin-if required}


{code if any..begin should be included (i.e more than one action)}
for {loop counter} := {original value} to {final value} do {Begin-if required}
{code..if more than one action, include begin in the second for loop}
{End; - if begin is included in the second for loop)}
{code if any..begin should be included in the first for loop} 
{End; - if begin is included in the first for loop)}
The nested for loop is rarely used and it may cause problems.

While-Do Loop
This type of loop is executed while the condition is true. It is different from the ‘Repeat-Until’ loop
since the loop might not be executed for at least one time. The code works like this:
While <condition is true> do the following:
instruction 1;
instruction 2;
instruction 3;
etc...
End; {If while-do loop starts with a begin statement}

Example Program on the While-Do loop:

Program Lesson4_Program4;
Uses Crt;

Var Ch : Char;
Begin
Writeln(‘Press “q” to exit...’);
Ch := Readkey;
While Ch <> ‘q’ do
Begin
Writeln(‘I told you press “q” to exit!!’);
Ch := Readkey;
End;

By Serah Beza Mbewe 47


Introduction to Programming

End.

The CASE-OF Statement

*You should have an idea of the ‘if statement’ before you proceed with this lesson.

The Simple Case Statement

So far, you have learned how to use an ‘if statement’. But in some cases the ‘case statement’ is
preferred to the if statement because it reduces some unnecessary code but the same meaning is
retained. The case statement is very similar to the if statement, except in that the it does not accept
literal conditional expressions (i.e.: strings) but surprisingly enough, it allows single character
conditional expressions. Here is how it works:

Case {variable of type: integer or character ONLY} of


{input statement- within inverted commas if of type char} : {code..}
{input statement- within inverted commas if of type char} : {code..}
    ...
End;  {End Case}

Now you should note the difference and the intelligent use of the case statement over the if statement.

The Program is written using the if statement:

Program Program1a_Lesson5;
Uses Crt;
Label Return; {used respectively with the
goto statement; beware of it}
Var SEL : Integer;
YN : Char;
Begin
Return: Clrscr;
Writeln(‘[1].PLAY GAME’);
WRITELN(‘[2].LOAD GAME’);
WRITELN(‘[3].MULTIPLAYER’);
WRITELN(‘[4].EXIT GAME’);
Writeln(‘note: Do note press anything except’);
Writeln(‘numbers; otherwise an error occurs!’);
Readln(SEL);
If SEL = 1 then
Begin
Writeln(‘Are you able to create a game’);
Writeln(‘of yourself using pascal??’);
Delay(2000);
Goto Return;
End;
If SEL = 2 then
Begin
Writeln(‘Ahhh... no saved games’);
Delay(2000);
Goto Return;
End;
If SEL = 3 then
Begin

By Serah Beza Mbewe 48


Introduction to Programming

Writeln(‘networking or 2 players?’);
Delay(2000);
Goto Return;
End;
If SEL = 4 then
Begin
Writeln(‘Exit?’);
YN := Readkey;
If YN = ‘y’ then
Begin
Writeln(‘Nooooooooooooo...’);
Delay(1000);
Halt; {EXIT PROGRAM}
End;
If YN = ‘n’ then
Goto Return;
End;

End.

So far, you have learned how to use an ‘if statement’. But in some cases the ‘case statement’ is
preferred to the if statement because it reduces some unnecessary code but the same meaning is
retained. The case statement is very similar to the if statement, except in that the it does not accept
literal conditional expressions (i.e.: strings) but surprisingly enough, it allows single character
conditional expressions. Here is how it works:

Case {variable of type: integer or character ONLY} of


{input statement- within inverted commas if of type char} : {code..}
{input statement- within inverted commas if of type char} : {code..}
    ...
End;  {End Case}

Now you should note the difference and the intelligent use of the case statement over the if statement.

The Program is written using the if statement:

Program Program1a_Lesson5;
Uses Crt;
Label Return; {used respectively with the
goto statement; beware of it}
Var SEL : Integer;
YN : Char;
Begin
Return: Clrscr;
Writeln(‘[1].PLAY GAME’);
WRITELN(‘[2].LOAD GAME’);
WRITELN(‘[3].MULTIPLAYER’);
WRITELN(‘[4].EXIT GAME’);
Writeln(‘note: Do note press anything except’);
Writeln(‘numbers; otherwise an error occurs!’);
Readln(SEL);
If SEL = 1 then
Begin
Writeln(‘Are you able to create a game’);
Writeln(‘of yourself using pascal??’);

By Serah Beza Mbewe 49


Introduction to Programming

Delay(2000);
Goto Return;
End;
If SEL = 2 then
Begin
Writeln(‘Ahhh... no saved games’);
Delay(2000);
Goto Return;
End;
If SEL = 3 then
Begin
Writeln(‘networking or 2 players?’);
Delay(2000);
Goto Return;
End;
If SEL = 4 then
Begin
Writeln(‘Exit?’);
YN := Readkey;
If YN = ‘y’ then
Begin
Writeln(‘Nooooooooooooo...’);
Delay(1000);
Halt; {EXIT PROGRAM}
End;
If YN = ‘n’ then
Goto Return;
End;
End.

Now, the next program is written using the case statement and the output
is almost the same.

Program Program1b_Lesson5;
Uses Crt;
Label Return; {use of the goto statement
is not recommended..avoid it}
Var SEL : Integer;
YN : Char;
Begin
Return:Clrscr;
Writeln(‘[1].PLAY GAME’);
WRITELN(‘[2].LOAD GAME’);
WRITELN(‘[3].MULTIPLAYER’);
WRITELN(‘[4].EXIT GAME’);
Writeln(‘note: Do note press anything except’);
Writeln(‘numbers; otherwise an error occurs!’);
Readln(SEL);
Case SEL of
1 : Begin
Writeln(‘Are you able to create’);
Writeln(‘a game of yourself using pascal??’);
Delay(2000);
Goto Return;
End;
2 : Begin
Writeln(‘Ahhh... no saved games’);
Delay(2000);
Goto Return;
By Serah Beza Mbewe 50
Introduction to Programming

End;
3 : Begin
Writeln(‘networking or 2 players?’);
Delay(2000);
Goto Return;
End;
4 : Begin
Writeln(‘Exit?’);
YN := Readkey;
Case YN of {a sort of a nested case statement}
‘y’ : Begin
Writeln(‘Nooooooooooooo...’);
Delay(1000);
Halt;
End;
‘n’ : Goto Return;
End;{End Case2}
End;{Close Conditional Expression 4}
End; {End Case1}

End.

This source code had a syntax error and is now corrected (Vaar changed to Var)

The Case-Else Statement 

Again this is similar to the if..then..else statement. Study the program below to learn how to use the
‘else’ term following the ‘case statement’:

Program Program2_Lesson5;
Uses Crt;
Label Return; { avoid it }
Var YN : Char;

Begin
Return:ClrScr;
Writeln(‘Exiting?’);
YN := Readkey;
Case YN of
‘y’ : Halt;
‘n’ : Begin
Writeln(‘What are you going to do here, anyway?’);
Delay(2000);
Halt;
End;
Else
Begin
Writeln(‘Either press “y” for yes’);
Writeln(‘or “n” for no.. please try again..’);
Delay(3500);
ClrScr;
Goto Return;
End;
End; {CASE}

End. {PROGRAM}

By Serah Beza Mbewe 51


Introduction to Programming

LOGICAL OPERATORS AND BOOLEAN EXPRESSIONS


Here we cover:
 What are logical operators?
 The Logical Operators
AND
OR
NOT
 Example of each logical operator:
AND
OR
NOT

What are the Logical Operators?

The logical operators are expressions which return a false or true result over a conditional expression.
They are also used in assignments (an example of this would be shown later). Such  operators consist
of simple logical operators, such as ‘Not’ or ‘And’. They should be used between two conditional
expressions; for example:

If (x = 0) AND (a = 2) then...

The Logical Operators

There are three types of logical operators, each of which are concerned with conditional expressions.
These are:

AND  OR    NOT
All of these logical operators have a different effect on the conditional expressions. Let’ssee what each
of the logical operator does two (or more) conditional expressions...

And

If  *1(Str1 = ‘a’)  AND  *2(Str2 = ‘b’) then writeln(‘Yes, you got it right.’);

Expression 2 AND (result)


Expression 1
true true true
false true false
true false false
false false false

If expression 1 and expression 2 are both true (i.e. the user inputs ‘a’ and ‘b’ into variables ‘Str1’ and
‘Str2’ respectively), the message will be displayed. Above  is a table showing the possible
combinations.

So, from the above table, one can conclude that for a logical operation such as AND, to give out a true
result, both conditional expressions should be true.
By Serah Beza Mbewe 52
Introduction to Programming

OR

If  *1(Str1 = ‘a’)  OR  *2(Str2 = ‘b’) then writeln(‘Yes, you got it right.’);

Expression 2 OR (result)
Expression 1
true true true
false true true
true false true
false false false

Either expression 1 or expression 2 should be true to display the message. If for example expression 1
is true and any other conditional expressions are false, the result is true! Above is a table(the truth
table) showing the possible combinations.

So, from the above table, one can conclude that for a logical operation such as OR, to give out a true
result, only one of the conditional expressions should be true.

NOT

Not is almost different from the two logical gates. It only accepts one input and is well-known as the
‘inverter’. If for example the result of two conditional expressions is true, the ‘not’ operator would
invert the result to false! So, the of the logical operator, ‘not’, is to output the inverse of the input. The
simple truth table for the not operator is:

Input Output
true false
false true

Example of the AND Operator

Program Lesson6_Program1;
Uses Crt;
Var n1, n2 : string;

Begin
Writeln(‘Enter two numbers: (“0” & “0” to exit)’);
Repeat
Write(‘No.1: ‘);
Readln(n1);
Write(‘No.2: ‘);
Readln(n2);
If (n1 = ‘0’) AND (n2 = ‘0’) then Halt(0);
Until (n1 = ‘0’) AND (n2 = ‘0’);

End.

Example of the OR Operator


By Serah Beza Mbewe 53
Introduction to Programming

Program Lesson6_Program2;
Uses Crt;
Var n1, n2 : String;

Begin
Writeln(‘Enter two numbers: (“1” & “2” to exit)’);
Repeat
Write(‘No.1: ‘);
Readln(n1);
Write(‘No.2: ‘);
Readln(n2);
If (n1 = ‘1’) OR (n2 = ‘2’) then Halt;
Until (n1 = ‘1’) OR (n2 = ‘2’);

End.

Example of the NOT Operator

Program Lesson6_Program3;
Uses Crt;
Var n1 : String;

Begin
Writeln(‘Enter two numbers: (any number except 0 to exit)’);
Repeat
Write(‘No.1: ‘);
Readln(n1);
If not(n1 = ‘0’) then Halt;
Until not(n1 = ‘0’);

End.

The Boolean Expressions

The boolean expressions are the terms ‘true’ and ‘false’. These are simply similar to 1’s (for true) and
0’s(for false). They describe an expression whether it is false or true. The variable types over boolean
expressions is the ‘boolean’ type. Example:

Var bool : Boolean;

Example Program:

Program Lesson6_Program4;
Var quit : Boolean;
a : String;
Begin
Repeat
Write(‘Type “exit” to quit:’);
Readln(a);
If a = ‘exit’ then quit := True else quit := False;
If quit = True then Halt;
Until quit = True;

End.

By Serah Beza Mbewe 54


Introduction to Programming

THE COPPERBELT UNIVERSITY


SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

PROCEDURES AND FUNCTIONS

Procedures

Procedures are sub-programs that can be called from the main part of the program. Procedures are
declared outside of the main program body using the procedure keyword. Procedures must also be
given a unique name. Procedures have their own begin and end. Here is an example of how to make a
procedure called Hello that prints “Hello” on the screen.

The general form for a procedure definition is identical to the main program except that the header is
changed
PROCEDURE ProcName(<parameter definitions>);
<Data Definition Part>

BEGIN
<Statement Sequence>

END;
program Procedures;
 
procedure Hello;
begin
   Writeln(‘Hello’);
end;
 
begin
end.

To use a procedure we must call it by using its name in the main body.

program Procedures;
 
procedure Hello;
begin
   Writeln(‘Hello’);
end;
 
begin
   Hello;
end.

Procedures must always be above where they are called from. Here is an example of a procedure that
calls another procedure.

program Procedures;
 
By Serah Beza Mbewe 55
Introduction to Programming

procedure Hello;
begin
   Writeln(‘Hello’);
end;
 
procedure HelloCall;
begin
   Hello;
end;
 
begin
   HelloCall;
end.

Procedures can have parameters just like the other commands we have been using. Each parameter is
given a name and type and is then used just like any other variable. If you want to use more than one
parameter then they must be separated with semi-colons.

program Procedures;
 
procedure Print(s: String; i: Integer);
begin
   Writeln(s);
   Writeln(i);
end;
 
begin
   Print(‘Hello’,3);
end.

When calling print we replace s and i by there values ‘Hello’ and 3, these are called arguments. The
parameter passing mechanism described above allows values to be passed into a procedure but does
not allow the procedure to pass results back to the calling program. This is because any assignment to
a parameter within a procedure only alters a copy of the corresponding actual parameter, not the
parameter itself. So, for example, the following will not work

PROGRAM AddOne(input,output);
VAR val : Integer;
PROCEDURE Inc(i:Integer);

BEGIN
i := i + 1

END;

BEGIN
Write(‘Enter a number: ‘); Readln(val);
Inc(val);
Writeln(‘Incremented value = ‘,val:1)

By Serah Beza Mbewe 56


Introduction to Programming

END.
The program AddOne is legal and will execute. As an example, consider what happens if 1 is entered
following the prompt. The program will just print out ‘ Incremented value = 1’ which is wrong.
This is because the Inc procedure does not alter the value of val
The intended effect of the AddOne program is to add 1 to the number entered. One way to do this
would be for the procedure Inc to reference val directly, as in
PROGRAM AddOne(input,output);
VAR val : Integer;
PROCEDURE Inc;

BEGIN
val := val + 1

END;

BEGIN
Write(‘Enter a number: ‘); Readln(val);
Inc;
Writeln(‘Incremented value = ‘,val:1)

END.
This is perfectly legal, all data objects (and types) defined in the main program are global and are
accessible within procedures. Furthermore, this version of AddOne does work as intended. However,
this kind of direct access to global variables is generally bad programming practice. It is also
restrictive in the sense that Inc is now limited to incrementing a specific variable whereas we would
prefer a version in which any variable could be incremented simply by passing it as a parameter.
To make the original version Inc work as intended, the symbol VAR should be inserted before the
parameter name in the procedure heading, that is
PROCEDURE Inc(VAR i:Integer);
The effect of the VAR is to change the parameter passing mechanism used for i from value to variable.
This means that the actual parameter supplied in calls to Inc must now be a variable. When Inc is
called, all references within Inc to the formal parameter i are changed to references to the actual
parameter. Thus, when Inc(val) is executed, the body of Inc effectively becomes

BEGIN
val := val + 1

END
and hence val is incremented by one as intended.
There is no limit to the number of procedures that you can have in a program. They are listed one after
the other immediately before the main program body. Procedures can call other procedures to any
depth, the only restriction being that, like variables, a procedure must be defined before it can be used
in a call.

By Serah Beza Mbewe 57


Introduction to Programming

Global and Local variables

The variables we have been using so far have been global because they can be used at any time during
the program. Local variables can only be used inside procedures but the memory they use is released
when the procedure is not being used. Local variables are declared just underneath the procedure name
declaration.

program Procedures;
 
procedure Print(s: String);
var
   i: Integer;
begin
   for i := 1 to 3 do
      Writeln(s);
end;
 
begin
   Print(‘Hello’);
end.

Functions

Functions are like procedures except that they return a value. The function keyword is used instead of
procedure when declaring a function. To say what data type the return value must be you must use a
colon and the name of the type after the function’s name.

The general form of the function statement looks like this:

FUNCTION FunctionName(VariableName: VariableType): VariableType;


BEGIN
some code, if necessary;
FunctionName := some computation;
more code if necessary;
END;

program Functions;
 
function Add(i:integer;j:Integer): Integer;
begin
end;
 
begin
end.

Assigning the value of a function to a variable makes the variable equal to the return value. If you use
a function in something like Writeln it will print the return value. To set the return value just make the
name of the function equal to the value you want to return.

program Functions;
 
var
   Answer: Integer;
 
function Add(i:integer;j:Integer): Integer;
By Serah Beza Mbewe 58
Introduction to Programming

begin
   Add := i + j;
end;
 
begin
   Answer := Add(1,2);
   Writeln(Add(1,2));
end.

You can exit a procedure or function at any time by using the Exit command.

program Procedures;
 
procedure GetName;
var
   Name: String;
begin
   Writeln(‘What is your name?’);
   Readln(Name);
   if Name = “ then
      Exit;
   Writeln(‘Your name is ‘,Name);
end;
 
begin
   GetName;
end.

Here another is an example:

PROGRAM Test;
VAR
radius: REAL;
FUNCTION CircleArea(r:REAL): REAL;
BEGIN
CircleArea:= 3.1415 * r * r;
END;
BEGIN
WRITE(‘Area of circle with radius 2.0: ‘);
WRITELN(CircleArea(2.0):6:1);
WRITE(‘Area of circle with radius 5.0: ‘);
WRITELN(CircleArea(5.0):6:1);
WRITE(‘Enter your own radius: ‘);
READLN(radius);
WRITE(‘Area of circle with radius ‘, radius:3:1,’: ‘);
WRITELN(CircleArea(radius)); { ugly - formatting missing for real }
radius := 5.0;
radius := CircleArea(radius);
WRITELN(radius); { can you guess the output ? }
END.

By Serah Beza Mbewe 59


Introduction to Programming

Arrays

Arrays can be thought of as a chain of identifiers. Arrays are variables that are made up of many
variables of the same data type but have only one name. Here is a visual representation of an array
with 5 elements:
1 value 1
2 value 2
3 value 3
4 value 4
5 value 5

Arrays are declared in almost the same way as normal variables are declared except that you have to
say how many elements you want in the array.

program Arrays;
 
var
   a: array[1..5] of Integer;
 
begin
end.

We access each of the elements using the number of the elements behind it in square brackets.

program Arrays;
 
var
   a: array[1..5] of Integer;
 
begin
   a[1] := 12;
   a[2] := 23;
   a[3] := 34;
   a[4] := 45;
   a[5] := 56;
end.

It is a lot easier when you use a loop to access the values in an array. Here is an example of reading in
5 values into an array:

program Arrays;
 
var
   a: array[1..5] of Integer;
   i: Integer;
 
begin
   for i := 1 to 5 do
      Readln(a[i]);
end.

If we want to access individual integers in this array this is how.

for i:=1 to 5 do
By Serah Beza Mbewe 60
Introduction to Programming

writeln(a[i];

This loop goes through all the individual integers and prints out all values that are in the individual
integers.

Types

It is possible to create your own variable types using the type statement. The first type you can make is
a set. Many books ignore this special feature, but I’ll try to cover it as best and as clearly as
possible.What are sets exactly? Sets in programming are quite the same as in mathematics. Sets in
mathematics are like this:

A = { 1, 2, 3, 4, 5 }
So does sets. OK, how can we declare sets? The general way of declaring a set is as follows:
Type
Set_Name = set of (…<list of set contents>…);

The following is an example of a set called Animal which has dog, cat and rabbit as the data it can
store:

program Types;
 
Type
   Animal = set of (dog, cat, rabbit);
 
var
   MyPet: Animal;
 
begin
   MyPet := dog;
end.

You can’t use Readln or Writeln on sets so the above way of using it is not very useful. You can create
a range of values as a set such as ‘a’ to ‘z’. This type of set can be used to test if a value is in that
range.

program Types;
 
uses
   crt;
Type
   Alpha = ‘a’..’z’;
var
   Letter: set of Alpha;
   c: Char;
 
begin
   c := ReadKey;
   if c in [Letter] then
      Writeln(‘You entered a letter’);
end.

Another example is on days of the week:


By Serah Beza Mbewe 61
Introduction to Programming

type
days = (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);

var
allday : set of days;

You cannot write its contents or read to add it. Well, how can we use it ? Run this program :

type
days = (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);

var
allday : set of days;
workday : set of Monday .. Friday;
thisday : days;

begin
thisday:=Monday;
if thisday in workday then
writeln(‘This day I”m in work’)
else
writeln(‘This day I”m on holiday’);
end.

The second type you can make is a record. Records are two or more variables of different types in one.
An example of how this could be used is for a student who has a student number and a name. Here is
how you create a type:

program Types;
 
Type
   Student = Record
      Number: Integer;
      Name: String;
   end;
 
begin
end.

After you have created the type you must declare a variable of that type to be able to use it.

program Types;
 
Type
   StudentRecord = Record
      Number: Integer;
      Name: String;
   end;
var
   Student: StudentRecord;
 
begin
end.

By Serah Beza Mbewe 62


Introduction to Programming

To access the Number and Name parts of the record you must do the following:

program Types;
 
Type
   StudentRecord = Record
      Number: Integer;
      Name: String;
   end;
 
var
   Student: StudentRecord;
 
begin
   Student.Number := 12345;
   Student.Name := ‘John Smith’;
end.

THE COPPERBELT UNIVERSITY


SCHOOL OF TECHNOLOGY
COMPUTER SCIENCE DEPARTMENT
Introduction to Computing (CS 110)

ARRAYS AND RECORDS


Most realistic programs need to store substantial amounts of data and process it efficiently. So far the
only types of variable considered have been simple data types capable of holding a single value and
this is inadequate for many tasks. For example, suppose that we wished to store a list of student’s
exam marks. The following is clearly impractical
TYPE Mark = 0..100;
VAR student1, student2, student3, .... : Mark;
...
average := (student1 + student2 + ....) / numStudents;
since for a large number of students, we do not want to have to refer to each by a unique name.
Pascal provides two ways of collecting related data objects together into a single unit: arrays and
records. An array is a collection of components of identical type, stored in sequence in the computer’s
memory, and accessed by means of an index value. In order to use an array in a program, you must
define the type and range of the index and the component type, and you do this by defining a new type
with the required properties. The general form of an ARRAY type definition is
TYPE ArrayName = ARRAY[lo..hi]OF ComponentType;
where the index ranges from lo to hi and the component type is any type you wish.

As an example, student marks could be stored in an array as


follows
By Serah Beza Mbewe 63
Introduction to Programming

CONST maxStudents = 1000;


TYPE MarkList = ARRAY[1..maxStudents]OF Mark;
VAR marks : MarkList;
The variable marks is an array variable with 1000 components. In terms of the box analogy introduced
in section 5, the array variable marks is like a box with 1000 compartments. Each component can hold
a mark and each component is referenced by a number in the range 1 to 1000.
To refer to an array component within a program, you simply write the index of the needed component
within square brackets after the array name. For example, the following statements would place values
into the first 3 components of marks as shown in the diagram
marks[1] := 65; marks[2] := 70; marks[3] := 36
Although a more likely method of initializing the array would be to read the marks from a file as
explained in the next section.
The index of an array can be any expression yielding a value of the appropriate type and very often it
is the index variable of a FOR loop. For example, given an array of marks and the total number of
students, the following procedure would print the average of the student marks
PROCEDURE ComputeAverage(marks:MarkList; numStudents:Integer);
VAR i : 1..maxStudents;
sum : Real;

BEGIN
sum :=0.0;
FOR i := 1 TO numStudents DO
sum := sum + marks[i];
Writeln(‘Average Mark is ‘,sum/numStudents:6:2)

END;
In this example, the procedure reads the value of each component marks[i] in turn using a FOR loop
and accumulates the total mark in sum. The average is then printed out as the sum divided by the
number of students.
The index of an array is not limited to just integer subranges but can be any simple ordinal type. The
following give some examples of the possibilities
TYPE WorkLog = ARRAY[mon..fri]OF Real;
Rainfall = ARRAY[Month]OF Integer;
Evidence = ARRAY[Boolean]OF Probability;
AllMarks = ARRAY[1..numSubjects]OF MarkList;

The type WorkLog is an array with five real components meant for storing the hours worked during the
week. If hrs is a variable of type WorkLog then

FOR d := mon TO fri DO hrs[d]:=0.0


would set all components to zero. Similarly, Rainfall has an enumeration type as index but in this
case just the type name is given. This is identical to writing jan..dec for the index limits. Evidence
shows that you can even use the Boolean values true and false to index an array. Finally, AllMarks
By Serah Beza Mbewe 64
Introduction to Programming

defines an array of arrays as an example of having a composite data type as an array element. If all is
a variable of type AllMarks then the i’th mark for subject n would be accessed by writing all[n][i].
To compute the average mark for subject n you would write
ComputeAverage(all[n],numStudents)
In Engineering applications, arrays are used to represent vectors and matrices. Vectors are just arrays
of real numbers. For example,
TYPE Vector = ARRAY[1..100]OF Real;
VAR v1,v2 : Vector;
and some typical operations might be
FOR i:=1 TO 100 DO v1[i]:=0.0; {Zero v1}
v2 := v1; {now v2 is all zero also}
v2[1]:=1.0 {first component of v2 = 1.0}
Note the whole array assignment, in Pascal assignment works for all types not just simple types.
The miniX graphics package provides a procedure to plot the contents of a vector. The call
MxPlotData(x0,y0,x1,y1,ymax,ymin,v,i,j)
plots the values in vector v between v[i] and v[j] in an imaginary rectangle whose top left corner is
at (x0,y0) and whose bottom right corner is at (x1,y1). The vertical scale of the plot is set such that a
value ymax in the array would just touch the top of the rectangle and a value ymin in the array would
just touch the bottom. For example, the following statements would display one cycle of a sine wave
in the top half of the graphics window

FOR i:=1 TO 100 DO


v1[i] := sin(pi*i/50);
MxPlotData(0,0,1.0,0.5,1.0,-1.0,v1,1,100)
Matrices are 2-dimensional arrays of real numbers and in Pascal they are defined as follows
TYPE Matrix = ARRAY[1..nRows,1..nCols]OF Real;
VAR m1,m2 : Matrix;
The element in the i’th row and j’th column of m1 would be accessed by writing m1[i,j] within a
program. For example, the following statement would add m1 to m2 leaving the result in m1.

FOR i:=1 TO nRows DO


FOR j:=1 TO nCols DO
m1[i,j]:=m1[i,j] + m2[i,j]
As another example, the following function returns the number of marks in the given mark list equal to
or greater than the given pass mark.
FUNCTION Passes(passMark:Mark; marks:MarkList;
numStudents:Integer):Integer;
VAR i : 1..maxStudents;
count : 0..maxStudents;

BEGIN
count := 0;
FOR i := 1 TO numStudents DO
By Serah Beza Mbewe 65
Introduction to Programming

IF marks[i]>=passMark THEN
count := count+1;
Passes := count

END;
The second data structuring facility in Pascal is the record. Whereas an array is a collection of
components of identical type accessed by an index, a record is a collection of possibly differing types
accessed by name. A record is defined using the following format

TYPE RecordType = RECORD


c1 : ctype1;
c2 : ctype2;
...

END;
where c1, c2, etc. are the components of the record. As an example, the following could be used to
represent time
TYPE Hour = 0..23;
Minute = 0..59;
Second = 0..59;

Time = RECORD
hr : Hour;
min : Minute;
sec : Second

END;
VAR timeNow:Time;
The variable timeNow is a record variable with 3 components. In terms of the box analogy, the record
variable timeNow is like a box with 3 compartments. The first component can hold a number in the
range 0 to 23 and it is called hr, the second and third components can hold numbers in the range 0 to
59 and are called min and sec as shown by the diagram opposite.

The components of a record are accessed by writing the record name followed by a period and then the
component name. For example, the following statements would initialise the record variable timeNow
with the values shown in the diagram
timeNow.hr := 10;
timeNow.min := 45;
timeNow.sec := 36

By Serah Beza Mbewe 66


Introduction to Programming

The main reason for using records is that it allows a collection of data objects to be bundled-up and
manipulated as a single unit. For example, a procedure to add two times together would have the
heading
PROCEDURE AddTime(t1,t2:Time; VAR sum:Time);
rather than
PROCEDURE AddTime(t1h:Hour; t1m:Minute; t1s:Second;
t2h:Hour; t2m:Minute; t2s:Second;
VAR sumh:Hour; VAR summ:Minute; VAR sums:Second);
The first version is much simpler and more importantly, it saves the programmer having to bother
about the internal details of Time objects. Once a set of appropriate operations have been defined (in
terms of procedures and functions) such as AddTime, SetTime, etc., it is no longer necessary to worry
about how the type Time is implemented. This process is called Data Abstraction and is of great
importance in software engineering.
Finally note that since there are no restrictions on the component types of either arrays or records, an
array can have record components and vice versa. For example, a vector of complex numbers could be
defined by

TYPE Complex = RECORD


re : Real;
im : Real

END;
CVector = ARRAY[1..10] OF Complex;
VAR cv : CVector;
Array indexing and record access can be applied successively as required, so the imaginary part of the
3rd component of cv would be written as cv[3].im.
You can use array of records. Suppose you have declared the TEmployee record tag. Now you want to
declare an array of it. It’s simple :
var
MyEmployee : array[1..100] of TEmployee;
Just like declaring normal arrays. How to access it ? Suppose I access the first element :
begin
MyEmployee[1].name := ‘Paul Doherty’;
MyEmployee[1].address := ‘11th Kingston Avenue’;
MyEmployee[1].age := 35;
MyEmployee[1].position := ‘Salesman’;
MyEmployee[1].commision := 0.10;
end.
With with...do it’s all the same :
begin
with MyEmployee[1] do
begin
name := ‘Paul Doherty’;
By Serah Beza Mbewe 67
Introduction to Programming

address := ‘11th Kingston Avenue’;


age := 35;
position := ‘Salesman’;
commision := 0.10;
end;
end.
Can we do nested record as looping and conditional do ? Good question ! It IS perfectly legal. But you
may do it like this :
type

TCommision = record
sales : real;
production : real;
absence : real;
end;

TEmployee = record
name : string[25];
address : string[40];
age : byte;
position : string[10];
commision : TCommision;
end;
of TEmployee record tag is a record of TCommision. How to access
In that example, the field commision
the sales field of commision ? Easy ! Suppose you have declared x as a variable of TEmployee :
x.commision.sales:=0.5; Just add another period after commision then type sales, that’s it ! Using
arrays are pretty much the same ! MyEmployee[1].commision.sales:=0.3;
You may nest records more than 2 steps. To accomplish such task you may use analogies to the
previous example. To access them is quite the same, just type down the period and subfield name and
so on. The deeper you nest, the longer you type.
You may use with...do block inside another with...do block to access nested records. Go on, try it !
One special caution should be taken: Pascal gives a special gift that may not even exist in other
programming languages: CONDITIONAL RECORDS. What are conditional records exactly?
Conditional records are record with a variable length depending on the contents of a field. That field
whose contents become so important is called pivot field. Let’s look at this:
type

TEmployee = record
Name : string[20];
Age : byte;
case department:byte of
0: (sales : longint);
1: (product : integer);
end;

By Serah Beza Mbewe 68


Introduction to Programming

TEmployee has the field of name, age, and department. Department is a byte field. If the department is
0, then the TEmployee contains sales field as the next field. Or else, in this case 1, it has product field
as the next one. The usage is quite rare though. Yet, this is very useful indeed.

LABELS

In the Pascal definition, a label is a number from 0 to 9999 that is used to define a point in the program
to which you wish to jump. All labels must be defined in the label definition part of the program
before they can be used. Then a new reserved word goto is used to jump to that point in the program.
The best way to see how the goto is used with labels is to examine the program below.

program Label_Illustration;
label 274,Repeat_Loop,Help,Dog;
var Counter : byte; (* This limits us to a maximum of 255 *)
begin
Writeln(‘Start here and go to “help”’);
goto Help;

Dog:
Writeln(‘Now go and end this silly program’);
goto 274;

Repeat_Loop:
for Counter := 1 to 4 do Writeln(‘In the repeat loop’);
goto Dog;
Help:
Writeln(‘This is the help section that does nothing’);
goto Repeat_Loop;
274:
Writeln(‘This is the end of this spaghetti code’);
end.

Result of execution
Start here and go to “help”
This is the help section that does nothing
In the repeat loop
In the repeat loop
In the repeat loop
In the repeat loop
Now go and end this silly program
This is the end of this spaghetti code

RECURSION

How about calling ourselves? Well, IT IS PERFECTLY LEGAL too!! Example:

By Serah Beza Mbewe 69


Introduction to Programming

procedure a;
begin
a;
end;
begin
a;
end.

But it will say error since it calls itself ENDLESSLY. The method of calling oneself is called
RECURSIVE CALLS. In recursive calls, we must:

Provide terminating conditions.


Be extremely careful in coding.
Not use too many recursive calls, say 50,000 times.
If not, you could find these symptoms:
Hang / stopped responding.
Beeping erratically.
Auto-reboot.
Other unexpected result

One of the very good examples of recursive calls is factorial. See the non-recursive method of
factorial function above, and then see this recursive version:

function factorial (n:byte):factorial;


begin
if n<2 then { This is the terminating condition }
factorial:=1;
else
factorial:=n*factorial(n-1); { This is the recursive part }
end;
var
x : byte;
begin
writeln(‘Enter a value : ‘); readln(x);
writeln(x,’! is ‘,factorial(x));
end.
If x = 5,
At first call, n = 5. Factorial:=5*factorial(4); => need second call
Second call, n = 4. Factorial:=4*factorial(3); => need third call
Third call, n = 3. Factorial:=3*factorial(2); => need fourth call
Fourth call, n = 2. Factorial:=2*factorial(1); => need fifth call
Fifth call, n = 1. Factorial:=1; => inserted back to above so
4th call becomes : Factorial:=2*1; (=2) => inserted back to above so
3rd call becomes : Factorial:=3*2; (=6) => inserted back to above so
2nd call becomes : Factorial:=4*6; (=24) => inserted back to above so
1st call becomes : Factorial:=5*24; (=120)

As you may see that factorial in recursive method is simpler than ever. Suppose you miswrite n-1 to n,
the terminating condition would never be functional. So, it will loop forever ! Be careful !

Well, we come to a quite advanced matter. It is sometimes used though. Inter-referenced calls. It
means that 2 procedures or functions could call each other.

procedure a;
By Serah Beza Mbewe 70
Introduction to Programming

begin
b; { illegal }
end;
procedure b;
begin
a;
end;

As you may see, calling a from b is legal, but calling b from a is illegal. It sometimes necessary for a
to call b and for b to call a. The real-life problem is like context-sensitive help. Sometimes the
description, when it is pointed or clicked, it call the index. But also, the index has to call its description
after a topic is picked. The solution is: FORWARD CALL. Example:

procedure b; forward;
procedure a;
begin
b; { now legal }
end;
procedure b;
begin
a;
end;

Use the statement forward to make b visible to a, so a can call b. It is more dangerous than recursive
call. If you are not careful, you may find the same symptoms as recursive call did. What you must do
is also the same as in the recursive call. Just beware : Calling procedures uses a part of memory called
stack. Reciprocal calls wastes stacked much faster than recursive calls. If you run out of stack, your
program would stuck.

SAMMARY
From what we have seen, a program could have a structure containing between one to all of the
following declarations.
Program Name
label declarations, if any
const constant declarations, if any
type type declarations, if any
var variable declarations, if any

procedure and function declarations, if any


Then the within the main body depending on the execution to be carried out the program could contain
sequential statements, loops and selections statements could also be included.
Begin
Sequential statement(eg writeln(a));
Selection statements( if statements);
Looping statements(repeat,for and while statements);
End.

By Serah Beza Mbewe 71

You might also like