cs110 Notes2
cs110 Notes2
cs110 Notes2
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.
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.
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’
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.
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.
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 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.
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.
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
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.
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.
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.
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.
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
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.
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:
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.
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).
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:
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.
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
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.
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.
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.
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.
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.
PROGRAMMING
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.
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
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.
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:
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.
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.
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.
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
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
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.
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.
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:
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.
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.
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.
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.
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;
Var
A,B,C: integer;
Begin
C:=A+B;
Writeln©
Readln;
End.
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.
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.
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
OR Operations (+)
Value for A Value for B Result of A+B
False False False
True False True
False True True
True True True
Associative Law
(A·B)·C = A·(B·C) = A·B·C
(A+B)+C = A+(B+C) = A+B+C
Distributive 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.
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)
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
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.
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.
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.
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.
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);
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
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)
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;
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
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.
Program PrintOut2;
begin
WriteLn (‘This is yet another’);
WriteLn (‘Pascal programming test!’);
end.
This program will print the following on the screen:
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
This will set ‘Centre stage’ on screen with the final ‘e’ at column 46— effectively centering the text
on an 80-column screen.
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.
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).
(LEFT PARENTHESIS) Group mathematical or boolean expression, or function and procedure arguments.
(
(RIGHT PARENTHESIS) Group mathematical or boolean expression, or function and procedure arguments.
)
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).
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
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
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.
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.
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
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
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:
Nested If statements
The previous program have already shown an example of nested if statements. I.e.:
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 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:
End;
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:
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.
A nested for loop is similar to that of the nested if statements. A nested for loop is in the form:
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}
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;
End.
*You should have an idea of the ‘if statement’ before you proceed with this lesson.
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:
Now you should note the difference and the intelligent use of the case statement over 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
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:
Now you should note the difference and the intelligent use of the case statement over 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
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)
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}
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...
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.’);
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
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.
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.
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 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:
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.
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)
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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
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
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
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
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;
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
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:
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:
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