CMP 201 Computer Programming I
CMP 201 Computer Programming I
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
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.
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.
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.
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.
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.
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
7E16
7E16
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.
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 HelloWorld;
uses crt;
(* Here the main program block starts *)
begin
writeln('Hello, World!');
readkey;
end.
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 { ... }.
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.
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:
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.
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;
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.
var
variable_list : type;
var
variable_name : type = value;
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.
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
~, 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
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
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
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.
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
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.
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
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
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
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
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
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
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
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:
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.
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.
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;
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;
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