0% found this document useful (0 votes)
144 views

CMP 201 Computer Programming I

The document provides information about a computer programming course, including its contents, objectives, and learning outcomes. The course covers topics like computer components, programming languages, the program development life cycle, number systems, and the PASCAL programming language. Students will learn about problem solving methods, designing and coding programs, and using control structures like decision making and repetition. The goal is for students to be able to develop simple valid PASCAL programs that solve problems by applying programming concepts and techniques of good style.

Uploaded by

Ezekiel James
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views

CMP 201 Computer Programming I

The document provides information about a computer programming course, including its contents, objectives, and learning outcomes. The course covers topics like computer components, programming languages, the program development life cycle, number systems, and the PASCAL programming language. Students will learn about problem solving methods, designing and coding programs, and using control structures like decision making and repetition. The goal is for students to be able to develop simple valid PASCAL programs that solve problems by applying programming concepts and techniques of good style.

Uploaded by

Ezekiel James
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

CMP 201 LECTURE NOTE

COMPUTER PROGRAMMING I (3 UNITS)


COURSE CONTENTS
Introduction to problem solving methods and algorithm development, designing, coding,
debugging and documenting programmes using techniques of a good programming language
style, programming language and programming algorithm development. A widely used
programming language should be used in teaching the above. E.g. PASCAL
OBJECTIVES
The specific objectives of this course are to:
1. Identify the different components of a computer
2. Know about programming languages and their categories
3. Understand the program development life cycle and apply it in problem solving
4. Learn the different number systems and their conversions

LEARNING OUTCOMES
The students should be able to:
1. Know the definition of a computer.
2. Know the basic Components of a Computer.
3. Explain the architecture of a simple Von Neumann machine.
4. Know the definition of a Programming Language.
5. Explain the Categories of Programming Languages.
6. Explain the Program Development Life Cycle.
7. Know the concepts of Number Systems and Conversions.
8. Describe the features of PASCAL program.
9. Identify the basic parts of a PASCAL program
10. Differentiate among literals, primitive data types, variable types, identifiers and operators.
11. Develop a simple valid PASCAL program using the concepts of Problem Solving Method
and Algorithm Development.
12. Create an interactive PASCAL program that gets input from the keyboard.
13. Know functions and procedure in PASCAL
14. Know the concepts of good programming such as
i. abstraction
ii. modularization
iii. documentation
15. Use decision control structures (if, else, switch) which allows selection of specific sections
of code to be executed.
16. Use repetition control structures (while, do-while, for) which allow executing specific
sections of code a number of times.
17. Explain pointers and arrays.
TEXT BOOK(S):
1.
2.
Course Writer/Developer: Dr. F.E. AYO, Department of Mathematical Sciences (Computer
Science Unit), Olabisi Onabanjo University, Ago-Iwoye.
E-mail: [email protected]
INTRODUCTION
A computer is a machine that performs a variety of tasks according to specific instructions. It
is a data processing machine which accepts data via an input device and its processor
manipulates the data according to a program.
A computer is a very powerful and versatile machine capable of performing a multitude of
different tasks, yet it has no intelligence or thinking power. The intelligence Quotient (I.Q) of
a computer is zero. A computer performs many tasks exactly in the same manner as it is told
to do. This places responsibility on the user to instruct the computer in a correct and precise
manner, so that the machine is able to perform the required job in a proper way. A wrong or
ambiguous instruction may sometimes prove disastrous.
In order to instruct a computer correctly, the user must have clear understanding of the problem
to be solved. A part from this he should be able to develop a method, in the form of series of
sequential steps, to solve it. Once the problem is well-defined and a method of solving it is
developed, then instructing him computer to solve the problem becomes relatively easier task.
Thus, before attempt to write a computer program to solve a given problem. It is necessary to
formulate or define the problem in a precise manner. Once the problem is defined, the steps
required to solve it, must be stated clearly in the required order.

The computer has two major components. The first one is the Hardware which is the tangible
part of the computer. It is composed of electronic and mechanical parts. The second major
component is the software which is the intangible part of a computer. It consists of data and
the computer programs.
BASIC COMPONENTS OF A COMPUTER
HARDWARE
The Central Processing Unit
The processor is the “brain” of the computer. It contains millions of extremely tiny electrical
parts. It does the fundamental computing within the system. The CPU is made up of Arithmetic
and Logic Unit (ALU), control unit and register arrays. Examples of processors are Pentium,
Intel etc.
Memory
The memory is where data and instructions needed by the CPU to do its appointed tasks can be
found. It is divided into several storage locations which have corresponding addresses. The
CPU accesses the memory with the use of these addresses.
1. Main Memory
The main memory is very closely connected to the processor. It is used to hold programs and
data that the processor is actively working with. It is not used for long-term storage. It is
sometimes called the RAM (Random Access Memory).
The computer's main memory is considered as volatile storage. This means that once the
computer is turned off, all information residing in the main memory is erased.
2. The Secondary Memory
The secondary memory is connected to main memory. It is used to hold programs and data for
long term use. Examples of secondary memory are hard disks and CD-ROM.
Secondary memory is considered as non-volatile storage. This means that information residing
in secondary memory is not erased after the computer is turned off.
Table 1: Comparison between main memory and secondary memory
Main Secondary
Property
Memory Memory
Fast Slow Speed
Expensive Cheap Price
Low High Capacity
Yes No Volatile

Input and Output Devices


Input and output devices allows a computer system to interact with the outside world by moving
data into and out of the system. Examples of input devices are keyboards, mice and
microphones. Examples of output devices are monitors, printers and speakers.

SOFTWARE
A software is the program that a computer uses in order to function. It is kept on some hardware
device like a hard disk, but it itself is intangible. The data that the computer uses can be
anything that a program needs. Programs acts like instructions for the processor.
Some Types of Computer Programs:
Systems Programs
1. Programs that are needed to keep all the hardware and software systems running
together smoothly.
Examples: Operating Systems like Linux, Windows, Unix, Solaris, MacOS
2. Application Programs
Programs that people use to get their work done.
Examples:
• Word Processor
• Game programs
• Spreadsheets
3. Compilers
The computer understands only one language: machine language. Machine language is
in the form of ones and zeros. Since it is highly impractical for people to create
programs out of zeros and ones, there must be a way of translating or converting a
language which we understand into machine language, for this purpose, there exists
compilers.
OVERVIEW OF COMPUTER PROGRAMMING
What is a Programming Language?
A programming language is a standardized communication technique for expressing
instructions to a computer. Like human languages, each language has its own syntax and
grammar.
Programming languages enable a programmer to precisely specify what data a computer will
act upon, how these data will be stored/transmitted, and precisely what actions to take under
various circumstances.
There are different types of programming languages that can be used to create programs, but
regardless of what language you use, these instructions are translated into machine language
that can be understood by computers.
CATEGORIES OF PROGRAMMING LANGUAGES
1. High-level Programming Languages
A high-level programming language is a programming language that is more user-friendly,
to some extent platform-independent, and abstract from low-level computer processor
operations such as memory accesses. A programming statement may be translated into one
or several machine instructions by a compiler. Examples are Pascal, Java, C, C++, Basic,
Fortran etc.
2. Machine Language
Any computer can directly understand only its own machine language. Machine language
is the “natural language” of a computer and as such is defined by its hardware design.
Machine language is often referred to as object code. Machine languages generally consist
of strings of numbers (ultimately reduced to 1s and 0s) that instruct computers to perform
their most elementary operations one at a time. Machine languages are machine dependent
(i.e., a particular machine language can be used on only one type of computer). Such
languages are cumbersome for humans. Machine-language programming was simply too
slow, tedious and error prone for most programmers. Instead of using the strings of numbers
that computers could directly understand, programmers began using English-like
abbreviations to represent elementary operations. These abbreviations formed the basis of
assembly languages.
3. Assembly Language
Assembly languages or low-level languages are similar to machine languages, but they are
much easier to program in because they allow a programmer to substitute names for
numbers. Assembly languages are available for each CPU family, and each assembly
instruction is translated into one machine instruction by an assembler program. Translator
programs called assemblers were developed to convert early assembly-language programs
to machine language at computer speeds.
Note: The terms "high-level" and "low-level" are inherently relative. Originally, assembly
language was considered low-level and COBOL, C, etc. were considered high-level. Many
programmers today might refer to these latter languages as low-level.
PRINCIPLES OF GOOD PROGRAMMING
It is generally accepted that a good Computer program should have the characteristics shown
below:
1. Accuracy: The Program must do what it is supposed to do correctly and must meet the
criteria laid down in its specification.
2. Reliability: The Program must always do what it is supposed to do, and never crash.
3. Efficiency: Optimal utilization of resources is essential. The program must use the
available storage space and other resources in such a way that the system speed is not
wasted.
4. Robustness: The Program should cope with invalid data and not stop without an
indication of the cause of the source of error.
5. Usability: The Program must be easy enough to use and be well documented.
6. Maintainability: The Program must be easy to amend having good structuring and
documentation.
7. Readability: The Code of a program must be well laid out and explained with
comments i.e. proper indentation.

CONCEPT OF GOOD PROGRAMMING


The concept of modularity
The original name for modularity was a sub-program. Other names include: macro, sub-routine,
procedure, module and function. Modularity is important because they allow us to take large
complicated programs and to divide them into smaller manageable pieces.
Modularity has two aspects: the language’s support for sub-programming and the language’s
extensibility in the sense of allowing programmer – defined operators and data types. By sub
programming, we mean the ability to define independent procedures and functions
(subprograms), and communicate via parameters or global variables with the invoking
program.
The concept of abstraction
The most important concept introduced by high level languages is abstraction, which is a
process that allows the general pattern to be observed while ignoring the inessential details.
Implementation details and certain irrelevant properties will be hidden for clarity. An
abstraction is thereby also a simplification of facts.
An example of abstraction could be the description of a memory cell as a location to store data
values, the physical details are of no interest from a programmer's point of view. Abstraction
has a twofold relationship with programming languages:
• Programming languages are used to implement abstract models.
• Programming languages are hardware abstractions.
Along with the evolution of programming languages we can recognize an evolution of the latter
relationship. While binary or octal code was just a low level abstraction of the flip-flop
hardware level, with the introduction of assembler code we find the abstraction on the register
level, and finally with higher level languages the abstraction is based on logical data objects
(variables) and their control. Thus, two principle mechanisms of abstraction can be
distinguished:
i. Data abstraction.
ii. Control abstraction
Data abstraction
Data abstraction is a mechanism providing types and allowing the declaration of variables of
these types, as well as providing operations for the manipulation of these variables. Thus, data
abstraction in its simplest form is given by standard types such as real, for example. In high
level programming languages the data type real allows the definition of floating-point
variables, and the set of operations on this data type allow the arithmetic manipulation of
objects of this type.
Control abstraction
Control abstraction is the mechanism defining the order in which certain activities or groups
of activities should be performed. By this we mean not only control structures on the statement
level like conditional and unconditional branching, but also the construction of subprograms
up to concurrent programs. Control abstraction on the subprogram level was already introduced
in assembler languages by allowing macro definitions.
Documentation
Comments are notes written to a code for documentation purposes. Those text are not part of
the program and does not affect the flow of the program.
Pascal supports two types of comments: single line and multiple line comments.
Single Line Comments
Pascal single line comments starts with { and ends with a }. All the text between {…}are treated
as comments. For example,
{This is a single style or single line comments }
Multiple Line Comments
Pascal multiline comments starts with a {* and ends with a *}. All text in between the two
delimeters are treated as comments. Unlike single line comments, it can span multiple lines.
For example,
{* this is an example of a
Multiline or multiple line comments *}
Advantages of Program documentation
1. It provides all necessary information for anyone who comes in contact with the
program.
2. It helps the supervisor in determining the program’s purpose, how long the program
will be useful and future revision that may be necessary.
3. It simplifies program maintenance (revision or updating)
4. It provides information as to the use of the program to those unfamiliar with it.
5. It provides operating instructions to the computer operator.

THE PROGRAM DEVELOPMENT LIFE CYCLE (problem solving methodologies)


A computer cannot solve a problem on its own. One has to provide step by step solutions of
the problem to the computer. In fact, the task of problem solving is not that of the computer. It
is the programmer who has to write down the solution to the problem in terms of simple
operations which the computer can understand and execute.
In order to solve a problem by the computer, one has to pass though certain stages or steps.
They are:
1. Understanding the problem/problem definition
2. Problem Analysis
3. Algorithm design and representation (Pseudocode or flowchart)
4. Coding and debugging
In order to understand the basic steps in solving a problem on a computer, let us define a single
problem that we will solve step-by-step as we discuss the problem solving methodologies in
detail. The problem we will solve will be defined in the next section.
PROBLEM DEFINITION
A programmer is usually given a task in the form of a problem. Before a program can be
designed to solve a particular problem, the problem must be well and clearly defined first in
terms of its input and output requirements.
A clearly defined problem is already half the solution. Computer programming requires us to
define the problem first before we even try to create a solution.
Let us now define our example problem:
“Create a program that will determine the number of times a name occurs in a list.”
PROBLEM ANALYSIS
After the problem has been adequately defined, the simplest and yet the most efficient and
effective approach to solve the problem must be formulated.
Usually, this step involves breaking up the problem into smaller and simpler subproblems.
Example Problem:
Determine the number of times a name occurs in a list
Input to the program:
list of names, name to look for
Output of the program:
the number of times the name occurs in a list

ALGORITHM DESIGN AND REPRESENTATION


Once our problem is clearly defined, we can now set to finding a solution. In computer
programming, it is normally required to express our solution in a step-by-step manner.
An Algorithm is a clear and unambiguous specification of the steps needed to solve a problem.
It may be expressed in either Human language (English, Tagalog), through a graphical
representation like a flowchart or through a pseudocode, which is a cross between human
language and a programming language.
Now given the problem defined in the previous sections, how do we express our general
solution in such a way that it is simple yet understandable?
Expressing our solution through Human language:
1. Get the list of names, nameList
2. Get the name to look for, let's call this the keyname
3. Compare the keyname to each of the names in the list
4. If the keyname is the same with a name in the list, add 1 to the count
5. If all the names have been compared, output the result

Expressing our solution through a flowchart:


Figure 1. Example of a flow chart

Expressing our solution through pseudocode:


1. Start
2. Let nameList = List of Names
3. Let keyName = the name to be sought
4. Let Count = 0
5. For each name in NameList do the following
6. if name == keyName
7. Count = Count + 1
8. Display Count
9. Stop

Algorithm
Definition
A set of sequential steps usually written in Ordinary Language to solve a given problem is
called Algorithm.
It may be possible to solve to problem in more than one ways, resulting in more than one
algorithm. The choice of various algorithms depends on the factors like reliability, accuracy
and easy to modify. The most important factor in the choice of algorithm is the time
requirement to execute it, after writing code in High-level language with the help of a computer.
The algorithm which will need the least time when executed is considered the best.
Steps involved in algorithm development
An algorithm can be defined as “a complete, unambiguous, finite number of logical steps for
solving a specific problem “.
Step1. Identification of input: For an algorithm, there are quantities to be supplied called
input and these are fed externally. The input is to be identified first for any specified problem.
Step2: Identification of output: From an algorithm, at least one quantity is produced, called
for any specified problem.
Step3: Identification the processing operations: All the calculations to be performed in order
to lead to output from the input are to be identified in an orderly manner.
Step4: Processing Definiteness: The instructions composing the algorithm must be clear and
there should not be any ambiguity in them.
Step5: Processing Finiteness : If we go through the algorithm, then for all cases, the algorithm
should terminate after a finite number of steps.
Step6 : Possessing Effectiveness : The instructions in the algorithm must be sufficiently basic
and in practice they can be carried out easily.

An algorithm must possess the following properties


1. Finiteness: An algorithm must terminate in a finite number of steps
2. Definiteness: Each step of the algorithm must be precisely and unambiguously stated
3. Effectiveness: Each step must be effective, in the sense that it (should be primitive easily
convertible into program statement) can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it can be used to solve problems
of a specific type for any input data.
5. Input/output: Each algorithm must take zero, one or more quantities as input data produce
one or more output values. An algorithm can be written in English like sentences or in any
standard representation sometimes, algorithm written in English like languages are called
Pseudo Code.
Examples
1. Suppose we want to find the average of three numbers, the algorithm is as follows
Step 1 Read the numbers a, b, c
Step 2 Compute the sum of a, b and c
Step 3 Divide the sum by 3
Step 4 Store the result in variable d
Step 5 Print the value of d
Step 6 End of the program
2. Write an algorithm to calculate the simple interest using the formula.
Simple interest = P*N* R/100.
Where P is principle Amount, N is the number of years and R is the rate of interest.
Step 1: Read the three input quantities’ P, N and R.
Step 2 : Calculate simple interest as
Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.

3. Area of Triangle: Write an algorithm to find the area of the triangle.


Let b, c be the sides of the triangle ABC and A the included angle between the given sides.
Step 1: Input the given elements of the triangle namely sides b, c and angle between the sides
A.
Step 2: Area = (1/2) *b*C* sin A
Step 3: Output the Area
Step 4: Stop.

4. Write an algorithm to find the largest of three numbers X, Y,Z.


Step 1: Read the numbers X,Y,Z.
Step 2: if (X > Y)
Big = X
else BIG = Y
Step 3 : if (BIG < Z)
Step 4: Big = Z
Step 5: Print the largest number i.e. Big
Step 6: Stop.
5. Write down an algorithm to find the largest data value of a set of given data values
Algorithm largest of all data values:
Step 1: LARGE ← 0
Step 2: read NUM
Step 3: While NUM > = 0 do
3.1 if NUM > LARGE
3.1.1 then
3.1.1.1 LARGE← NUM
3.2. read NUM
Step 4: Write “largest data value is”, LARGE
Step 5: end.

6. Write an algorithm which will test whether a given integer value is prime or not.
Algorithm prime testing:
Step 1: M← 2
Step 2: read N
Step 3: MAX ← SQRT (N)
Step 4: While M < = MAX do
4.1 if (M* (N/M) = N
4.1.1 then
4.1.1.1 go to step 7
4.2. M ← M + 1
Step 5: Write “number is prime”
Step 6: go to step 8
Step 7: Write “number is not a prime”
Step 8: end.
7. Write algorithm to find the factorial of a given number N
Step 1: PROD ← 1
Step 2: I ← 0
Step 3: read N
Step 4: While I < N do
4.1 I ← I + 1
4.2. PROD ← PROD* I
Step 5: Write “Factorial of”, N, “is”, PROD
Step 6: end.
8. Write an algorithm to find sum of given data values until negative value is entered.
Algorithm Find – Sum
Step 1: SUM ← 0
Step 2: I ← 0
Step 3: read NEW VALUE
Step 4: While NEW VALUE < = 0 do
4.1 SUM ← SUM + NEW VALUE
4.2 I ← I + 1
4.3 read NEW VALUE
Step 5: Write “Sum of”, I, “data value is, “SUM
Step 6: END

9. Write an algorithm to calculate the perimeter and area of rectangle. Given its length and
width.
Step 1: Read length of the rectangle.
Step 2: Read width of the rectangle.
Step 3: Calculate perimeter of the rectangle using the formula perimeter = 2* (length + width)
Step 4: Calculate area of the rectangle using the formula area = length*width.
Step 5: Print perimeter.
Step 6: Print area.
Step 7: Stop.

Flowchart
A flow chart is a step by step diagrammatic representation of the logic paths to solve a given
problem. Or A flowchart is visual or graphical representation of an algorithm.
The flowcharts are pictorial representation of the methods to b used to solve a given problem
and help a great deal to analyze the problem and plan its solution in a systematic and orderly
manner. A flowchart when translated in to a proper computer language, results in a complete
program.
Advantages of Flowcharts
1. The flowchart shows the logic of a problem displayed in pictorial fashion which felicitates
easier checking of an algorithm.
2. The Flowchart is good means of communication to other users. It is also a compact means
of recording an algorithm solution to a problem.
3. The flowchart allows the problem solver to break the problem into parts. These parts can be
connected to make master chart.
4. The flowchart is a permanent record of the solution which can be consulted at a later time.

Table 2. Differences between Algorithm and Flowchart


S/N Algorithm Flowchart
1. A method of representing them step-by- Flowchart is diagrammatic representation
step logical procedure for solving a of an algorithm. It is constructed using
problem different types of boxes and symbols.
2. It contains step-by-step English The flowchart employs a series of blocks
descriptions, each step representing a and arrows, each of which represents a
particular operation leading to solution particular step in an algorithm
of problem
3 These are particularly useful for small These are useful for detailed representations
problems of complicated programs
4 For complex programs, algorithms prove For complex programs, Flowcharts prove to
to be Inadequate be adequate

FLOWCHARTING SYMBOLS AND THEIR MEANINGS


A flowchart is a design tool used to graphically represent the logic in a solution.
Flowcharts typically do not display programming language commands. Rather, they state the
concept in English or mathematical notation.
Here are some guidelines for commonly used symbols in creating flowcharts. You can use any
symbols in creating your flowcharts, as long as you are consistent in using them.
Table 3: Flowchart Symbols
Symbol Name Meaning
Process Symbol Represents the process of executing a
defined operation or groups of
operations that results in a change in
value, form, or location of information.
Also functions as the default symbol
when no other symbol is available.
Input/Output Represents an I/O function, which
(I/O) Symbol makes data available for processing
(input) or displaying (output) of
processed information.

Flowline Symbol Represents the sequence of available


information and executable operations.
The lines connect other symbols, and
the arrowheads are mandatory only for
right-to-left and bottom-to-top flow.

Annotation Represents the addition of descriptive


Symbol information, comments, or explanatory
notes as clarification. The vertical line
and the broken line may be placed on
the left, as shown, or on the right.

Decision Symbol Represents a decision that determines


which of a number of alternative paths
is to be followed.

Terminal Symbol Represents the beginning, the end, or a


point of interruption or delay in a
program.

Connector Represents any entry from, or exit to,


Symbol another part of the flowchart. Also
serves as an off-page connector.
Predefined Represents a named process consisting
Process Symbol of one or more operations or program
steps that are specified elsewhere.

Simple Problems using Flow Chart


Draw the Flowchart for the following
1. Draw the Flowchart to find Roots of Quadratic equation ax2+ bx + c= 0. The coefficients a,
b, c are the input data.

2. Draw a flowchart to find out the biggest of the three unequal positive numbers.
3. Draw a flowchart for adding the integers from 1 to 100 and to print the sum.

4. Draw a flowchart to find the factorial of given positive integer N.


5. Develop a flowchart to illustrate how to make a Land phone telephone call
Flowchart for Telephone call
6. ABC company plans to give a 6% year-end bonus to each of its employees earning N6,000
or more per month , and a fixed N250/bonus to the remaining employees. Draw a flowchart for
calculating the bonus for an employee

Pseudo code
The Pseudo code is neither an algorithm nor a program. It is an abstract form of a program. It
consists of English like statements which perform the specific operations. It is defined for an
algorithm. It does not use any graphical representation. In pseudo code, the program is
represented in terms of words and phrases, but the syntax of program is not strictly followed.
Advantages:
• Easy to read
• Easy to understand
• Easy to modify.
Example: Write a pseudo code to perform the basic arithmetic operations.
Read n1, n2
Sum = n1 + n2
Diff = n1 – n2
Mult = n1 * n2
Quot = n1/n2
Print sum, diff, mult, quot
End.
Activity
Practice more sample problems on algorithm and Flowcharts.

CODING AND DEBUGGING


After constructing the algorithm, it is now possible to create the source code. Using the
algorithm as basis, the source code can now be written using the chosen programming
language.
Most of the time, after the programmer has written the program, the program isn't 100%
working right away. The programmer has to add some fixes to the program in case of errors
(also called bugs) that occurs in the program. This process is called debugging.
There are two types of errors that a programmer will encounter along the way. The first one is
compile-time error, and the other is runtime error.
Compile time error
Compile-Time Errors occur if there is a syntax error in the code. The compiler will detect the
error and the program won't even compile. At this point, the programmer is unable to form an
executable that a user can run until the error is fixed. Forgetting a semi-colon at the end of a
statement or misspelling a certain command, for example, is a compile-time error. It's
something the compiler can detect as an error.
Run time error
Compilers aren't perfect and so can't catch all errors at compile time. This is especially true for
logic errors such as infinite loops. This type of error is called runtime error. For example, the
actual syntax of the code looks okay. But when you follow the code's logic, the same piece of
code keeps executing over and over again infinitely so that it loops. In such a case, compilers
aren't really smart enough to catch all of these types of errors at compile-time, and therefore,
the program compiles fine into an executable file. However, and unfortunately, when the end-
user runs the program, the program (or even their whole computer) freezes up due to an infinite
loop. Other types of run-time errors are when an incorrect value is computed, the wrong thing
happens, etc.

NUMBER SYSTEMS AND CONVERSIONS


Numbers can be represented in a variety of ways. The representation depends on what is called
the BASE. The following are the four most common representations.
Decimal
We normally represent numbers in their decimal form. Numbers in decimal form are in base
10. This means that the only digits that appear are 0-9. Here are examples of numbers written
in decimal form:
12610 (normally written as just 126)
1110 (normally written as just 11)
Binary
Numbers in binary form are in base 2. This means that the only legal digits are 0 and 1. We
need to write the subscript 2 to indicate that the number is a binary number. Here are examples
of numbers written in binary form:
11111102
10112
Octal
Numbers in octal form are in base 8. This means that the only legal digits are 0-7. We need to
write the subscript 8 to indicate that the number is an octal number. Here are examples of
numbers written in octal form:
1768
138
Hexadecimal
Numbers in hexadecimal form are in base 16. This means that the only legal digits are 0-9 and
the letters A-F (or a-f, lowercase or uppercase does not matter). We need to write the subscript
16 to indicate that the number is a hexadecimal number. Here are examples of numbers written
in hexadecimal form:
7E16
B16
Table 3: Hexadecimal Numbers and their Equivalence to decimal numbers
Hexadecimal 0 1 2 3 4 5 6 7 8 9 A C C D E F
Decimal
Equivalent 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Table 4: Summary of Examples

CONVERSIONS
Decimal to Binary / Binary to Decimal
For Example:
Decimal to Binary
12610 = ? 2
128 64 32 16 8 4 2 1
0 1 1 1 1 1 1 0
12610 = 011111102
Binary to Decimal
011111102 = ?10

Decimal to Octal (or Hexadecimal)/Octal (or Hexadecimal) to Decimal


Converting decimal numbers to Octal or hexadecimal is basically the same as converting
decimal to binary. However, instead of having 2 as the divisor, you replace it with 8 (for octal)
or 16 (for hexadecimal). In a simpler method, we can use octal and hexadecimal tables for the
conversions.
Octal table (23 =8)
Decimal no A B C
0 0 0 0
1 0 0 1
2 0 1 0
3 0 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1

Hexadecimal table (24 =16)


Decimal no A B C D
0 0 0 0 0
1 0 0 0 1
2 0 0 1 0
3 0 0 1 1
4 0 1 0 0
5 0 1 0 1
6 0 1 1 0
7 0 1 1 1
8 1 0 0 0
9 1 0 0 1
A 1 0 1 0
B 1 0 1 1
C 1 1 0 0
D 1 1 0 1
E 1 1 1 0
F 1 1 1 1

For Example (Decimal to Octal):


12610 = ? 8
Step 1. Convert 126 to binary
12610 = 011111102
Step 2. Group the binary into 3 digits
001, 111, 110
Step 3. Check for the value of each group in the octal table
001 111 110
1 7 6
12610 = 1768

For Example (Decimal to Hexadecimal):


12610 = ? 16
Step 1. Convert 126 to binary
12610 = 011111102
Step 2. Group the binary into 4 digits
0000, 0111, 1110
Step 3. Check for the value of each group in the hexadecimal table
0000, 0111, 1110
0 7 E

7E16

For Example (Octal to decimal):


1768 = ? 10

For Example (Hexadecimal to Decimal):


7E16 = ? 10
Octal to Hexadecimal/Hexadecimal to Octal
For Example (Octal to hexadecimal):
1768 = ? 16
Step 1. Convert 1768 to binary using the octal table
1768 = 0011111102
Step 2. Group the binary into 4 digits
0000, 0111, 11102
Step 3. Check for the value of each group in the hexadecimal table
0000, 0111, 1110
0 7 E

7E16

For Example (Hexadecimal to octal):


7E16 = ? 8
Step 1. Convert 7E16 to binary using the hexadecimal table
7E16 = 011111102
Step 2. Group the binary into 3 digits
001, 111, 1102
Step 3. Check for the value of each group in the octal table
001, 111, 110
1 7 6

1768
PASCAL OVERVIEW
Pascal is a general-purpose, high-level language that was originally developed by Niklaus
Wirth in the early 1970s. It was developed for teaching programming as a systematic discipline
and to develop reliable and efficient programs.
Pascal is Algol-based language and includes many constructs of Algol. Algol-60 is a subset of
Pascal. Pascal offers several data types and programming structures. It is easy to understand
and maintain the Pascal programs.
Pascal has grown in popularity in the teaching and academics arena for various reasons:
• Easy to learn.
• Structured language.
• It produces transparent, efficient and reliable programs.
• It can be compiled on a variety of computer platforms.

Features of the Pascal Language


Pascal is a structured program and has the following features:
• Pascal is a strongly typed language.
• It offers extensive error checking.
• It offers several data types like arrays, records, files and sets.
• It offers a variety of programming structures.
• It supports structured programming through functions and procedures.
• It supports object oriented programming.

Facts about Pascal


• The Pascal language was named for Blaise Pascal, French mathematician and pioneer
in computer development.
• Niklaus Wirth completed development of the original Pascal programming language in
1970.
• Pascal is based on the block structured style of the Algol programming language.
• Pascal was developed as a language suitable for teaching programming as a systematic
discipline, whose implementations could be both reliable and efficient.
• Pascal was the primary high-level language used for development in the Apple Lisa,
and in the early years of the Mac.
• In 1986, Apple Computer released the first Object Pascal implementation, and in 1993,
the Pascal Standards Committee published an Object-Oriented Extension to Pascal.

Why to use Pascal?


Pascal allows the programmers to define complex structured data types and build dynamic and
recursive data structures, such as lists, trees and graphs. Pascal offers features like records,
enumerations, subranges, dynamically allocated variables with associated pointers and sets.
Pascal allows nested procedure definitions to any level of depth. This truly provides a great
programming environment for learning programming as a systematic discipline based on the
fundamental concepts.
Among the most amazing implementations of Pascal are:
• Skype
• Total Commander
• TeX
• Macromedia Captivate
• Apple Lisa
• Various PC Games
• Embedded Systems

Program Structure
A Pascal program basically consists of the following parts:
• Program name
• Uses command
• Type declarations
• Constant declarations
• Variables declarations
• Functions declarations
• Procedures declarations
• Main program block
• Statements and Expressions within each block
• Comments

Every Pascal program generally have a heading statement, a declaration and an execution part
strictly in that order. Following format shows the basic syntax for a Pascal program:

program {name of the program}


uses {comma delimited names of libraries you use}
const {global constant declaration block}
var {global variable declaration block}
function {function declarations, if any}
{ local variables }
begin
...
end;
procedure { procedure declarations, if any}
{ local variables }
begin
...
end;
begin { main program block starts}
...
end. { the end of main program block }

Pascal Hello World Example


Following is a simple Pascal code that would print the words "Hello, World!":

program HelloWorld;
uses crt;
(* Here the main program block starts *)
begin
writeln('Hello, World!');
readkey;
end.

Let us look various parts of the above program:


• The first line of the program program HelloWorld; indicates the name of the program.
• The second line of the program uses crt; is a preprocessor command, which tells the
compiler to include the crt unit before going to actual compilation.
• The next lines enclosed within begin and end statements are the main program block.
Every block in Pascal is enclosed within a begin statement and an end statement.
However, the end statement indicating the end of the main program is followed by a
full stop (.) instead of semicolon (;).
• The begin statement of the main program block is where the program execution begins.
• The lines within (*...*) will be ignored by the compiler and it has been put to add a
comment in the program.
• The statement writeln('Hello, World!'); uses the writeln function available in Pascal
which causes the message "Hello, World!" to be displayed on the screen.
• The statement readkey; allows the display to pause until the user presses a key. It is part
of the crt unit. A unit is like a library in Pascal.
• The last statement end. ends your program.

Basic Syntax
You have seen a basic structure of Pascal program, so it will be easy to understand other basic
building blocks of the Pascal programming language.
This section shows the basic syntax of Pascal program.
Variables
A variable definition is put in a block beginning with a var keyword, followed by definitions
of the variables as follows:
var
A_Variable, B_Variable ... : Variable_Type;

Pascal variables are declared outside the code-body of the function which means they are not
declared within the begin and end pairs, but they are declared after the definition of the
procedure/function and before the begin keyword. For global variables, they are defined after
the program header.

Functions/Procedures
In Pascal, a procedure is set of instructions to be executed, with no return value and a function
is a procedure with a return value. The definition of function/procedures will be as follows:
Function Func_Name(params...) : Return_Value;
Procedure Proc_Name(params...);

Comments
The multiline comments are enclosed within curly brackets and asterisks as {* ... *}. Pascal
allows single-line comment enclosed within curly brackets { ... }.

{* This is a multi-line comments


and it will span multiple lines. *}
{ This is a single line comment in pascal }

Case Sensitivity
Pascal is a case non-sensitive language, which means you can write your variables, functions
and procedure in either case. Like variables A_Variable, a_variable and A_VARIABLE have
same meaning in Pascal.

Reserved Words in Pascal


The reserved words are predefined keywords. The statements in Pascal are designed with some
specific Pascal words, which are called the reserved words. For example, the words, program,
input, output, var, real, begin, readline, writeline, end, and, array, begin, case, const, div, do
downto, else, file, for, function, goto, if, in, label, mod, nil, not, of, or, packed, procedure,
record, repeat, set, then, to, type, until, Var, while and with are all reserved words.
Character set and Identifiers in Pascal
The Pascal character set consists of:
• All upper case letters (A-Z)
• All lower case letters (a-z)
• All digits (0-9)
• Special symbols - + * / := , . ;. () [] = {} ` white space
The entities in a Pascal program like variables and constants, types, functions, procedures and
records, etc., have a name or identifier. An identifier is a sequence of letters and digits,
beginning with a letter. Special symbols and blanks must not be used in an identifier.

Data Types
This section shows the data types used in a Pascal program.
Data types of an entity indicates the meaning, constraints, possible values, operations, functions
and mode of storage associated with it.
Data types can be categorized as scalar, pointer and structured data types. Examples of scalar
data types are integer, real, Boolean, character, subrange and enumerated. Structured data types
are made of the scalar types; for example, arrays, records, files and sets. We will discuss the
pointer data types later.
Pascal Data Types:
Pascal data types can be summarized as below in the following diagram:
Type Declarations:
The type declaration is used to declare the data type of an identifier. Syntax of type declaration
is:

type-identifier-1, type-identfier-2 = type-specifier;

For example, the following declaration defines the variables days and age as integer type, yes
and true as Boolean type, name and city as string type, fees and expenses as real type.
type
days, age = integer;
yes, true = boolean;
name, city = string;

Constants
These are identifier that cannot change throughout the program execution. All constant
declarations must be given before the variable declaration.

Syntax of constant type declaration is follows:

const
Identifier = contant_value;

For example,
const
PIE = 3.141592;

Enumerated types
Enumerated data types are user-defined data types. They allow values to be specified in a list.
The domain of enumerated type identifiers cannot consist of numeric or character constants.
Syntax
type
enum-identifier = (item1, item2, item3, ... );
For example,
type
SUMMER = (April, May, June, July, September);
COLORS = (Red, Green, Blue, Yellow, Magenta, Cyan, Black, White);
TRANSPORT = (Bus, Train, Airplane, Ship);

Subrange Types
Subrange types allow a variable to assume values that lie within a certain range. For example,
if the age of voters should lie between 18 to 100 years, a variable named age could be declared
as:

var
age: 18 ... 100;

Syntax for declaring a subrange type is as follows:

type
subrange-identifier = lower-limit ... upper-limit;

For example,
const
P = 18;
Q = 90;
type
Number = 1 ... 100;
Subrange types can be created from a subset of an already defined enumerated type,
For example:
type
months = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec);
Summer = Apr ... Aug;
Winter = Oct ... Dec;
Variable Types
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in Pascal has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the set of
operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Pascal is not case-sensitive, so uppercase and
lowercase letters mean same here. The following are the basic variable types:
Basic Variables in Pascal
Type Description
Character Typically a single octet (one byte). This is an integer type.
Integer The most natural size of integer for the machine.
Real A single-precision floating point value
Boolean Specifies true or false logical values. This is also an integer type.
Enumerated Specifies a user-defined list.
Subrange Represents variables, whose values lie within a range.
String Stores an array of characters.

Variable Declaration in Pascal


All variables must be declared before we use them in Pascal program. All variable declarations
are followed by the var keyword. A declaration specifies a list of variables, followed by a colon
(:) and the type. Syntax of variable declaration is:

var
variable_list : type;

Variable Initialization in Pascal


Variables are assigned a value with a colon and the equal sign, followed by a constant
expression. The general form of assigning a value is:

var
variable_name : type = value;

Let us look at examples, which makes use of various types of variables:

program Greetings;
const
message = ' Welcome to the world of Pascal ';
type
name = string;
var
firstname, surname: name;
begin
writeln('Please enter your first name: ');
readln(firstname);
writeln('Please enter your surname: ');
readln(surname);
writeln;
writeln(message, ' ', firstname, ' ', surname);
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
Please enter your first name:
John
Please enter your surname:
Smith
Welcome to the world of Pascal John Smith

program exEnumeration;
type
beverage = (coffee, tea, milk, water, coke, limejuice);
var
drink:beverage;
begin
writeln('Which drink do you want?');
writeln('You have ', sizeof(drink), ' choices');
end.

program exSubrange;
var
marks: 1 .. 100;
grade: 'A' .. 'E';
begin
writeln( 'Enter your marks(1 - 100): ');
readln(marks);
writeln( 'Enter your grade(A - E): ');
readln(grade);
writeln('Marks: ' , marks, ' Grade: ', grade);
end.

program const_circle (input,output);


const
PI = 3.141592654;
var
r, d, c : real; {variable declaration: radius, dia, circumference}
begin
writeln('Enter the radius of the circle');
readln(r);
d := 2 * r;
c := PI * d;
writeln('The circumference of the circle is ',c:7:2);
end.

OUTPUT
Enter the radius of the circle
23
The circumference of the circle is 144.51

Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. Pascal allows the following types of operators:
• Arithmetic operators e.g. +, -, *, div, mod
• Relational operators e.g. =, <>, >, <, >=, <=
• Boolean operators e.g. and, or, <=(NOT), and then, or else
• Bit operators e.g. &, !,~,<<, >>
• Set operators
• String operators

Operators Precedence in Pascal


Operators Precedence

~, not, Highest
*, /, div, mod, and, &
|, !, +, -, or,

CONTROL STRUCTURE
Normally, statements in a program are executed one after the other in the order in which they’re
written. This process is called sequential execution. Various PASCAL statements, enable you
to specify that the next statement to execute is not necessarily the next one in sequence. This
is called transfer of control. Structured programs are clearer, easier to debug and modify, and
more likely to be bug free in the first place.
Programs could be written in terms of only three control structures:
• the sequence structure
• the selection structure and
• the repetition structure.
SELECTION STRUCTURE
The selection structure are known as decision making structures. It require that the programmer
specify one or more conditions to be evaluated or tested by the program, along with a statement
or statements to be executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.
There are three basic types of selection statements:
i. If-then (Single-Selection) Statement
The if statement either performs (selects) an action, if a condition is true, or skips it, if the
condition is false. The if-then statement is the simplest form of control statement, frequently
used in decision making and changing the control flow of the program execution.
Syntax
Syntax for if-then statement is:
if condition then S

Where condition is a Boolean or relational condition and S is a simple or compound


statement.
Flow Diagram:

Example:
Let us try a complete example that would illustrate the concept:

program ifChecking;
var
{ local variable declaration }
a:integer;
begin
a:= 10;
(* check the boolean condition using if statement *)
if( a < 20 ) then
(* if condition is true then print the following *)
writeln('a is less than 20 ' );
writeln('value of a is : ', a);
end.

When the above code is compiled and executed, it produces the following result:

OUTPUT
a is less than 20
value of a is : 10
ii. if-then-else (Double Selection)Statement
The if-then-else statement performs an action if a condition is true and performs a different
action if the condition is false. The if-then single-selection statement performs an indicated
action only when the condition is true; otherwise, the action is skipped. The if-then-else double-
selection statement allows you to specify an action to perform when the condition is true and a
different action when the condition is false.
The switch statement performs one of many different actions, depending on the value of an
expression.
The if statement is a single-selection statement because it selects or ignores a single action (or,
as we’ll soon see, a single group of actions). The if…else statement is called a double-selection
statement because it selects between two different actions (or groups of actions). The switch
statement is called a multiple-selection statement because it selects among many different
actions (or groups of actions).

Syntax:
Syntax for the if-then-else statement is:
if condition then S1 else S2;
Where, S1 and S2 are different statements. Please note that the statement S1 is not followed by
a semicolon. In the if-then-else statements, when the test condition is true, the statement S1 is
executed and S2 is skipped; when the test condition is false, then S1 is bypassed and statement
S2 is executed.
For example,
if color = red then
writeln('You have chosen a red car')
else
writeln('Please choose a color for your car');

If the boolean expression condition evaluates to true, then the if-then block of code will be
executed, otherwise the else block of code will be executed.
Flow Diagram:

Example:
Let us try a complete example that would illustrate the concept:

program ifelseChecking;
var
{ local variable definition }
a : integer;
begin
a := 100;
(* check the boolean condition *)
if( a < 20 ) then
(* if condition is true then print the following *)
writeln('a is less than 20' )
else
(* if condition is false then print the following *)
writeln('a is not less than 20' );
writeln('value of a is : ', a);
end.
When the above code is compiled and executed, it produces the following result:
OUTPUT
a is not less than 20
value of a is : 100

iii. The if-then-else if-then-else Statement


An if-then statement can be followed by an optional else if-then-else statement, which is very
useful to test various conditions using single if-then-else if statement. When using if-then, else
if-then, else statements there are few points to keep in mind.
• An if-then statement can have zero or one else's and it must come after any else if's.
• An if-then statement can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
• No semicolon (;) is given before the last else keyword, but all statements can be
compound statements.

Syntax:
The syntax of an if-then-else if-then-else statement in Pascal programming language is:

if(boolean_expression 1)then
S1 (* Executes when the boolean expression 1 is true *)
else if( boolean_expression 2) then
S2 (* Executes when the boolean expression 2 is true *)
else if( boolean_expression 3) then
S3 (* Executes when the boolean expression 3 is true *)
else
S4; ( * executes when the none of the above condition is true *)
Example:
The following example illustrates the concept:

program ifelse_ifelseChecking;
var
{ local variable definition }
a : integer;
begin
a := 100;
(* check the boolean condition *)
if (a = 10) then
(* if condition is true then print the following *)
writeln('Value of a is 10' )
else if ( a = 20 ) then
(* if else if condition is true *)
writeln('Value of a is 20' )
else if( a = 30 ) then
(* if else if condition is true *)
writeln('Value of a is 30' )
else
(* if none of the conditions is true *)
writeln('None of the values is matching' );
writeln('Exact value of a is: ', a );
end.

OUTPUT
The following example illustrates the concept:
None of the values is matching
Exact value of a is: 100

iv. Nested if-then Statements


It is always legal in Pascal programming to nest if-else statements, which means you can use
one if or else if statement inside another if or else if statement(s). Pascal allows nesting to any
level, however, if depends on Pascal implementation on a particular system.
Syntax:

The syntax for a nested if statement is as follows:


if( boolean_expression 1) then
if(boolean_expression 2)then S1
else
S2;

You can nest else if-then-else in the similar way as you have nested if-then statement. Please
note that, the nested if-then-else constructs gives rise to some ambiguity as to which else
statement pairs with which if statement. The rule is that the else keyword matches the first if
keyword (searching backwards) not already matched by an else keyword.

The above syntax is equivalent to:


if( boolean_expression 1) then
begin
if(boolean_expression 2)then
S1
else
S2;
end;
Example:
program nested_ifelseChecking;
var
{ local variable definition }
a, b : integer;
begin
a := 100;
b:= 200;
(* check the boolean condition *)
if (a = 100) then
(* if condition is true then check the following *)
if ( b = 200 ) then
(* if nested if condition is true then print the following *)
writeln('Value of a is 100 and value of b is 200' );
writeln('Exact value of a is: ', a );
writeln('Exact value of b is: ', b );
end.

When the above code is compiled and executed, it produces the following result:

OUTPUT
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

v. Case (multiple selection) Statement


You have observed that if-then-else statements enable us to implement multiple decisions in a
program. This can also be achieved using the case statement in simpler way.

Syntax:
The syntax of the case statement is:

case (expression) of
L1 : S1;
L2: S2;
...
...
Ln: Sn;
end;
Where, L1, L2... are case labels or input values, which could be integers, characters, boolean
or enumerated data items. S1, S2, ... are Pascal statements, each of these statements may have
one or more than one case label associated with it. The expression is called the case selector or
the case index. The case index may assume values that correspond to the case labels.
The case statement must always have an end statement associated with it.

The following rules apply to a case statement:


• The expression used in a case statement must have an integral or enumerated type or be
of a class type in which the class has a single conversion function to an integral or
enumerated type.
• You can have any number of case statements within a case. Each case is followed by
the value to be compared to and a colon.
• The case label for a case must be the same data type as the expression in the case
statement, and it must be a constant or a literal.
• The compiler will evaluate the case expression. If one of the case label's value matches
the value of the expression, the statement that follows this label is executed. After that,
the program continues after the final end.
• If none of the case label matches the expression value, the statement list after the else
or otherwise keyword is executed. This can be an empty statement list. If no else part
is present and no case constant matches the expression value, program flow continues
after the final end.
• The case statements can be compound statements (i.e., a Begin ... End block).

Flow Diagram:
Example:
The following example illustrates the concept:
program checkCase;
var
grade: char;
begin
grade := 'A';

case (grade) of
'A' : writeln('Excellent!' );
'B', 'C': writeln('Well done' );
'D' : writeln('You passed' );
'F' : writeln('Better try again' );
end;
writeln('Your grade is ', grade );
end.

When the above code is compiled and executed, it produces the following result:

OUTPUT
Excellent!
Your grade is A

vi. Case Else Statement


The case-else statement uses an else term after the case labels, just like an if-then-else construct.
Syntax:
The syntax for the case-else statement is:

case (expression) of
L1 : S1;
L2 : S2;
...
...
Ln: Sn;
else
Sm;
end;

Flow Diagram:

Example:
The following example illustrates the concept:

program checkCase;
var
grade: char;
begin
grade := 'F';
case (grade) of
'A' : writeln('Excellent!' );
'B', 'C': writeln('Well done' );
'D' : writeln('You passed' );
else
writeln('You really did not study right!' );
end;
writeln('Your grade is ', grade );
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
You really did not study right!
Your grade is F

vii. Nested Case Statements


It is possible to have a case statement as part of the statement sequence of an outer case
statement. Even if the case constants of the inner and outer case contain common values, no
conflicts will arise.
Syntax:
The syntax for a nested case statement is as follows:
case (ch1) of
'A': begin
writeln('This A is part of outer case' );
case(ch2) of
'A': writeln('This A is part of inner case' );
'B': (* case code *)
...
end; {end of inner case}
end; (* end of case 'A' of outer statement *)
'B': (* case code *)
'C': (* case code *)
...
end; {end of outer case}

Example:
The following program illustrates the concept.

program checknestedCase;
var
a, b: integer;
begin
a := 100;
b := 200;
case (a) of
100: begin
writeln('This is part of outer statement' );
case (b) of
200: writeln('This is part of inner statement' );
end;
end;
end;
writeln('Exact value of a is : ', a );
writeln('Exact value of b is : ', b );
end.

REPETITION STRUCTURE
There may be a situation, when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. Programming languages provide various control
structures that allow for more complicated execution paths.
A repetition or loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the programming
languages:

Pascal programming language provides the following types of repetition or loop constructs to
handle looping requirements.
Loop Type Description
while-do loop Repeats a statement or group of statements until a given condition is
true. It tests the condition before executing the loop body.
or-do loop Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
repeat-until loop Like a while statement, except that it tests the condition at the end of
the loop body.
nested loops You can use one or more loop inside any another while, for or repeat
until loop.

i. while-do loop
A while-do loop statement in Pascal allows repetitive computations till some test condition is
satisfied. In other words, it repeatedly executes a target statement as long as a given condition
is true.
Syntax:
The syntax of a while-do loop is:
while (condition) do S;

Where condition is a Boolean or relational expression, whose value would be true or false and
S is a simple statement or group of statements within BEGIN ... END block.
For example,
while number>0 do
begin
sum := sum + number;
number := number - 2;
end;

When the condition becomes false, program control passes to the line immediately following
the loop.
Flow Diagram:

Here, key point of the while loop is that the loop might not ever run. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.
Example:
program whileLoop;
var
a: integer;
begin
a := 10;
while a < 20 do
begin
writeln('value of a: ', a);
a := a + 1;
end;
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

ii. For-do LOOP


A for-do loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax:
The syntax for the for-do loop in Pascal is as follows:
for < variable-name > := < initial_value > to [down to] < final_value > do
S;

Where, the variable-name specifies a variable of ordinal type, called control variable or index
variable; initial_value and final_value values are values that the control variable can take; and
S is the body of the for-do loop that could be a simple statement or a group of statements.
For example:
for i:= 1 to 10 do writeln(i);
Here is the flow of control in a for-do loop:
• The initial step is executed first, and only once. This step allows you to declare and
initialize any loop control variables.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for-do loop.
• After the body of the for-do loop executes, the value of the variable in increased or
decreased.
• The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the for-do loop terminates.
Flow Diagram

Example:
program forLoop;
var
a: integer;
begin
for a := 10 to 20 do
begin
writeln('value of a: ', a);
end;
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

iii. Repeat-Until Loop


Unlike for and while loops, which test the loop condition at the top of the loop, the repeat-until
loop in Pascal checks its condition at the bottom of the loop.
A repeat-until loop is similar to a while loop, except that a repeat-until loop is guaranteed to
execute at least one time.
Syntax:

repeat
S1;
S2;
...
...
Sn;
until condition;
For example,
repeat
sum := sum + number;
number := number - 2;
until number = 0;

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to repeat and the statement(s) in the
loop execute again. This process repeats until the given condition becomes false.

Flow Diagram:

Example:
program repeatUntilLoop;
var
a: integer;
begin
a := 10;
(* repeat until loop execution *)
repeat
writeln('value of a: ', a);
a := a + 1
until a = 20;
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

iv. Nested Loops


Pascal allows using one loop inside another loop. Following section shows few examples to
illustrate the concept.
The syntax for a nested for-do loop statement in Pascal is as follows:
for variable1:=initial_value1 to [downto] final_value1 do
begin
for variable2:=initial_value2 to [downto] final_value2 do
begin
statement(s);
end;
end;
The syntax for a nested while-do loop statement in Pascal is as follows:
while(condition1)do
begin
while(condition2) do
begin
statement(s);
end;
statement(s);
end;

The syntax for a nested repeat ... until loop Pascal is as follows:
repeat
statement(s);
repeat
statement(s);
until(condition2);
until(condition1);

A final note on loop nesting is that you can put any type of loop inside of any other type of
loop. For example, a for loop can be inside a while loop or vice versa.

Example:
The following program uses a nested for loop to find the prime numbers from 2 to 50:
program nestedPrime;
var
i, j:integer;
begin
for i := 2 to 50 do
begin
for j := 2 to i do
if (i mod j)=0 then
break; {* if factor found, not prime *}
if(j = i) then
writeln(i , ' is prime' );
end;
end.

When the above code is compiled and executed, it produces the following result:

OUTPUT
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Pascal supports the following control statements.
Control Statements Description
break statement Terminates the loop or case statement and transfers execution to the
statement immediately following the loop or case statement.
continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
goto statement Transfers control to the labeled statement. Though it is not advised to
use goto statement in your program.

i. break statement
The break statement in Pascal has the following two usages:
1. When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the case statement. If you are using nested loops
(i.e., one loop inside another loop), the break statement will stop the execution of the
innermost loop and start executing the next line of code after the block.
Syntax:
The syntax for a break statement in Pascal is as follows:
break;

Flow Diagram:
Example:

program exBreak;
var
a: integer;
begin
a := 10;
(* while loop execution *)
while a < 20 do
begin
writeln('value of a: ', a);
a:=a +1;
if( a > 15) then
(* terminate the loop using break statement *)
break;
end;
end.
When the above code is compiled and executed, it produces the following result:
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

ii. continue statement


The continue statement in Pascal works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any
code in between.
For the for-do loop, continue statement causes the conditional test and increment portions of
the loop to execute. For the while-do and repeat...until loops, continue statement causes the
program control to pass to the conditional tests.
Syntax:
The syntax for a continue statement in Pascal is as follows:
continue;
Flow Diagram:

Example:
program exContinue;
var
a: integer;
begin
a := 10;
(* repeat until loop execution *)
repeat
if( a = 15) then
begin
(* skip the iteration *)
a := a + 1;
continue;
end;
writeln('value of a: ', a);
a := a+1;
until ( a = 20 );
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
iii. goto statement
A goto statement in Pascal provides an unconditional jump from the goto to a labeled statement
in the same function.
NOTE: Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program, making the program hard to understand
and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the
goto.
Syntax:
The syntax for a goto statement in Pascal is as follows:

goto label;
...
...
label: statement

Flow Diagram:
Example:
The following program illustrates the concept.

program exGoto;
label 1;
var
a : integer;
begin
a := 10;
(* repeat until loop execution *)
1: repeat
if( a = 15) then
begin
(* skip the iteration *)
a := a + 1;
goto 1;
end;
writeln('value of a: ', a);
a:= a +1;
until a = 20;
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

FUNCTIONS
This section shows the general form of functions used in Pascal:
Subprograms
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design.' A
subprogram can be invoked by a subprogram/program, which is called the calling program.
Pascal provides two kinds of subprograms:
• Functions: these subprograms return a single value.
• Procedures: these subprograms do not return a value directly.

Functions
A function is a group of statements that together perform a task. Every Pascal program has at
least one function, which is the program itself, and all the most trivial programs can define
additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function.
Pascal standard library provides numerous built-in functions that your program can call. For
example, function AppendStr() appends two strings, function New() dynamically allocates
memory to variables and many more functions.
Defining a Function:
In Pascal, a function is defined using the function keyword. The general form of a function
definition is as follows:
function name(argument(s): type1; argument(s): type2; ...): function_type;
local declarations;
begin
...
< statements >
...
name:= expression;
end;
A function definition in Pascal consists of a function header, local declarations and a function
body. The function header consists of the keyword function and a name given to the function.
Here are all the parts of a function:
• Arguments: The argument(s) establish the linkage between the calling program and the
function identifiers and also called the formal parameters. A parameter is like a
placeholder. When a function is invoked, you pass a value to the parameter. This value
is referred to as actual parameter or argument. The parameter list refers to the type,
order, and number of parameters of a function. The formal parameters list appearing in
the function statement could be simple or subscripted variables, arrays or structured
variables, or subprograms.
• Return-Type: All functions must return a value, so all functions must be assigned a
type. The function-type is the data type of the value the function returns. It may be
standard, user-defined scalar or subrange type but it cannot be structured type.
• Local declarations: Local declarations refer to the declarations for labels, constants,
variables, functions and procedures, which are application to the body of function only.
• Function Body: The function body contains a collection of statements that define what
the function does. It should always be enclosed between the reserved words begin and
end. It is the part of a function where all computations are done. The last statement in
the body must be an end statement.
Following is an example showing how to define a function in pascal:
(* function returning the max between two numbers *)
function max(num1, num2: integer): integer;
var
(* local variable declaration *)
result: integer;
begin
if (num1 > num2) then
result := num1
else
result := num2;
max := result;
end;

Calling a Function:
While creating a function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task. When a program calls
a function, program control is transferred to the called function. A called function performs
defined task, and when its return statement is executed or when it last end statement is reached,
it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name,
and if function returns a value, then you can store returned value.
Following is a simple example to show the usage:

program exFunction;
var
a, b, ret : integer;
(*function definition *)
function max(num1, num2: integer): integer;
var
(* local variable declaration *)
result: integer;
begin
if (num1 > num2) then
result := num1
else
result := num2;
max := result;
end;
begin
a := 100;
b := 200;
(* calling a function to get max value *)
ret := max(a, b);
writeln( 'Max value is : ', ret );
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
Max value is : 200

PROCEDURE
This section explains procedure concepts used in Pascal:
Procedures are subprograms that, instead of returning a single value, allow to obtain a group
of results.
Defining a Procedure:
In Pascal, a procedure is defined using the procedure keyword. The general form of a procedure
definition is as follows:
procedure name(argument(s): type1, argument(s): type 2, ... );
< local declarations >
begin
< procedure body >
end;

A procedure definition in Pascal consists of a header, local declarations and a body of the
procedure. The procedure header consists of the keyword procedure and a name given to the
procedure. Here are all the parts of a procedure:
• Arguments: The argument(s) establish the linkage between the calling program and the
procedure identifiers and also called the formal parameters. Rules for arguments in
procedures are same as that for the functions.
• Local declarations: Local declarations refer to the declarations for labels, constants,
variables, functions and procedures, which are applicable to the body of the procedure
only.
• Procedure Body: The procedure body contains a collection of statements that define
what the procedure does. It should always be enclosed between the reserved words
begin and end. It is the part of a procedure where all computations are done.

Following is the source code for a procedure called findMin(). This procedure takes 4
parameters x, y, z and m and stores the minimum among the first three variables in the variable
named m. The variable m is passed by reference (we will discuss passing arguments by
reference a little later):
procedure findMin(x, y, z: integer; var m: integer);
(* Finds the minimum of the 3 values *)
begin
if x < y then
m := x
else
m := y;
if z <m then
m := z;
end; { end of procedure findMin }

Calling a Procedure:
While creating a procedure, you give a definition of what the procedure has to do. To use the
procedure, you will have to call that procedure to perform the defined task. When a program
calls a procedure, program control is transferred to the called procedure. A called procedure
performs the defined task, and when its last end statement is reached, it returns the control back
to the calling program.
To call a procedure, you simply need to pass the required parameters along with the procedure
name as shown below:
program exProcedure;
var
a, b, c, min: integer;
procedure findMin(x, y, z: integer; var m: integer);
(* Finds the minimum of the 3 values *)
begin
if x < y then
m:= x
else
m:= y;
if z < m then
m:= z;
end; { end of procedure findMin }
begin
writeln(' Enter three numbers: ');
readln( a, b, c);
findMin(a, b, c, min); (* Procedure call *)
writeln(' Minimum: ', min);
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
Enter three numbers:
89 45 67
Minimum: 45

Recursive Subprograms
We have seen that a program or subprogram may call another subprogram. When a subprogram
calls itself, it is referred to as a recursive call and the process is known as recursion.
The following program calculates the factorial of a given number by calling itself recursively.
program exRecursion;
var
num, f: integer;
function fact(x: integer): integer; (* calculates factorial of x - x! *)
begin
if x=0 then
fact := 1
else
fact := x * fact(x-1); (* recursive call *)
end; { end of function fact}
begin
writeln(' Enter a number: ');
readln(num);
f := fact(num);
writeln(' Factorial ', num, ' is: ' , f);
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
Enter a number:
5
Factorial 5 is: 120

Following is another example, which generates the Fibonacci Series for a given number using
a recursive function:
program recursiveFibonacci;
var
i: integer;
function fibonacci(n: integer): integer;
begin
if n=1 then
fibonacci := 0
else if n=2 then
fibonacci := 1
else
fibonacci := fibonacci(n-1) + fibonacci(n-2);
end;
begin
for i:= 1 to 10 do
write(fibonacci (i), ' ');
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
0 1 1 2 3 5 8 13 21 34

Arguments of a Subprogram:
If a subprogram (function or procedure) is to use arguments, it must declare variables that
accept the values of the arguments. These variables are called the formal parameters of the
subprogram.
The formal parameters behave like other local variables inside the subprogram and are created
upon entry into the subprogram and destroyed upon exit.
While calling a subprogram, there are two ways that arguments can be passed to the
subprogram:

Call Type Description


Call by value This method copies the actual value of an argument into the formal
parameter of the subprogram. In this case, changes made to the parameter
inside the subprogram have no effect on the argument.
Call by This method copies the address of an argument into the formal parameter.
reference Inside the subprogram, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect the
argument.

By default, Pascal uses call by value to pass arguments. In general, this means that code within
a subprogram cannot alter the arguments used to call the subprogram. The example program
we used in the chapter 'Pascal - Functions' called the function named max() using call by value.
Whereas, the example program provided here (exProcedure) calls the procedure findMin()
using call by reference.
Call by Value
The call by value method of passing arguments to a subprogram copies the actual value of an
argument into the formal parameter of the subprogram. In this case, changes made to the
parameter inside the function have no effect on the argument.
By default, Pascal uses call by value method to pass arguments. In general, this means
#thatcode within a subprogram cannot alter the arguments used to call the subprogram.
Consider the procedure swap() definition as follows.

procedure swap(x, y: integer);


var
temp: integer;
begin
temp := x;
x:= y;
y := temp;
end;

Now, let us call the procedure swap() by passing actual values as in the following example:
program exCallbyValue;
var
a, b : integer;
(*procedure definition *)
procedure swap(x, y: integer);
var
temp: integer;
begin
temp := x;
x:= y;
y := temp;
end;
begin
a := 100;
b := 200;
writeln('Before swap, value of a : ', a );
writeln('Before swap, value of b : ', b );
(* calling the procedure swap by value *)
swap(a, b);
writeln('After swap, value of a : ', a );
writeln('After swap, value of b : ', b );
end.

When the above code is compiled and executed, it produces the following result:
OUTPUT
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
The program shows that there is no change in the values though they had been changed inside
the subprogram.
Call by Reference
The call by reference method of passing arguments to a subprogram copies the address of an
argument into the formal parameter. Inside the subprogram, the address is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
passed argument.
In order to pass the arguments by reference, Pascal allows to define variable parameters. This
is done by preceding the formal parameters by the keyword var. Let us take the example of the
procedure swap() that swaps the values in two variables and reflect the change in the calling
subprogram.

procedure swap(var x, y: integer);


var
temp: integer;
begin
temp := x;
x:= y;
y := temp;
end;

Next, let us call the procedure swap() by passing values by reference as in the following
example:

program exCallbyRef;
var
a, b : integer;
(*procedure definition *)
procedure swap(var x, y: integer);
var
temp: integer;
begin
temp := x;
x:= y;
y := temp;
end;
begin
a := 100;
b := 200;
writeln('Before swap, value of a : ', a );
writeln('Before swap, value of b : ', b );
(* calling the procedure swap by value *)
swap(a, b);
writeln('After swap, value of a : ', a );
writeln('After swap, value of b : ', b );
end.

When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

Which shows that now the procedure swap() has changed the values in the calling program.

ARRAYS
Pascal programming language provides a data structure called the array, which can store a
fixed-size sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables of
the same type.
Instead of declaring individual variables, such as number1, number2, ..., and number100, you
declare one array variable such as numbers and use numbers[1], numbers[2], and ...,
numbers[100] to represent individual variables. A specific element in an array is accessed by
an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Declaring Arrays
To declare an array in Pascal, a programmer may either declare the type and then create
variables of that array or directly declare the array variable.
The general form of type declaration of one-dimensional array is:

type
array-identifier = array[index-type] of element-type;
Where,
• array-identifier indicates the name of the array type.
• index-type specifies the subscript of the array; it can be any scalar data type except real
• element-type specifies the types of values that are going to be stored.
For example,
type
vector = array [ 1..25] of real;
var
velocity: vector;

Following is an example for declaration, assignment and accessing arrays:


program exArrays;
var
n: array [1..10] of integer; (* n is an array of 10 integers *)
i, j: integer;
begin
(* initialize elements of array n to 0 *)
for i := 1 to 10 do
n[ i ] := i + 100; (* set element at location i to i + 100 *)
(* output each array element's value *)
for j:= 1 to 10 do
writeln('Element[', j, '] = ', n[j] );
end.
OUTPUT
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Element[10] = 110

Multidimensional arrays
Pascal programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:

type
array-identifier = array [index-type1, index-type2, ...] of element-type;
var
a1, a2, ... : array-identifier;

POINTERS
Pointers in Pascal are easy and fun to learn. Some Pascal programming tasks are performed
more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be
performed without using pointers. So it becomes necessary to learn pointers to become a perfect
Pascal programmer.

As you know, every variable is a memory location and every memory location has its address
defined which can be accessed using the name of the pointer variable, which denotes an address
in memory.
What Are Pointers?
A pointer is a dynamic variable, whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a pointer
before you can use it to store any variable address.
The general form of a pointer variable declaration is:
type
ptr-identifier = ^base-variable-type;

Once a pointer type has been defined, we can use the var declaration to declare pointer
variables.
ar
p1, p2, ... : ptr-identifier;

Following are some valid pointer declarations:


type
Rptr = ^real;
Cptr = ^char;
Bptr = ^ Boolean;
Aptr = ^array[1..5] of real;
date-ptr = ^ date;
Date = record
Day: 1..31;
Month: 1..12;
Year: 1900..3000;
End;
var
a, b : Rptr;
d: date-ptr;

program exPointers;
var
number: integer;
iptr: ^integer;
begin
number := 100;
writeln('Number is: ', number);
iptr := @number;
writeln('iptr points to a value: ', iptr^);
iptr^ := 200;
writeln('Number is: ', number);
writeln('iptr points to a value: ', iptr^);
end.
When the above code is compiled and executed, it produces the following result:

OUTPUT
Number is: 100
iptr points to a value: 100
Number is: 200
iptr points to a value: 200

You might also like