Computer Programing of DCSA
Computer Programing of DCSA
DCSA 1303
DCSA 1303
COMPUTER PROGRAMMING
Writer
Dr. M. Kaykobad
Professor
Department of Computer Science and Engineering
Bangladesh University of Engineering and Technology
Co-ordinator
Dr. K. M. Rezanur Rahman
Professor
School of Science and Technology
Bangladesh Open University
Overall Supervision
Dean
School of Science and Technology
Bangladesh Open University
BANGLADESH OPEN UNIVERSITY
COMPUTER PROGRAMMING
ISBN 984-34-4003-X
1st Edition: April 1997
Revised and Reprint: December 2010
Dean
School of Science and Technology
Bangladesh Open University
Unit 1: Principles of Programming
Introduction
In this unit you will learn some general terms related to computer
programming such as languages and algorithms. You will be familiar
with these terms after reading this unit. The importance of an algorithm
in a programming language can be realised in lesson 2. Chronological
development of different languages and their uses are described in this
unit. A general rule of writing algorithm is also described here.
1
Computer Programming
In old days computers were very large and were not much reliable.
Programming was done by switches and there was no facility to use the
program. This approach of computer programming was completely a
hardware technology. Next the approach of machine language comes up.
In this approach instruction set of the computer consists of some
numerical digits. This instruction set is used to build up a program. This
code is difficult to understand for human beings. Next assembly
language was introduced. In assembly language the numerical codes are
replaced by suitable names which are understandable. This has made
programming easier.
This type of languages are like English language. But this is more
C++, Mathematica, Math
structured. Actually this type of languages support mathematical
Lab. etc..
notations used in arithmetic expressions. There are some special rules for
writing programs in high level languages. Pascal, C, C++, Mathematica,
Java, Math lab etc. Ada are all high level languages. High level
languages are easy to write, compile and suitable for error correction.
Visual Basic, SQL, ORACLE. Scientists are trying to develop computer languages like human
languages. They have not been successful but may be successful in near
future. These languages have greater built-in facility such as database
query, searching, sorting and interfacing. FoxPro, Cobol, Visual Basic,
MS Access, Oracle Forms and Reports, SQL systems make use of such
programs or languages. These are also known as the Fourth Generation
Languages (4GL).
Result Processing. Different offices need different system. So a ready made software is not
enough for this purpose. Special programs should be written for office
automation. These softwares may be used for accounting, payroll
systems, machine control, industrial control, billing system of electricity,
telephone and water, result processing of examination etc. It is important
to develop these softwares properly because the output of the whole
system depends on the output of the computer system.
2
Principles of Programming
Learner! you will learn C Programming instead of Pascal from the study
guide “Programming with C” and from its reference book.
3
Computer Programming
1.6 Exercise
a) Assembly
b) C
c) Pascal or C
d) machine language.
a) High level
b) Pascal or C
c) machine
d) Macro assembler.
4
Principles of Programming
algorithm
methods of writing algorithms
properties of algorithms.
4. The algorithm may have one or more inputs but it must have at least
one output.
5
Computer Programming
6
Principles of Programming
2.7 Exercise
2.7.1 Multiple choice questions
1. Which one of the following statement is true?
a) Algorithm is a part of programming
b) Algorithm is a part of system design
c) Algorithm is a part of problem solving
d) Algorithm is a part of system analysis.
2. Which one of the following statement is true?
a) An Algorithm is composed of finite number of steps
b) An Algorithm is composed of any number of steps
c) An Algorithm is composed of certain number of steps
d) An Algorithm is composed of infinite number of steps.
3. Which of the following is false?
a) Programming means translation of an algorithm into some machine
code
b) Programming means translation of an algorithm into structured
English
c) Programming means translation of an algorithm into a programming
language
d) Programming means translation of an algorithm into C programming
language.
7
Unit 2 : Programming Tools
Introduction
This unit will help learner about the programming tools like flowcharts,
pseudocodes, use of which improves the efficiency of programming and
programming skill. Flowcharts give a pictorial representation of the
logic. This is described with several symbols and rules associated with
them. Some examples on flowchart are also included for making the idea
clear. Pseudocode is another method which is very similar to
programming languages. The method of writing programmes with the
help of pseudocode has been given in the lessons. Decision tables are
another representation of programmes. Decision table describes how
conditional statements are represented in short cut format in a table. The
last lesson of this unit describes some methods of representing data
structures of input and output of the programme. Warnier-Orr diagrams
are such diagrams. Structured chart gives a pictorial representation of
programme by dividing main module into different modules and by
parameter passing between the modules.
9
Computer Programming
Do you see what is wrong? The instructions never mentioned the time
Of course, a human being when the oven must be turned off. Of course, a human being would
would probably compensate probably compensate for the inadequate instructions by making some
for the inadequate
instructions by making some assumptions or by his common-sense (which are not common to even
assumptions or by common- sophisticated machines like computers). A machine, however, would not
sense. and this “program” would not work properly.
The step 4 can be executed only after being confirmed that the water in
the kettle is already boiled. So, a condition must be tested satisfactorily
before the step 4 can be executed. So the correct algorithm will be:
3a.
check whether
water is boiled
Note that in this diagram we have enclosed each instruction in a box and
drawn an arrow to the instruction that follows. This type of diagram,
called a flowchart, is very useful as a means of visualising the
relationships among the statements of algorithms.
10
Programming Tools
.
.
.
.
.
.
Get dressed.
.
.
.
.
.
.
If you feared you might be delayed, your plans might include the
possibility of telephoning to say you would be late. To include this
possibility you must introduce a decision point into the algorithm:
1.
.
.
.
.
Statement 12 will be performed only if you were late and will not be
executed otherwise.
11
Computer Programming
The decision statement is statement 11. The flowchart for this algorithm
is shown in Figure 3.1.
Get dressed
No
Late?
Yes
Telephone friend
Catch a bus
Fig 3.1
The exact way in which this algorithm will be executed depends on the
data (that is, whether you are late or not):
But paths are implicit in the algorithm; the specific path executed will
depend on the circumstances.
Next, let us look at a task a bit more complex- getting to the college in
the morning.
0. Start.
12
Programming Tools
Normally, we begin from step 0 and go to the next statement and finished
GO TO and IF statements at the space end unless directed to do otherwise by a GO TO instruction
cause a program to branch- as in steps 3, 6, 9, 11 and 12 in the present example. Notice that this
that is, to make an out-of- algorithm, like the previous one, contains an IF statement. IF statements
sequence jump from one permit jumping around and skipping some instructions. GO TO and IF
statement to another. statements cause a program to branch- that is, to make an out-of-
sequence jump from one statement to another.
Each block in the flowchart has a characteristic shape. Start and end
blocks look like this :
and a decision block (logical block) which asks a question and has two
or more outputs looks like this:
The flow chart of plan for making school can be shown in figure 3.2
using symbols described just above.
13
Computer Programming
Start
Time avail to
get wash?
No
Yes
fig. 3.1.
14
Programming Tools
Time avail No
to breakfast?
Yes
Situation Yes
tense?
No
End
Fig 3.2
15
Computer Programming
3.3.1 Exercise
a) Ellipse
b) Circle
c) Rectangle
d) Cone.
a) Parallelogram
b) Rhombus
c) Line
d) Rectangle.
3. Which one is the decision block, that asks a question and has two
or move outputs looks like?
a) Rhombus
b) Circle
c) Point
d) Ellipse.
16
Programming Tools
Lesson 4 : FlowCharts-II
Start
Statement 2
Statement 3
Fig 4.1
17
Computer Programming
Start Start
Statement 1
Cond
checking
Statement 2
Statement 1
Yes
Cond? Statement 2
checkin
No
Statement 3 Statement 3
Suppose you wish to visit the botanical garden, and therefore, are
looking for one of your friends to accompany you. So you take out your
book of few phones and select a likely prospect. Dial the number, make
few talk, and finally invite the friend to visit. If he (or she) accepts the
offer, you have finished your work. If you are refused, then go back and
select another number. These actions are shown in a flow chart in Figure
4.4. The essential concept in this algorithm is the branch back to an
18
Programming Tools
Start
Dial a friend's
number
Yes
Yes
Busy?
No
End
Fig 4.4
0. Start.
19
Computer Programming
The algorithm reads the name and blood type of a student. If the blood
type is B-positive, then the name is printed; otherwise it loops back to
read the next record. This process continues until all the records have
been read.
Begin
No
B positive?
Yes
Print name
End
Fig 4.5
20
Programming Tools
0. Start.
3. Print NAME.
4. Go to step 1
5. End.
Fig 4.6
21
Computer Programming
Start Start
dialing
Dial a friend's
number Get phone book
Select a friend
Yes
Busy?
End
End dialling
Fig 4.7
22
Programming Tools
4.5 Exercise
a) not repeated
b) repeated several times
c) no use further
d) repeated only one time.
3. Which of the following symbol is used for modular flowchart?
a) Rectangle with two sides double lined
b) Parallelogram
c) Point
d) Quadruple.
1. What is a loop?
2. Show different types of looping in flowchart.
3. How short modules are represented in a flowchart?
4. What is the reason of modularization in a flowchart?
5. How can you remove the problem when a flowchart is more than
one page long?
23
Computer Programming
Lesson 5 : Pseudocodes
pseudocode
structure of pseudocode
use of pseudocode.
The sequence structure is single steps or actions that follow one another
without interruption. The series of actions does not depend on the
existence of any condition. The pseudocode for the sentence structure is:
Do action1
Do action2.
For example:
Read customer bill
Print customer bill.
24
Programming Tools
In C language In Pascal
if (expression) IF (condition 1 in true)
statement 1 Do X
else ELSE
statement 2 DO Y
For example : ENDIF
if (Income >Tk. 1,000) For example :
income_tax=4*Income; IF (Income >Tk. 10,000)
else income_tax=4*Income
income_tax=0; ELSE
Printf(“%f”, income_tax); income_tax=0
ENDIF
5.3.3 Iteration structure
The iteration structure, when certain actions are repeated over and over
while a specified condition occurs or until a condition occurs. The
pseudocode format for the iteration structure is :
:
do Statement
While (expression);
:
:
:
Here is an example of repetitive structure.
In C language In Pascal
include <Studio.h> Here is an example of repetitive
main() /*display the integers 0 through 9*/ structure.
{
int digit = 0; DO WHILE (End of file switch is off)
do Read each student rector
printf (“%d\n”,digit++) Add 1 to student Record counter.
DOWEND
while(digit<=9);
}
Example: Write a pseudocode for money market fund monthly statement in
Pascal
IF investor's balance is greater than or equal to Tk.500
Send monthly balance statement only
ELSE
IF account fund has had activity
Send monthly balance statement only
ELSE
Send monthly balance statement + warning notice
ENDIF
25
Computer Programming
5.5 Exercise
a) ENDFOR
b) ENDIF
c) ENDWHILE
d) DOWEND.
a) 2
b) 3
c) 4
d) 5.
26
Programming Tools
1. What is a pseudocode?
2. What are the characteristics of Pseudocodes?
3. What is a decision structure? Write the pseudocode format for a
decision structure.
4. What is the use of a pseudocode to programmers?
5. Describe how repetitive structures are represented in
pseudocodes.
27
Computer Programming
Header
1.
Condition 2. Condition
stub 3. entries
1.
Action 2. Action
statements 3. entries
Condition Stub: This is the upper left portion of table. Several conditions
are listed here. The conditions are stated in structured English. Some
notations like '<'(less than), ‘>’ (greater than) are valid to use in stating
conditions.
28
Programming Tools
Action statements : This is the lower left corner of the table. Several
actions written in pseudocode are listed in this portion with their serial
number.
Rule : The right portion of the table indicates the rules. Each column
Each rule satsfies one or more indicates one rule. Each rule satisfies one or more conditions and the
conditions and the entries for entries for that condition is written by 'Y'. The conditions which is not
that condition is written by 'Y'. satisfied is indicated by 'N' entry. The ignored conditions are denoted by
The conditions which is not '-', All these indicates condition entry that is upper right corner of the
satisfied is indicated by 'N' table.
entry. The ignored conditions
are denoted by. The lower right corner is for action entry. The rule may support one or
more action. The supported actions are denoted by 'X' entry and the
others are denoted by blank entries in the corresponding column of the
rule.
6.4 Example
Make a decision table for sending grade sheet to students. The decision
table is shown below :
1. marks 80% Y - - - -
2. marks < 40% - - Y - -
3. marks 40% - - - Y Y
4. Is the student N Y - - -
defaulter?
5. marks < 50% - - - Y N
1. Send marksheet X - - X X
2. Send distinction X - - - -
certificate
3. Defer result - X X - -
4. Send warning - - - X -
sheet
29
Computer Programming
6.6 Exercise
a) 1 or 2 words
b) 3 or 4 words
c) 5 or 6 words
d) 10 to 12 words.
a) lower left
b) bottom left
c) top right
d) bottom right portion of the decision table.
a) action entries
b) condition stub
c) header
d) condition entry.
a) X
b) ,
c) -
d) I.
30
Programming Tools
31
Computer Programming
structured diagram
different types of structured diagram and their construction method
use of the structured diagrams.
This is almost a tree with a tree root at the top. The whole problem is
Structured Chart not only broken into smaller modules. This chart not only shows the way how
shows the way how they are they are broken but also the way how the programme is controlled by
broken but also the way how parameter passing between higher and lower level modules. There are
the program is controlled by several rules to express all these. Now we will show the structured
parameter passing between diagram of result processing in fig 7.1 and then discuss certain rules of
higher and lower level structured chart.
modules.
Result processing is done for every student so the every operation will
iterate several times. The direction is denoted by directed arrows. The
rectangular box denotes modules. The diamond with submodule denotes
the conditional branch to another submodule.
32
Programming Tools
Result
The program works with the data. So construction of data helps to make
a programme. Warnier-Orr diagram is that type of diagram which gives
Warnier - Orr diagram gives structure of input, output file database or final report in a structured way
structure of input, output file
and which supports the tree structure. This is developed by Warnier and
database or final report in a
structured way and supports
Orr. Actually the data is divided into submodules in this diagram. The
the tree structure. root or main part of the system is written in the left portion and the
submodules are written in the right of left curly braces as shown in the
fig. 7.2.
33
Computer Programming
sub mod ule1
submod ule2
mod ule(root)
.
.
submod ulen
Fig 7.2
Heading
name
roll
GP
Classtest
result sheet of deptstudents(50)courses(10)
Theory
Attendence
GPA
CGPA
CGPA
stat of result(average)GPA
Attendence
Fig 7.3
The numbers in the parentheses denotes the repetition numbers. Here the
computer science department has 50 students. So 50 set of data of the
same size is required. There are 10 courses in each semester. Each course
grade is divided into three examinations. They are class tests, attendance
and theory examination. So courses are divided further.
34
Programming Tools
7.4 Exercise
a) Repetition symbol
b) Main structure
c) Tree structure
d) Looping.
a) Program flow
b) Output report
c) Arithmetic computation
d) Flow chart.
35
Computer Programming
a) Circle
b) Diamond
c) Rectangle
d) Curly braces.
36
Unit 3 : High Level Languages -I
Introduction
This unit provides some idea on high level languages. This unit is not for
any special language such as Pascal, C but for any kind of high level
language. First two lessons show some elementary data types used in
high level languages and next two lessons give idea of data structures.
This unit gives idea for developing not only programmes but also
algorithms. Some data structures are not readily available in high level
languages but can be easily constructed by elementary data structures.
They are queue, stack etc. They are very useful for algorithm
construction and understanding. You will find a brief introduction of
these topics in the last lesson of this unit. Records and arrays are
common compound data structures in all languages. These will be
discussed more elaborately.
Lesson 8 : Characteristics
8.1 Learning Objectives
On completion of this lesson you will learn :
37
Computer Programming
8.4.2 Naturalness
Much of the understand ability of an HLL comes from the ease with
FORTRAN is designed for which one can express an algorithm in that language. Some languages
numerical and mathematical are clearly more suitable than others in this regard. FORTRAN is
computations, SNOBOL for designed for numerical and mathematical computations, SNOBOL for
string manipulation, DBASE, string manipulation, DBASE, FOXPRO, Visual Basic, MS Access for
FOXPRO for database
applications.
database applications. A particular programme may be easy to develop in
a particular language and not in others.
38
High Level Languages -I
8.4.3 Portability
8.5 Exercise
a) PASCAL
b) C
c) Machine language
d) LISP.
39
Computer Programming
a) portability
b) efficiency of use
c) naturalness
d) low productivity of programmers.
a) compilation
b) portability
c) execution
d) booting.
40
High Level Languages -I
Data elements are single items (numbers, characters etc.) which can be
Data elements are single
used with single names on one to one basis. An HLL supports many
items (numbers, characters different data elements. There are four standard data elements - integer,
etc.) which can be used with real, character and Boolean. Some HLLs support user defined data
single names on one to one elements, which include enumerated types and subrange types. Pascal, C
basis. supports all of them. These are discussed below:
These include integers (whole numbers like 2, 3), real (numbers with
floating point like 1.0, 2.56), complex numbers (numbers with imaginary
part, like 2 + 3i ) etc. The following operations on numerical data are
defined :
9.4 Character
Most computers, and virtually Character type data are single characters enclosed in apostrophes like ‘a’,
all microcomputers, make use of
the ASCII (American Standard ‘B’, ‘$’ etc. Most computers, and virtually all microcomputers, make use
Code for Information of the ASCII (American Standard Code for Information Interchange)
Interchange) character set. character set in which 128 different characters are ordered.
41
Computer Programming
Boolean-type data are truth values which are either true or false.
Boolean-type expressions are formed by combining operands of the same
type with relational operators. The following are the most common
relational operators.
Boolean type data can be subjected to logical operations (and, or, not
etc.).
9.6 Pointers
These are data elements whose values address other data elements. The
syntax may vary, the general idea is that we may write statement P :=
Data elements whose values addr (X) to mean that P will now hold the address of X, or P will now
address other data elements. point to X and P’s value will be address of variable X. Pointers are useful
in allowing the programmer to create his own data structures, although
their indiscriminate use can make the programs hard to read and debug.
9.7 Labels
These are data whose values are the position in the program. For
Labels are data whose example, when we write go to X, we mean that we are transferring the
values are the position in the control of the program to the program location which is labeled or
program.
denoted by X. In the following example 100 is a label.
42
High Level Languages -I
Subrange type data are the data items that fall within any defined
Subrange type data are the subrange, thus forming a subset of contiguous, ordered data. For
data items that fall within example, the range of marks obtained in an examination is 0 to 100. The
any defined subrange.
type score range is defined by TYPE scorerange = 0 .. 100.
9.9 Exercise
a) 2
b) 3
c) 4
d) 5.
43
Computer Programming
a) enumerated data
b) integer
c) real
d) Boolean.
a) "2>3" integer
b) "2>3" character
c) "2>3" Boolean
d) "2>3" real data.
44
High Level Languages -I
10.3 Arrays
Consider the following one dimensional array, where each of its element
is an integer. Suppose the array is defined as
45
Computer Programming
SCORE (1 .. 8).
Student no.
1 2 3 4 5 6 7 8
60 72 48 39 50 91 62 55
In the definition, SCORE is the array name and so all the elements will
be referred to by this name. The range within the bracket is called the
subscript and determines the range of the location. The value of the
subscripted variable SCORE(7) is 62. Each element can be accessed in
this way. Now consider the following two dimensional array which is
defined as SCORE(1..5, 1..9).
1 2 3 4 5 6 7 8 9
In the definition, two subscripts define the row and column number of
the two dimensional array. In the subscripted variable, two subscripts
indicate row and column number. For example, SCORE(3,8) means the
element of 3rd row and 8th column.
These are really one dimensional array whose elements are characters.
They can be represented as a sequence of characters bounded by “or’’
character. For example, “abcdef” is a string.
46
High Level Languages -I
10.5 Exercise
47
Computer Programming
11.2 Records
record PERSON
NAME CHARACTER(15)
AGE INTEGER
11.3 Lists
48
High Level Languages -I
11.4 Stacks
A stack is a special type of list in which all insertions and deletions are
A stack is a special type of made at one end of the list, commonly called “top” of the list. This is
list in which all insertions very much like a stack of trays in the cafeteria; the new tray is put on top
and deletions are made at of the stack and the tray at the top is removed. For this reason, stacks are
one end of the list, commonly also referred to as last-in-first-out (or LIFO) lists. Adding an item to a
called “top” of the list. stack is called pushing it onto the stack, while deleting an item from
stack is called popping it off the stack.
11.5 Queues
Queue is a special list where all insertions are made at one end (back) of
the list and all deletions are made at another end (front) of the list. Unlike
Queue is a special list where a stack, which is a last-in-first -out list, a queue is a first-in-first-out (or
all insertions are made at FIFO) list, because the element which is inserted first in the queue is
one end (back) of the list and deleted first. This works in the same way as a line at an airline ticket
all deletions are made at counter. When new passengers arrive, they join the line at the end.
another end (front) of the People who arrived earlier, however, leave the line at the front as they
list.
get their tickets. Perhaps queues are more familiar, so there are no special
terms to describe adding items to queues and deleting items from queues.
Both stacks and queues are often used in real-life programming situation.
11.6 Exercise
49
Computer Programming
50
Unit 4: High Level Language - II
Introduction
This unit gives the information about the format of any high level
language. Different types of operators and their detailed characteristics
have been discussed. Evaluation of different operators are shown in
tabular form. In every compiler while evaluating arithmetic expression
their sequence of operation is very important. This is called the
precedence rule. This is described in lesson 13. Modular programming
requires procedure. High level language must have this scope. Parameter
passing is very important in this case. This is also described in this unit
briefly.
Lesson 12 : Operators
12.1 Learning Objectives
Arithmetic operators can be classified into two classes: unary and binary.
They take only one argument. Examples are Negation (as in -X) in which
it is called prefix operator (which precedes the operand) and Increment
Unary Operators where the operator may be prefix or postfix (which follows the operand).
For example, C language allows ++ as both a prefix and postfix unary
operator, when X and Y are integer variables, X = ++Y means the same
as
Y=Y+1
X=Y
X=Y
X=Y+1
51
Computer programming
They take two operands. Virtually all the binary operators are infix
(which is placed between two operands). Examples are addition (X+Y),
Binary Operators
subtraction (X-Y) multiplication (X*Y), division (X / Y).
A logical or Boolean A logical or Boolean operator has arguments with logical values, and the
operator has arguments with operator itself returns a logical value. The logical operators and, or, not,
logical values, and the and “exclusive or” are common in many programming languages. The
operator itself returns a operands are interpreted as logical value, true or false. Not is a unary
logical value. operator and the rule is that not true = false, not false = true. The other
logical operators are binary and operates in following way:
A B A and B A or B A exclusive or B
true true true true false
true false false true true
false true false true true
false false false false false
(A + B) and (X < Y)
The principal operations on strings that are common to many HLLs are
52
High Level Language - II
12.6 Exercise
a) 4,5
b) 4,6
c) 3,5
d) 6,6.
a) 5,6
b) 5,5
c) 6,6
d) 8,9.
53
Computer programming
i) (A*B) >= (B * Y)
ii) (A<B) XOR (B >Y)
iii) A/B >= X / Y
iv) (B /Y>= Y / Y) AND (A / X <X / B)
v) (A + B) > (X - Y) NOR (substr ("mostofa", "tof"))
54
High Level Language - II
13.2 Precedence
Consider the arithmetic expression A + B * C. It may be interpreted in
two ways :
Precedence First add A and B and then multiply the result with C,
(A + B) * C
First multiply B and C and then add the result with A,
A + (B * C).
Obviously, the two results may not be the same. We, therefore, need the
notion of precedence levels to indicate which operands are allowed to
group their operands first. Normally, * and / are given higher precedence
than + and -, meaning that ( A + B * C ) is grouped first by finding
operands to the left and right of *, then doing the same for +. That is, the
grouping A + (B * C) is correct. Different operators with same
precedence level are treated as if they were the same operator and they
are then evaluated by the associativity rule.
13.3 Associativity
When we combine operators to form expressions, the order in which the
operators are to be applied may not be obvious. For example, (A + B +
C) can be interpreted as ((A + B)+C) or as (A + (B + C)). That is, we
Associativity can go on addition from left to right or right to left of the expression. We
say that the operator + is left associative if the operands are grouped left
to right as in ((A + B) + C). We say that it is right associative if the
grouping is from right to left, as in (A + (B + C )).
Evaluation of expression with different operators on same precedence
level is solely restricted by the associativity. For example, consider the
expression ( 20 / 5 * 2 ). Here * and / have same precedence. If the
operators are left associative then the expression would be evaluated as
((20/5)*2) = 8 while if the operators are right associative then the
expression would be evaluated as ( 20/ (5*2)) = 2.
Every HLL describes some precedence level and associativity to its
operators.
55
Computer programming
13.4 Exercise
a) (B*C) + D/C
b) *C+D/C
c) (C+D)/C
d) ((D/B)*C)+B.
a) -8
b) -9
c) 5
d) 6.
56
High Level Language - II
Lesson 14 : Statements
14.1 Learning Objectives
57
Computer programming
In C In Pascal
a) i = 0; a) Counter : = 1;
b) i = i + 1; b) Counter : = Counter +1;
58
High Level Language - II
In Pascal
b) READ (Counter);
{This statement moves a number from screen to memory}
In C
a) Printf (..........................................);
{This statement moves a text from memory to the PC’s screen.}
59
Computer programming
14.5 Exercise
a) 5
b) 4
c) 2
d) 8.
a) I/O statements
b) Arithmetic statements
c) Declarative statements
d) Structural statements.
a) I/O
b) Structural
c) Sequence control statements
d) none of the above.
60
High Level Language - II
15.4 Parameters
At first, we need to make a distinction between the definition of a
procedure and its use. Suppose the sequence
61
Computer programming
15.4.1 Call-by-value
A := 10;
B := 12;
CALL CHANGE(A, B)
CALL PRINT (A, B)
15.4.2 Call-by-Reference
62
High Level Language - II
When parameters are passed by reference, the calling program passes the
memory locations ( not the values, as in pass-by-value) of the actual
The important thing to note is parameters to the subroutine. Many languages (like PASCAL) restrict
that, when passed by reference, that, the actual parameter must be a variable and must not be a constant
any change in the formal or expression. The important thing to note is that, when passed by
parameters within the reference, any change in the formal parameters within the subroutine will
subroutine will affect the value
of the actual parameters i.e. any affect the value of the actual parameters, i.e., any change in the formal
change in the formal parameters will be reflected outside the subroutine. Consider the same
parameters will be reflected procedure definition and program segment discussed in call-by-value
outside the subroutine. part. Suppose that the parameters are now passed by reference. Then the
program will work in this different way: A and B are initialized to 10 and
12 respectively. The procedure CHANGE is called with A and B as
actual parameters. Now X and Y will have the same memory location of
A and B respectively. So at the starting of CHANGE value of X and Y
will be 10 and 12 respectively. Within CHANGE the value of X and Y
are reset to 2 and 3 respectively. As the parameters are passed by
reference, the change in X and Y will not affect the actual parameters A
and B. So after returning from CHANGE, values of A and B will be 2
and 3 and PRINT will be print 2 and 3, not 10 and 12.
15.5.1 Exercise
1. Procedure decreases
a) programme size
b) programme execution time
c) compiling time
d) none of the above.
63
Computer programming
a) expression
b) operator
c) variable
d) array.
A = 2;
B = 5;
PROCEDURE swap (X,Y) INTEGER X,Y;
BEGIN
temp = X;
X = Y;
Y = temp;
a) 2,5
b) 5,5
c) 5,2
d) 2,2.
64
Unit 5 : Pascal Programming
Introduction
65
Computer Programming
These reserved words can be used only for their intended purpose, and
therefore, cannot be arbitrarily redefined by the programmer. It is
customary to display the reserved words within a Pascal program in
either boldface or upper-case letters.
16.4 Identifiers
Example :
66
Pascal Programming
16.6 Numbers
16.7 Integers
An integer contains neither a An integer contains neither a decimal point nor an exponent. Thus an
decimal point nor an integer is simply a sequence of digits, preceded (optionally) by a sign.
exponent. Thus an integer is The magnitude of an integer can range from zero to some maximum
simply a sequence of digits, value that varies from one computer (and one compiler) to another. A
preceded (optionally) by a
typical maximum value on a microcomputer is 32767, though some
sign.
computers allow integers that are much larger.
Example :
67
Computer Programming
Typically, the magnitude of a Real numbers have a much greater range than integer numbers.
real number might range Typically, the magnitude of a real number might range from a minimum
from a minimum value of value of approximately 1E-38 to a maximum of approximately 1E+38.
approximately 1E-38 to a (These values will vary from one computer (one compiler) to another.) In
maximum of approximately addition, the number 0.0 (zero, which is less than 1E-38) is also a valid
1E+38. real number.
Example :
68
Pascal Programming
16.10 String
Example :
69
Computer Programming
16.11 Exercise
a) 255
b) 128
c) 8
d) 64 characters.
a) twice
b) once
c) with a quote sign
d) surrounded by quote signs.
a) 0.0
b) 5000.0067
c) 1,00.08
d) -50.26e-18.
a) -5.021E-17
b) -.5021E-16
c) -5 0.21e-18
d) -5,00.021e-19.
70
Pascal Programming
a) 8e2.3
b) 0.021
c) -6.012E-22
d) 20.67895.
71
Computer Programming
These are single items (numbers, characters, etc.) that are associated with
single identifiers on a one-to-one basis. Actually there are several
different simple data types. These include the four standard data types :
(i) integer
(ii) real
(iii) char
(iv) Boolean.
(i) enumerated
(ii) subrange.
These data types consist of multiple data items that are related to one
another in some specified manner. Each group of data items is associated
These data types consist of
with a particular identifier. The individual data items within each group
multiple data items that are can also be associated with corresponding individual identifiers. There
related to one another in some are four types of structured data in Pascal :
specified manner.
(i) Arrays
(ii) Records
(iii) Files
(iv) Sets.
72
Pascal Programming
These types of data are used to construct dynamic structured data types.
17.3 Constants
The type of constant will implicitly be determined by the data item. The
general form of a constant definition is expressed as :
Example :
If we want to print out the actual string at a later point in the program, we
merely refer to the identifier title in the appropriate output statement.
73
Computer Programming
17.4 Variables
Example:
A Pascal program contains the integer variables row and column, the real
variable value, and the char variable flag. The program would, therefore,
contain the following declarations:
17.5 Expressions
74
Pascal Programming
Example :
(b*b-4*a*c)/(2*a)
The identifiers a,b and c and the numbers 4 and 2 are called operands;
and the symbols *, - and / are the corresponding operators (which
represent multiplication, subtraction and division, respectively). The
parentheses are used to specify the order in which the operations are
carried out. The entire expression represents a number. Thus, if a,b,c
represent the values 1,2,3 respectively, the expression will represent the
value -4.
This structure will cause the value of the variable employee number to be
written out if the value of pay is less than 1000.0.
75
Computer Programming
17.6 Exercise
a) 2
b) 3
c) 4
d) 5.
3. Pointer data types are used to
a) construct dynamic structured data types
b) records
c) files
d) static structured data types.
76
Pascal Programming
statements in a program
introduction to procedures and functions
Pascal Syntax diagram.
18.2 Statements
Example :
77
Computer Programming
which is used for assignment is ":=". Also note that the right hand side of
the statement is a numerical expression.
Note that the simple statements that comprise the compound statement
are enclosed within the keywords BEGIN and END. Also notice that the
simple statements are separated from one another by semicolons.
This statement will be executed 100 times. Each time the statement is
executed the current value of the variable count will be printed out or
displayed. Thus the statement will cause the values 1 2 3 4 ... 100 to
appear on the output device.
This statement causes the message "Group 1" to appear on the output
medium if the variable pay represents a value that is less than 1000.0. If
pay has a value that is greater than or equal to 1000.0, however, then the
message "Group 2" will appear instead.
Procedures and functions Procedures and functions are self-contained program elements,
are self-contained program sometimes referred to as modules, that carry out designated actions.
elements, sometimes referr- These modules can be accessed from anywhere within a program.
ed to as modules, that carry Moreover, if the same module is accessed from several different points,
out designated actions. the module can be given different information (i.e., different values for
the required data items) at each access point. When a module is accessed,
the information provided is processed by the action statements within the
module. Usually, this will cause new information to be generated. This
information is then returned to the point at which the module was last
accessed, and the program continues to execute from that point.
78
Pascal Programming
Example :
79
Computer Programming
Letter
Underscore
Digit
Letter
80
Pascal Programming
18.6 Exercise
a) 2
b) 3
c) 4
d) 5.
a) Compound statements
b) repetitive statements
c) conditional statements
d) assign a data item to a variable.
81
Computer Programming
82
Unit 6 : Data Types
Introduction
(i) Integer-type
(ii) Real-type
(iii) Char-type
(iv) Boolean-type.
This section will cover first two types and the next section will cover the
remaining two.
Integer type data are whole Integer type data are whole number (integer) quantities. Included within
number (integer) quantities. this category are integer-type constants, variables, functions and
expressions.
83
Computer Programming
Collectively, the operators that Collectively, the operators that are used to carry out numerical-type
are used to carry out numerical- operations are called arithmetic operators. There are six arithmetic
type operations are called operators that can be used with integer-type operands. Five of these will
arithmetic operators. produce an integer-type resultant, the sixth will produce a quantity of
type real, these operators are summarized below:
Example :
Suppose that a and b are integer-type variables that have been assigned
values 13 and 5, respectively. Several simple integer expressions and
their resulting values are shown below.
Expression Value
a+b 18
a -b 8
a*b 65
a/b 2.6
a DIV b 2
a MOD b 3
1. The resultant of the two integer operands will be positive if both are
positive otherwise it may be negative.
2. The two division operators(/ and DIV) and the MOD operator
require that the second operand be non-zero.
3. Use of the DIV operator with a negative operand will result in
truncation toward zero i.e., the resultant will be smaller in magnitude
than the true quotient.
84
Data Types
Example :
Suppose that i and j are integer-type variables whose assigned values are
11 and -3, respectively. Several integer expressions and their results are
given below:
Expression Value
i+j 8
i-j 14
i*j -33
i DIV j -3
i MOD j 2( nonstandard)
i/j -3.66666666667
If i had been assigned a value of -11 and j had been assigned 3, then we
would have
Expression Value
i DIV j -3
i MOD j -2
i/j -3.666667
Expression Value
i DIV j 3
i MOD j -2(nonstandard)
i/j 3.6666666667
85
Computer Programming
Example : Suppose you are adding two numbers i and j and the values
of them are as follows:
i = 0100000000000000
j = 0100000000000001
The summation (i+j) will have a result
i + j = 1000000000000001
Real-type data refers to data Real-type data refers to data items that represent real numerical
items that represent real quantities. This includes real-type constants, variables, functions and
numerical quantities. expressions.
There are four arithmetic operators that can be used with real-type
operands. They are
Example :
Suppose that p and q are real-type variables whose assigned values are
12.5 and 0.5, respectively. Several simple real expressions, and their
resulting values are shown below.
Expression Value
p+q 13.0
p-q 12.0
p*q 6.25
p/q 25.0
19.4.2 Common rules
86
Common rules
Data Types
1. The resultant will be positive if both operands are of the same sign.
Otherwise the resultant will be negative.
2. The division operator requires that the second operand be non-zero.
3. If one operand is of type integer and the other is of type real, then the
resultant will always be of type real.
Example : Let c and d be real variables whose assigned values are -0.66
and 4.50. Several real expressions and their corresponding values are
given below :
Expression Value
c+d 3.84
c-d 5.16
c*d -2.97
c/d -0.14666667
The range of real numbers on most computers is much larger than the
range of integers. For most purposes, you can pretend that real numbers
have no limit, although in Turbo Pascal, the actual range is
approximately plus or minus 10-38 to 10+38, equivalent to a 1 followed or
preceded by 38 zeros.
87
Computer Programming
19.5 Exercise
a) arbitrary number
b) non zero
c) negative
d) non negative.
a) integer
b) unknown
c) logical
d) real.
a) 10-64 to 10+64
b) 10-32 to 10+32
c) 10-38 to 10+38
d) 10-16 to 10+16.
6. 0.0123 is displayed as
a) 12.3E-03
b) 1.23E-03
c) 12.3E-04
d) 0.123E-08.
88
Data Types
89
Computer Programming
90
Data Types
91
Computer Programming
Example
Here are some simple Boolean expressions involving numerical
operands (within each expression, assume that both operands are of the
same type.)
Expression Value
2=3 false
2<3 true
0.6 >= 1.5 false
0.6 >= 0.5 true
-4 <> 4 true
1.7 <= -2.2 false
92
Data Types
Example : Suppose that i and j are integer-type variables that have been
assigned the values of 3 and -5, respectively. Several Boolean
expressions involving the use of these variables are shown below :
Expression Value
i <= 10 true
i+j > 0 false
(i-j) < (i+j) false
i-3 = j+5 true
2i >= i DIV 2 true
(i DIV 2) > (j+6) false
Example : Suppose that ch1 and ch2 are char-type variables that have
been assigned the characters ’P’ and ’T’, respectively. Several Boolean
expressions involving the use of these variables are shown below.
Expression Value
ch1 = ch2 false
ch2 = ‘T’ true
ch1 = ‘p’ false
ch1 < ch2 true ( because P precedes T)
ch2 > ‘A’ true ( because T succeeds A)
'W’ <> ch1 true
Operator Meaning
OR Expression will be true if either operand is true (or if
both operands are true).
AND Expression will be true only if both operands are true.
NOT negate a Boolean operand.
93
Computer Programming
Expression Value
(n > 0) AND (n < 20) true
(n > 0) AND (n < 5) false
(n > 0) OR (n <5) true
(n < 0) OR (n > 20) false
(n =10) AND (s = ‘A’) true
(n <> 5) OR (s >=‘A’) true
Example : Suppose that the Boolean expression j > 6 is true. Then the
expression
NOT (j > 6)
NOT ( j <= 6)
will be false. Also, the expression ch='A' will be false, so that the
expression
NOT (ch='A' )
will be true.
94
Data Types
20.6 Exercise
1. Which type of operator can not be used for character type data?
a) arithmetic
b) relational
c) logical
d) none of the above.
a) 1 bit
b) 2 bits
c) 8 bits
d) 16 bits.
a) 5
b) 2
c) 8
d) 7.
95
Computer Programming
Figure 22.1 shows the block diagram for a constant declaration, which
comes between the program declaration and body, but before any
variable declaration part. Each constant has a descriptive name and an
associated constant value.
Programming Example :
1. PROGRAM Constants;
2. CONST
3. Name = ‘Anne’;
4. Weight = 118;
5. Savings = 375;
6. BEGIN
7. Writeln(‘Name :’, Name);
8. Writeln(‘Weight :’,Weight,‘pounds’);
9. Writeln(Name, ‘has Tk’. ,Savings, ‘in savings’);
The constant declaration part of the Program begins with key word
Each constant has an CONST, followed by a list of constants separated by semicolons. Each
identifier, an equal sign, a
constant has an identifier, an equality sign, a value and a semicolon. The
value and a semicolon.
value itself determines the type of constant. For example, line 3 declares
a string constant, Name, while line 4 and 5 declare two integer, or whole
number, constants, Weight and Savings.
96
Data Types
Pascal also contains a number of standard functions that are used with
various simple data types. (Standard functions are also referred to as
intrinsic or built-in functions.) Some of these functions accept one type
of parameter and return a value of the same type, while others accept
parameters of one type and return a value of a different type. Information
on several of these functions are summarized below.
97
Computer Programming
value of x.
arctan(x) Compute the arctangent Integer or real Real
of x.
chr(x) Determine the character Integer Char
represented by x.
cos(x) Compute the cosine Integer or real Real
of x. (x in radians).
exp(x) Compute ex, where Integer or real Real
e = 2.7182818...is the
base of the natural system
of logarithm
ln(x) Compute the natural Integer or real Real
logarithm of x ( x>0).
odd(x) Determine if x is odd or Integer Boolean
even. (Return a value of
true if x is odd, false
otherwise).
ord(x) Determine the (decimal) Char Integer
integer that is used to
encode the character x.
pred(x) Determine the Integer, char or Same as x.
predecessor of x. boolean
round(x) Round the value of x to Real Integer
the nearest integer.
sin(x) Compute the sinc of x. (x Integer or real Real
in radians).
sqr(x) Compute the square of x Integer or real same as x
sqrt(x) Compute the square root Integer or real Real
of x (x>=0)
succ(x) Determine the successor Integer, char or same as x
to x. real
trunc(x) Truncate x (i.e., drop Real integer
the decimal part of x).
abs(0.003) 0.003
abs(-0.003) 0.003
98
Data Types
abs(diff) 5
Example : The functions chr and ord are used to determine the
relationship between any Pascal character and its corresponding integer
code. Thus if computer uses ASCII code then:-
chr(65) ‘A’
chr(112) ‘p’
chr(53) ‘5’
ord(’A’) 65
ord(’p’) 112
ord(‘5’) 53
ord(‘A’) = ord(chr(65)) = 65
and
Example : The functions round and trunc can accept both positive and
negative real-type numbers. Negative numbers are treated as though they
were positive numbers, with the minus sign added after the rounding or
truncation has been carried out. Thus
Function Value
round(2.3) 2
99
Computer Programming
round(3.7) 4
round(-1.8) -2
round(-6.1) -6
Function Value
trunc(2.3) 2
trunc(3.7) 3
trunc(-1.8) -1
trunc(-6.1) -6
Precedence Operators
1(highest) NOT
2 * / DIV MOD AND
3 + - OR
4(lowest) = <> < <= > >= IN
Within a given precedence group the operations are carried out as they
are encountered, reading from left to right.
Notice that the division is carried out first, since this operation falls
within a higher precedence group than subtraction. The resulting quotient
is then multiplied by 4 (left-to-right rule within a precedence group).
Finally, this product is subtracted from the value of the first variable.
100
Data Types
If the variables a, b and c have been assigned the values 8,15, and -4,
respectively, then the given expression would be evaluated as
101
Computer Programming
21.9 Exercise
a) -1/6
b) -2/3
c) -1/3
d) none of the above.
a) -5
b) -4
c) 5
d) 4.
3. Indicate the value of the expression:-chr(ord(succ(chr(ord(pred
(’B’))+5)))-6)
a) A
b) B
c) C
d) D.
102
Data Types
3. What is the purpose of the chr and ord functions? With what types
of parameters are they used? What type of resultant is obtained in
each case?
4. What is the purpose of the pred and succ functions? With what
types of parameters are they used? What type of resultant is
obtained in each case?
5. When using the ASCII character set, what relationships exist
between the chr and ord functions and pred and succ functions?
Why are these relationships not valid for all character sets?
6. What is the purpose of the round and trunc functions? With what
types of parameters are they used ? Give example of each function.
7. How are negative parameters treated by the round and trunc
functions?
8. In what order are the operations within a precedence group carried
out?
9. How can the natural operator precedence be altered?
10. In what order are the operations carried out within an expression
that contains nested parentheses?
103
Computer Programming
methods for reading data into the computer and writing data out of
the computer
special input/output statements that are included within Pascal
format of I/O instructions
writing a variety of complete, though simple, Pascal programs.
The input data items must be placed in a separate file, called the input
file, before the corresponding program is actually run. This file is most
often created via a text editor. However, it may also be entered into the
The input data items must be computer via punch cards, using a keypunch machine and a card reader.
placed in a separate file, In either case data items will be sorted sequentially, in the same order
called the input file, before that they were entered. These individual data items will be grouped into
the corresponding program logical lines, where each line corresponds to one line of typed data or one
is actually run. This file is punch card.
most often created via a text
editor. Output data are transferred from the computer’s memory to an output
file, which is similar but opposite to the input file. Again the data items
are stored sequentially, in the same order that they were written. The data
items will again be grouped into logical lines, which will correspond to
physical lines of output when the data are printed or displayed.
It should be understood that the input data file and the output data file are
stored within the computer as separate entities; they are not a part of a
Pascal program. These files are associated with a Pascal program,
however, by naming them as parameters within the program header.
The header specifies that the name of the program is payroll and that the
program utilizes both input and output files. A program need not utilize
both an input and an output file, though most programs do so, since most
programs require input data and generate output data when they are
executed.
104
Data Types
PROGRAM primes(output);
Notice that this program utilizes only an output file, since it does not
require any input data. If the program were modified, however, so that it
would generate the first n prime numbers, where n is an input quantity,
then the program header would have to be changed to
PROGRAM primes(input,output);
Such a modification would be a good idea, since the program would then
be much more general.
Finally, remember that there are some interactive versions of Pascal that
allow input/output operations to be carried out directly during program
execution. Input and output files are not required in such situations. This
is particularly common with microcomputers.
The read statement is used to read data items from the input file and
assign them to integer, real or char-type variables. The statement is
written as
where the input variables are separated by commas. (Note that Boolean-
type variables cannot be included in the list of input variables. )
read (a, b, c) ;
This statement causes three data items to be read from the input file and
The data items are read from assigned to the variables a, b, and c, respectively. The data items are read
the input file and assigned to
their respective variables in the
from the input file and assigned to their respective variables in the same
same order that they are stored. order that they are stored. Each variable must be of the same type as its
Each variable must be of the corresponding data item.
same type as its corresponding
data item.
Exception : An integer number can be assigned to a real-type variable.
Each data item can be read only once.
105
Computer Programming
VAR a, b : real;
i, j : integer;
p, q : char;
.
.
.
.
read ( a, b, i, j, p, q);
The read statement will cause two real numbers, two integer numbers
and two single characters to be read from the input file and assigned to
the variables a, b, i, j, p and q, respectively.
Some care should be given to the spacing of the input data items.
Numerical data items must be separated from one another by blank
spaces or by end-of-line designations. To be more precise, a numerical
Numerical data items must
data item may be preceded by one or more blank spaces or end-of-line
be separated from one
another by blank spaces or
designations. Real numbers can be written with or without an exponent.
by end-of-line designations. Moreover, real numbers that represent integral quantities (e.g., 1, 0 ) can
be written as integers(i.e., 1). Any number may be preceded by a plus or
a minus sign provided there is no space between the sign and the number.
Example: Consider once again the portion of the Pascal program shown
in the last example, i.e.,
VAR. a, b : real ;
i, j : integer;
p, q : char;
.
.
.
read(a, b, i,j,p,q );
Variable Value
a 12500
106
Data Types
b -14.8
i 5
j -9
p X
q Y
The data items might be entered into the input file as follows.
read ( a, b, i);
read ( j, p,q);
The input file need not be changed, since the first read statement would
read the first three values on the line, and the second read statement
would read the last three values.
The readln statement, like the read statement, is used to read data items
from the input file and assign them to integer, real or char-type variables.
This statement is written in the form
readln(input variables);
The difference between the two statements is that the readln statement
causes the next (not the current) read or readln statement to begin by
The difference between the two reading a new line of data, whereas the read statement will allow the next
statements is that the readln read or readln statement to begin on the same line.
statement causes the next (not
the current ) read or readln
statement to begin by reading a
new line of data, whereas the
read statement will allow the
next read or readln statement to
begin on the same line.
107
Computer Programming
Suppose that the input file contained the following eight numbers,
arranged in two lines.
1 2 3 4
5 6 7 8
then the variables p1 and p2 would still be assigned the values 1 and 2,
but p3 and p4 would be assigned the values 5 and 6 (from the second line
of input data). Note that it is the first readln statement that causes the
values from p3 and p4 to be read from the second line of input.
read(p1, p2);
readln(p3, p4);
The variables p1, p2, p3 and p4 would be assigned the values 1, 2, 3 and
4, respectively, since the readln statement would begin by reading the
third value in the first line of data. However, the next read or readln
statement would begin by reading the 5 from the second line of the input
data. The readln statement is convenient for reading data on a line-by-
line basis, as is common in batch processing.
108
Data Types
Suppose that the variables are all of type integer, and the input file
contains the numbers
1 2 3
4 5 6
7 8 9
Then the values 4 and 5 will be assigned to the variables c and d ; the
values 7 and 8 will be assigned to e and f. It is not clear what values
will be assigned to a and b, since it is not known where the first readln
statement will begin. If the statement begins at the start of the line, then
the values 1 and 2 will be assigned to a and b. On the other hand, if this
statement is preceded by a read statement, e.g.,
read(x);
then x will be assigned the value 1, and a and b will be assigned the
values 2 and 3 respectively.
The write statement is used to write data items to the output file. This
statement is written as
write (output data items);
The output data items can be strings, numerical constants or the values of
The output data items can be variables or expressions. They may be of type integer, real, char-type or
strings, numerical constants or Boolean-type. (Each string must be enclosed within apostrophes). The
the values of variables or data items must be separated by commas if there are more than one.
expressions.
Example : Here is a typical write statement.
109
Computer Programming
The standard field widths can easily be altered, thus allowing the
programmer greater control over the appearance of the output items.
When string and char-type data items are written out the field width will
be exactly equal to the number of characters in the data item. Hence there
When string and char-type data
items are written out the field will be no leading or trailing blank spaces, unless they are included as a
width will be exactly equal to part of the actual data.
the number of characters in the
data item. Example: A Pascal program contains the following write statement.
Notice that the blank spaces separating the individual words are included
within the last two strings. If the write statement had not included these
blank i.e., if we had written
110
Data Types
REDWHITEBLUE
VAR a, b : real;
i, j : integer;
p, q : char;
.
.
.
write (‘a =’, a, ‘b =’, b, ‘i =’, i);
write (‘j =’, j, ‘p =’, p, ‘q =’, q);
Suppose that the variables have been assigned the following values.
Variable Value
a 12500.0
b -14.8
i 5
j -9
p X
q Y
a = 1.250000000E+04 b = -1.4800000E+01 I = 5 j = -9 p = X q = Y
The writeln statement is identical to the write statement, except that the
writeln statement results in an end-of-line designation being written after
The writeln statement is the last data item. Therefore, any subsequent write or writeln statement
identical to the write statement, will begin a new line of output. The statement is written as
except that the writeln statement
results in an end-of-line
designation being written after writeln (output data items);
the last data item.
where the output data items can be strings, numerical constants or the
values of variables or expressions of type integer, real, char or Boolean.
111
Computer Programming
Example : Suppose that the write statements in the last example are
replaced with writeln statements i.e.,
VAR a, b : real;
i, j : integer;
p, q : char;
.
.
.
writeln (‘a =’, a, ‘b =’, b, ‘i =’, i);
writeln (‘j =’, j, ‘p =’, p, ‘q =’, q);
Notice that it is the first writeln statement that causes the original single
line of output to be broken up into two lines. Then second writeln
statement has no effect on this output, though any subsequent output
would begin on a new line. Therefore, the statements
would produce the same two lines of output shown above, but the
statements
112
Data Types
line one
line two
22.8 Exercise
a) 6
b) 8
c) 7
d) 14.
1. What is an input and output file? How are data items entered into
the input file?
2. How are the data items arranged within an input or an output
file?
3. In what sense must the data items in the input file correspond to
the variables in the read statement?
113
Computer Programming
1. What are the purposes of read and readln statement? How does
readln statement differ from the read statement? Describe with
suitable examples.
2. a) How does writeln statement differ from write statement?
b) What happens when writeln statement is preceded by a write
statement or writeln statement? Illustrate with example.
c) Why might an empty writeln statement be included in a Pascal
program? Describe with example.
114
Unit 7 : Control Structures
Introduction
This unit gives you knowledge about the structure of Pascal program.
These structural tools are basic structures of Pascal. Some of the
structures are very essential and the others are useful for obtaining more
efficiency. In first two lessons of this unit conditional structures IF and
CASE have been explained. This structures are useful while controlling
the flow of execution of programming depending on different situations.
Next two lessons describe the repetitive structures. This type of structure
is used when the same operation is allowed to do upon the same type of
data. Three structure have been explained FOR, WHILE - DO and
REPEAT - UNTIL. Specially in database applications this type of
statements are often used. With all these statements a new but easy
concept is introduced.
Statement 1
Statement 2
Statement 3
Statement 4
115
Computer Programming
us to ask a question and then do one thing if the answer is yes( true )and
another if the answer is no ( false ).
Decision
True False
Statement Statement
1A 1B
116
Control Structures
Example:
117
Computer Programming
Compound
Repetitive
Conditional.
BEGIN
read(radius);
area := 3.1415*sqr(radius);
write(radius,area);
END
Note that the simple statements that comprise the compound statement
are enclosed within the keywords BEGIN and END. Also, notice that the
simple statements are separated from one another by semicolons.
Note that the simple statements
that comprise the compound Example :
statement are enclosed within
the keywords BEGIN and END.
Here is a typical repetitive statement.
BEGIN
sum :=0;
FOR count:=1 TO n DO
BEGIN
read (x);
sum := sum +x
END;
write(‘sum =’, sum);
END
118
Control Structures
23.4 Exercise
a) True
b) False
c) 5
d) 2.
119
Computer Programming
conditional structure IF
conditional structure IF - THEN - ELSE
conditional jumping by CASE statement and its use
use of nesting these structures.
120
Control Structures
In the first example the value of tax is determined in one of the two
possible ways, depending on the value that is assigned to the char-type
variable status. The second example looks for certain “tagged” accounts.
If an account is tagged (i.e. if an ‘*’ is assigned to the char-type variable
tag), then the account number is written out and the credit limit is set to
zero; otherwise the credit limit is set at 1000.
The third example shows an area can be calculated for either of the two
different geometrical figures. If the Boolean type variable circle is true,
then the radius of the circle is read into the computer, the area is
calculated and then written out. If circle is false, then the length and
width of a rectangle are read into the computer, the area is calculated and
then written out.
Notice once again that there are no semicolons in the IF-THEN-ELSE
structure, except as separators in the compound statements. IF structure
can be nested within one another. Some of the forms that nested IF
IF structure can be nested
within one another.
121
Computer Programming
structures can take on are shown below. The most general form of two-
layer nesting is
where be1, be2, be3 represent Boolean expressions, and s1, s2, s3 and s4
represent statements. In this situation, one complete IF-THEN-ELSE
structure will be executed if be1 is true and another will be executed if
be1 is false. It is of course possible that s1, s2, s3 and s4 will contain
other IF-THEN-ELSE structures. We would then have multilayer
nesting.
IF be1 THEN s1
ELSE IF be2 THEN s2 ELSE s3
IF be1 THEN IF be2 THEN s1 ELSE s2
ELSE s3
IF be1 THEN IF be2 THEN s1 ELSE s2
In each of the first two cases, the subordinate nature of the inner IF-
THEN-ELSE structure is indicated by the line on which it is written. In
the last case, however, it is not clear which Boolean expression is
associated with the ELSE clause. The answer is be2 because this is the
associated with closest IF structure. Thus, this last example is equivalent
to
IF be1 THEN
BEGIN IF be2 THEN s1 ELSE s2 END
If we want to associate the ELSE clause with be1 rather than be2, we
could write
122
Control Structures
Each of the case labels represents one of the permissible values of the
expression. Thus, if the expression is of type integer, the case labels
would represent integer values that fall within the permissible range. The
case labels need not appear in any particular order, though each of the
case labels must be unique. Moreover, each label can appear in only one
list. (Note: These labels are referred to as case labels to distinguish them
from a different type of label, which will discuss in the next section.)
CASE choice OF
‘R’ : writeln(‘RED’);
123
Computer Programming
‘W’ : writeln(‘WHITE’);
‘B’ : writeln(‘BLUE’);
END;
Thus, RED will be written out if choice is assigned the value R, WHITE
will appear if W is assigned to choice and BLUE will be written out if B
is assigned to choice. No output will be generated if choice is assigned
some character other than R, W or B.
124
Control Structures
24.4 Exercise
a) unlimited
b) limited upto maximum allowed code size
c) limited upto Hard disk memory
d) none of the above.
3. CASE structure is a
a) conditional control structures
b) unconditional control structures
c) simple expression
d) none of the above.
125
Computer Programming
The statement part of the The statement part of the structure can be either simple or structured,
structure can be either though it is typically a compound statement that may include other
simple or structured, though control structures. This statement will be executed for each of the several
it is typically a compound consecutive values assigned to the control variable. The number of
statement that may include values assigned to the control variable therefore determines the number
other control structures. of times the statement will be executed.
To illustrate the use of the FOR structure, let us again consider the
problem of writing out the first 20 positive integers, with one integer on
each line. We require only a single FOR-TO statement to carry out this
task. In particular, we can write
126
Control Structures
executed 20 times. During each pass, the current value of digit will be
written out on a separate line, as required. Similarly, the problem of
determining the sum of the first n integer quantities can be expressed as
sum : = 0;
FOR digit : = 1 TO n DO sum : = sum + digit;
There are a few rules that must be adhered to when writing a FOR
statement. Specifically, the values of value1 and value2 can be expressed
as constants, variables or expressions. However, these values must be of
the same data type as the control variable. Also, the value of value1 must
be less than value2 if the statement is to be executed more than once. (If
value1 and value2 are equal the statement will be executed once only; if
value1 is greater than value2, the statement will not be executed at all.)
Example: The use of the FOR structure is really less complicated than it
first appears, as illustrated by the following examples.
(a) sum : = 0;
FOR count : = 1 TO n DO
BEGIN readln (x); sum := sum + x END;
writeln (‘sum =’, sum);
(b) sum : = 0;
FOR count : = n TO (3*n+1) DO
BEGIN
readln(x);
sum : = sum +x
END;
writeln(‘sum =’, sum);
127
Computer Programming
The second form of the FOR structure is similar to the first form, except
for the use of the key word DOWNTO in place of TO. Thus, the FOR
structure can be written as
The action taken by this form of the FOR structure is similar to the first
form, except that the control variable is evaluated backward rather than
forward. Thus, if the control variable is an integer-type variable it will
automatically decrease by 1, from value1 to value2, during successive
passes through the loop. Therefore, value1 should be greater than value2.
(if the values are equal, then the statement will be executed once only;
and if value1 is less than value2, then the statement will not be executed
at all).
This example will cause 13 lines of text to be printed. Each line will
contain the current value of the integer variable i, followed by the
corresponding value of the formula z = 2i +5. Notice that the successive
values of i will decrease, from i =0 on the first line to i = -12.
It should be understood that value1 and value2 are evaluated only once,
before the first pass through the loop. Therefore, the reader should not
attempt to change either of these values within the loop. Also, the reader
is cautioned not to use the control variable after the FOR structure has
terminated, since it will normally be undefined.
Averaging a list of Numbers: Let us use the FOR structure to obtain the
average of a list of n numbers. Our strategy will be based upon the use of
a partial sum that is initially set equal to zero and is then updated as each
new number is read into the computer. Thus, the very problem naturally
lends itself to the use of repetition. The actual calculations can be carried
out in the following manner.
128
Control Structures
129
Computer Programming
25.6 Exercise
a) Real
b) Character
c) Boolean
d) User defined variable.
a) string
b) logical operator
c) relational operator
d) expression.
a) condition checking
b) repetitive statement
c) input statement
d) parameter passing.
BEGIN
130
Control Structures
.
.
.
FOR c:= b TO d DO
BEGIN
.
.
.
END
END;
131
Computer Programming
digit : = 1;
WHILE digit <= 20 DO
BEGIN
writeln(digit);
digit : = digit +1
END;
132
Control Structures
or, equivalently,
sum : = 0;
digit : = 1;
WHILE digit < n + 1 DO
BEGIN
sum : = sum + digit;
digit : = digit + 1
END;
133
Computer Programming
Also, note that the loop will not be executed at all if n is assigned a value
that is less than 1. Physically, of course, it would not make any sense to
do this. Finally, notice that the innermost compound statement is
intended within the WHILE-DO structure. This causes the physical
extent of the WHILE-DO structure to be readily identifiable.
134
Control Structures
digit : = 1;
REPEAT
writeln(digit);
digit : = digit + 1
UNTIL digit > 20;
We again begin with a value of digit =1, and then proceed to write out
the current value of digit, increase its value by 1 and then repeat the
cycle. The process is continued UNTIL the current value of digit (which
was just increased in value) exceeds 20. The net effect of this REPEAT-
UNTIL structure will be the same as the corresponding WHILE-DO
structure presented in the last section. Thus, 20 successive lines of output
will be generated, with each line showing a successive integer value.
sum : = 0;
digit : = 1;
REPEAT
sum : = sum + digit;
digit : = digit + 1
UNTIL digit > n;
135
Computer Programming
count > n
136
Control Structures
26.6 Exercise
a) conditional
b) arithmetic
c) logical
d) a and c.
2. I=8
WHILE I<15 DO
BEGIN
I=I+2;
END
How many times the loop will be executed
a) 15
b) 18
c) 10
d) 4.
a) WHILE - DO
b) RPEAT- UNTIL
c) IF -THEN-ELSE
d) None of the above.
137
Computer Programming
138
Unit 8 : Procedures and Functions
Introduction
139
Computer Programming
PROGRAM findmax;
VAR a,b,c : INTEGER;
PROCEDURE maximum;
VAR max:INTEGER;
BEGIN
IF a>b THEN max : = a
ELSE max : = b;
IF c>max THEN max : = c;
writeln('The maximum number is :', max)
END;
140
Procedures and Functions
The scope of an identifier refers to the region within which the identifier
The scope of an identifier refers is declared and can be utilized. The constants and variables that appear
to the region within which the
identifier is declared and can be
within the action statements of a procedure may have been declared
utilized. externally, within a program block that contains the procedure
declaration, or locally, within the procedure itself. In this respect there
are two types of these:
The constants and variables that are declared within a block containing
the procedure declaration are called global identifiers and can be utilized
anywhere within that block, whether inside of or external to the
procedure. On the other hand , the constants and variables defined inside
a procedure are called local identifiers. They cannot be utilized
externally.
On the other hand, many programs require that certain data items be
recognized both within and outside of a procedure. There are two ways
to transfer such information across procedure boundaries :
141
Computer Programming
27.6 Exercise
a) constants
b) global variables
c) arguments
d) none of the above.
142
Procedures and Functions
PROGRAM sample;
VAR a,b,c,d : real;
PROCEDURE flash(x, y : real);
BEGIN
.
.
(*process the values of x and y*)
.
.
END;
BEGIN (*main action block*)
.
143
Computer Programming
.
flash(a,b);
.
.
flash(c,d);
.
.
END.
The first procedure reference causes the values of the actual parameters a
and b to be transferred to the formal parameters x and y. Thus, the values
of a and b are passed to procedure flash, where they are then processed.
This process is then repeated in the second procedure statement, this time
transferring the values of c and d to x and y. The values of c and d are
thus passed to flash, where they are processed accordingly. Notice that
we have processed two different data sets simply by accessing the same
procedure twice, with a different set of actual parameters each time.
Each actual parameter must 2. Each actual parameter must be of the same type as its corresponding
be of the same type as its formal parameter.
corresponding formal
parameter. 3. Each actual parameter must be expressed in a manner which is
consistent with its corresponding formal parameter, as determined by
the class of the formal parameter (the class of formal parameter is
described below).
PROGRAM sample;
144
Procedures and Functions
Note that each procedure reference includes two actual parameters, since
two formal parameters(x and y) are defined within the procedure.
Moreover, x is declared as an integer-type variable, and y is a real-type
variable. Thus, each procedure reference must include one integer
variable and one real variable, in that order.
145
Computer Programming
Value parameters are very simple to use. They are declared by simply
including their names and corresponding data types within the procedure
header, without any prefix (such as VAR). Absence of such a prefix
automatically identifies this class of parameters.
Since in this case, the values of the actual parameters are transferred
rather than the parameters themselves, an actual parameter may be
expressed as a constant, a variable or an expression (provided the value
of the parameter is of the proper data type).
PROGRAM sample;
VAR a,b : integer;
c,d : real;
146
Procedures and Functions
flash(2*(a+b),-0.5);
.
.
.
END.
The main block includes two different procedure reference (i.e., two
different references to flash). Each procedure reference contains two
actual parameters, the first of which is of type integer and the second
real, as required. Notice that two of these parameters are written as
constants and two are written as expressions. Thus the first procedure
reference transfers the value 3 to x, and the value of the real expression
a*(c+d)/b to y. Similarly, the second procedure reference transfers the
value of the integer expression 2*(a+b) to x and the value -0.5 to y.
At the end of program x=20 and y=10. When variable parameter is used
the address of the parameter is referenced not the value of the parameter.
So after complete execution of procedure the formal parameters passes
147
Computer Programming
their values to the main program such that actual parameters possess the
value of formal parameters. Thus information is passed from procedure
to main program.
28.6 Exercise
a) Expression
b) Procedure
c) Variable
d) Constants.
148
Procedures and Functions
149
Computer Programming
The last item, type, specifies the data type of the result that is returned by
the function. Generally, the formal parameters will be value parameters
rather than variable parameters. This allows the corresponding actual
parameters to be expressed as constants, variables or expressions.
The block is similar to that of a procedure and involves the same rules of
scope as a procedure. Within the block, the identifier that represents the
function name must be assigned a value of the appropriate type (as
specified in the header). This is the value that the function returns to its
reference point. Values can be assigned to the function name at two or
more points within the block. Once an assignment is made, it cannot
subsequently be altered.
Example: Observe the following function named factorial that
calculates the factorial of a positive integer quantity.
150
Procedures and Functions
The first line, which contains the keyword FUNCTION, is the function
header. Here, the header includes a declaration of the value parameter n.
Also, the last item on the line(INTEGER), which states that the function
will return an integer-type quantity.
This function accepts a value for n and then calculates the value of n!
using two local integer variables, factor and product. The final result is
assigned to the identifier factorial, which is also a function name.
Notice that there are two different assignments to factorial, but only one
of these assignments is utilized when the function is executed. The
choice depends upon the value that is assigned to n. Once factorial is
assigned a value, it is not altered within the function.
On the surface this version appears more appealing than the original,
since it is simpler. But, This version is not valid because the value of
factorial is altered after its initial assignment when n is greater than 1.
151
Computer Programming
VAR c : integer
x : real;
BEGIN
FOR c: = c1 TO c2 DO
BEGIN
x: = f(c);
WRITELN(x=, x)
END
END;
The main block might include the following reference to this procedure.
process(calc, 1, 100);
where the function calc is defined within the main block. Here is a
skeletal structure of the entire main block.
PROGRAM main;
.
.
FUNCTION calc(w : integer) : real;
..
.
152
Procedures and Functions
VAR c : integer;
x : real;
BEGIN
FOR c: = c1 TO c2 DO
BEGIN
x: = f(c);
WRITELN(‘x=’, x)
END
END; (*process*)
Procedure parameters and The formal procedure and function parameters and the actual procedure
function parameters are and function parameters must correspond with respect to their own
particularly useful when the parameters. This correspondence must include the number, class and
given procedure or function
accesses different procedures or type of parameters. Procedure parameters and function parameters are
functions (i.e., makes use of particularly useful when the given procedure or function accesses
different actual parameters) at different procedures or functions (i.e., makes use of different actual
different calling points. parameters) at different calling points.
153
Computer Programming
29.4 Exercise
154
Unit 9 : Arrays and Records
Introduction
Three important data structures have been discussed in this unit. Firstly
array and then records and sets. Array is a data structure where large
amount of identical data can be stored. The methods of accessing
elements of arrays and declaring arrays are listed here. Record is an
important data structure which has elements of different types. Accessing
different elements of records will be shown in the corresponding lesson.
Set is also an important data structure which can incorporate the idea of
mathematics in Pascal programming language. Several examples
incorporating the above ideas have been presented.
Lesson 30 : Arrays-I
30.1 Learning Objectives
On completion of this lesson you will learn :
a new data structure array which allows to store and operate on many
data of the same type.
how array is defined in programming languages
how this data structure can be accessed
use of array with sample program segments.
30.2 Arrays
An ARRAY is a collection of elements of identical data type. Group of
these elements are given a name to identify them collectively. Each
An ARRAY is a collection of
elements of identical data
element in the group can uniquely be identified and hence accessed by
type. using its relative position in that group. One important thing to remember
is that each element of the ARRAY is same in nature i.e., if an ARRAY
is defined of type character then each cell of the ARRAY (each element)
must be of character type.
155
Computer Programming
In the first example above LETTER is the name of the array. "ARRAY"
is the reserved word in PASCAL, [1..26] is the subscript also called
index type, CHAR is the element type in the array LETTER.
The declaration
LETTER
LETTER [1]
LETTER [2]
LETTER [3] This cell can contain a single
character
LETTER [4]
:
: :
: :
LETTER[26]
The declaration
POSITION
156
Arrays and Records
POSITION [1]
POSITION [2]
:
: :
: :
POSITION [20]
30.4 Exercise
157
Computer Programming
iii) To get access to the 5th element, the array reference statement
is
a) List[5]
b) List[10]
c) List[24]
d) none of above.
iv) What happens if we want to get access to List[32]?
a) Error message
b) Garbage value
c) May get content of other data or instruction.
d) none of above.
2. Subscript of array
a) must be positive integer
b) no restriction about +ve or -ve
c) must begin from 0
d) none of above.
3. What does the last program in this lesson do?
a) takes 20 numbers
b) takes 20 integers and calculates their summation and average
c) takes 20 integers from keyboard and calculates their summation
and average
d) none of above.
158
Arrays and Records
The concept of higher dimensional array comes into play when we think
about linear collection of its lower dimensional arrays. For example,
suppose we have an array of type integer having 100 elements. Then we
can think about 10 such arrays each having the same number of integer
elements (1000) arranged together as depicted below to form a two
dimensional array "Table".
Table : 31.1
[1] [2] [3] [4] ............................................. [100]
[1]
[2]
[3]
[4]
: ... .. . ... ...
: ... ...
[10]
The cell highlighted is the 4th cell of 3rd array of the array group.
Using the above rules, following are some valid declarations of two
dimensional arrays :
159
Computer Programming
Month
Year
Day
160
Arrays and Records
In order to access a particular day say December 16, 1971 we will use
which first enters into the year set (1900..1999) , then month set (1..12)
within that year and finally picks up the desired day from within the day
set (1..31) of that month.
Following is the accessing sequence for each day of the array calendar
and is initialized to 0
31.4 Exercise
a) 675
b) 670
c) 680
d) none of the above.
a) 3
b) 6
c) limitless
d) none of the above.
161
Computer Programming
a) 200
b) 800
c) 20
d) none of the above.
a) A[1]
b) A[0] [0]
c) A[1] [1]
d) none of the above.
a) A[20]
b) A[10] [20]
c) A[20] [20]
d) A[10] [10].
162
Arrays and Records
Lesson 32 : Records-I
32.1 Learning Objectives
Record is that structured data type whose constituent elements not be the
same. One of the difficulties of using array is that each element of the
array must be of the same data type. There are some situations where it is
necessary to store heterogeneous data against a single object. As for
example, it may be needed to store student ID, student name, courses
undertaken and GPA of those courses for each student of a class. We can
handle this situation using parallel arrays as follows :
: : : :
: : : :
: : : :
: : : :
: : : :
: : : :
Here using the same subscript in each of the 4 arrays we can have
complete information for a student.
PASCAL provides an alternate and attractive mechanism to store such
data using Records.
Declaration syntax for a Record type data structure is
163
Computer Programming
If we wish to find the 5th character of the student name we should use
the field selector operator (.) as follows :
History = RECORD
Name : ARRAY [1..30] OF char;
Salary : real;
Join : Date
END;
Employee = RECORD
Emp-Id : integer;
Post : char;
Detail : History;
Retire : Date
END;
164
Arrays and Records
32.4 Exercise
32.4.1 Multiple choice questions
1. Record supports
165
Computer Programming
Lesson: 33 Records-II
As we already have seen that array can be of any type e.g. CHAR,
INTEGER, REAL, BOOLEAN or other user defined type, so can be of
type "Record". Thus it is possible to define an array of type "Record".
This is particularly important in some cases where different types of data
for a single entity is required to store all information (name, Id, courses,
GPA, department etc.) of all students of a class. If the class contains 40
students we would define an array of length 40 whose type would be of
<Record type> where <Record type> contains details of each student.
Here is an example of a class roster represented by an array of student
records :
166
Arrays and Records
[2]
2nd record of type student
[3]
[4] Roll[4].Name
K A B J M A m I
2
Roll[4].class
[500] 3.5
Roll[4].GPA
Specifies the 4th element Specifies the GPA field of that record
167
Computer Programming
necessary to write the name of the record plus its field name together
with a dot (.).
Following are two methods to read data into the record type variable std-
Lst array.
Method 1
FOR I : = 1 TO 30 DO
BEGIN
READ (std - Lst [I]. Name);
READ (std - Lst [I]. Roll);
READ (std - Lst [I]. GPA)
END;
Method 2
FOR I : = 1 TO 30 DO
WITH std-Lst [I] DO
BEGIN
Read (Name);
Read (Roll);
Read (GPA)
END;
Note that in method 2 we have used "Std-Lst[I]" 3 times. Thus within the
scope of the WITH statement field identifiers are treated as variable
identifier. Thus within the scope of WITH statement the record
component can be selected by the field identifier alone - not by the full
field selector.
168
Arrays and Records
Lst = RECORD
UNIVERSITY : ARRAY [1..30] OF char;
FACULTY : ARRAY [1..20] OF char;
Member : student
END;
VAR
Roaster : ARRAY [1..10] of Lst;
std : student;
detail : History;
I : = 2;
WITH Roaster [I] DO
WITH number DO
:
:
:
169
Computer Programming
33.4 Exercise
a) Roll[7].Class
b) Roll[7].GPA
c) Roll[7].Name[7]
d) none of the above.
3. For the list Roaster mentioned in this lesson, to get access to the
5th character of faculty name of the 5th element of list Roaster
we have to write
a) Roaster[5].FACULTY[5]
b) Roaster[5].Name[5]
c) Roaster[5][5]
d) none of the above.
a) any where
b) in the loop only
c) for a group of statements
d) none of the above.
170
Arrays and Records
END.
171
Computer Programming
Lesson 34 : Sets
34.1 Learning Objectives
172
Arrays and Records
'+' (Union) : The union of two set variables is a set made up of those
elements which are in either or both.
173
Computer Programming
34.3 Exercise
174
Unit 10 : Pointers and Recursion
Introduction
Lesson 35 : Pointers-I
175
Computer Programming
One of the difficulties of using array is that its size is predefined, and can
One of the difficulties of using not be changed dynamically. This limitation may create a situation of
array is that it's size is
predefined , and can not be
wastage/shortage of memory.
changed dynamically. This
limitation may create a situation We can use dynamic variables to overcome these problems of static
of wastage / shortage of variables like array. We can create new component for our list only when
memory. they are needed by using dynamic variables as components. By having
each component contain the link or pointer to the next component in the
list, we can create a dynamic data structure that can expand or contact as
the program executes.
35.3 Pointers
176
Pointers and Recursion
Range = 1..25;
In the above declaration, ptr1, ptr2, and ptr3 are pointer variables as
denoted by () in their type definitions. The first declaration is read as
"ptr1 is a pointer to a variable of type color". The declaration causes the
compiler to name a memory location ptr1 the content of which will be a
memory address.
177
Computer Programming
35.4 Exercise
1. Pointer is
a) an address
b) a memory location
c) a data type which contains address of any location
d) none of the above structure.
178
Pointers and Recursion
The statements
NEW (ptr1);
NEW (ptr2);
NEW (ptr3);
will put the address in ptr1, ptr2, and ptr3 of each of the newly created
referenced variables, where ptr1, ptr2, ptr3 are defined in the previous
lesson.
Any variable preceded by operator gives the address. For example ptr.3
is a character. We can assign ptr3 = ch, where ch is a character data
declared in declaration part.
ptr1 : = White;
ptr2 : = 17;
ptr1 : = 'A'.
179
Computer Programming
ptr1 :
White
ptr2 :
17
ptr3 :
A
student = RECORD;
name : ARRAY [ 1..20 ] OF char;
next : ptrType
END;
NEW(ptr);
New : = ptr;
180
Pointers and Recursion
Head : = ptr;
Tail : = ptr;
FOR I = 1 TO 19 DO
BEGIN
NEW (tempptr);
Tail . next : = tempptr;
Tail : = Tail. next
END;
Tail . next : = NIL;
Only assignment and a test for equality are legal operations on pointer
variables. For example given these declarations.
NEW (PTRA);
NEW (PTRB);
READ(PTRA, PTRB );
PTRA : = 18;
181
Computer Programming
PTRB : = 20;
PTRA = PTRB;
the PTRA = PTRB evaluates to TRUE and PTRA <> PTRB evaluates
to FALSE.
PTRA PTRA
18 18
PTRB PTRB
20 20
(a) (b)
36.4 Exercise
a) Garbage
b) 5
c) NIL
d) none of the above.
a) 4 bytes
b) 8 bytes
182
Pointers and Recursion
c) 2 bytes
d) none of the above.
183
Computer Programming
Lesson 37 : Recursion-I
184
Pointers and Recursion
VAR val8;
BEGIN
val8 : = y*second(y);
third : = val8
END;
VAR val4;
BEGIN
val4 : = z * first (z);
second : = val4
END;
VAR val2;
BEGIN
val 2 : = p*1;
first : = val2
END;
Now let us define a recursive function power ( ) which perform the same
task more generally. Generally in the sense, we will make a call to
power ( ) with two parameter base and exponent. The function will return
the value of the base raised to the power exponent. This means if the
function is called with 2 and 5, it will return a value 25=32.
BEGIN
if n = 1 then;
power : = x;
else power : = x * power (x, n - 1)
END;
We now see how this simple but powerful function calculates the value
of X raised to the power N.
185
Computer Programming
We know
XN = X*X*X*X*X* ........ *X
N times
= X* (X*X*X*X......*X)
N - 1 times
= X*X* (X*X*X*......*X)
N - 2 times
= X*X*X* (X*X*X*......*X)
N - 3 times
Now to calculate power (2,2) it sees another task of power (2, 1) should
be performed to evaluate X * power (2,1). So another task is pending in
its hand (that is multiplying X with power (2,1)) and this task will have
to be completed after getting return value from power (2,1) function call.
The process continues like this and it maintains a chain of pending task.
[When N becomes 2 then it is needed to calculate the value of X *
power (X,1) still it adds another pending task to its list and calls power
(X,1)]. It immediately gets the success and needs no pending job to add
into the pending list. Just after returning from the call power (2,1) with a
returning value 2 in hand, it will perform the immediate pending task that
is the task which was added in the pending list during the time it invoked
186
Pointers and Recursion
the function call power (2,1). This task is multiplying X with power
(2,1). It will perform the task. This means it has only completed the
function evaluation phase of its previous call that calculation of power
(2,2) is just completed, so it will then perform that task which was added
in the pending list during the time of invoking the function call power
(2,2). This way it will perform all the pending job and the initial call
(from outside the function power ( ) would be completed.
I: = power (2,3)
returned value is 8.
call power (2,3)
FUNCTION
power
x n
2 3
returned value is 4.
call power (2,2)
FUNCTION
power
x n
2 2
187
Computer Programming
37.6 Exercise
a) C
b) PASCAL
c) PROLOG
d) FORTRAN.
a) 10
b) 11
c) 9
d) none of the above.
188
Pointers and Recursion
This 'exit' path is such statements which would be executed due to some
This 'exit' path is such
conditional cases. That is, there must be alternative steps for the program
statements which would be control to be chosen instead of calling itself at least once during running
executed due to some of the program.
conditional cases.
In our recursive example of the previous lesson we have used the
statement
IF N = 1
THEN power : = X
This is actually the 'exit' path in the recursive function. A closer look at
the function revels that each recursive call made to the function power ()
is actually with two parameters one of which (i.e., N) is reduced in each
call. This ensures that if we start with INTEGER N and N 1 there must
be a call with N = 1. At this point there is no need to call power ( ) itself
again and hence return from its previous call.
Once this return happens all pending jobs can easily be computed
because all the pending jobs are only simple multiplications involving no
call to itself.
189
Computer Programming
1: IF N = 1 THEN power : = X
END;
Table 38.1
190
Pointers and Recursion
38.4 Exercise
a) One
b) Two
c) unlimited
d) limited upto the program code size.
a) arithmetic expression
b) assignment statement
c) I/O statement
d) condition checking.
191
Unit 11 : Executing Programs
Introduction
While you are able to write a program you must run it by a compiler of
that language. This unit discusses the process of running programs. First
lesson of this unit discusses some common words about programming.
This lesson describes good programming habit which increases
programming speed of a quality programming. In the next lesson we will
learn some technical aspects of programming. Facilities of debugging or
correcting programs are also described in this lesson. This is actually a
manual of compiler program. The last section describes different types of
errors you can face in programming. The methods of recovering common
errors are also shown here. Some suggestions for program writing are
also given.
Many books have been written about program design, but people are still
arguing about the best ways to do it. Nevertheless, there are a few simple
rules that you can follow to create a good design without having to
become a master theoretician.
First try to understand the problem deeply. Sketch out all the details of
the problem step by step in normal English.
Example : Let us have a problem of finding out the area of circles of any
radius.
193
Computer Programming
start program
clear the screen
state what your program will do
take input of radius from the user
calculate the area using formula
show it
wait for any key
At this stage you need to decide what data structure you must use. You
recall that data structures are parts of your program that hold data, and
you design many of these structures yourself.
You will be able to follow all these features in the later lessons and now
we are presenting a simple demonstration program.
CONST
pi = 3.14159;
VAR
area, radious : real;
PROCEDURE Wait_for_a_key;
VAR
ch : char;
BEGIN
write (‘Press any key to continue...’);
ch := READKEY;
writeln
194
Executing Programs
END;
BEGIN
CLRSCR;
write (‘enter the radius of a circle :’);
read (radius);
area : = pi * sqr (radius);
writeln;
write (‘The area is :’, area);
Wait_for_a_key
END.
2. BEGIN and END are actually brackets that indicate the beginning
and end a of compound statement. So after BEGIN a semicolon is
not needed and before an END, semicolon is not needed.
195
Computer Programming
39.4 Exercise
a) instructions
b) I/O statements
c) separator of statements
d) none of the above.
a) termination of program
b) termination of subroutine
c) termination of statement
d) separator of fields.
196
Executing Programs
Lesson 40: Compiling and Running the Program
idea of compiling
process of compiling
some techniques of tracing for finding errors.
40.2 Compiling
Once you have corrected all the errors (if there were any) , you can press
ALT - F9 again to compile the program. You surely would be cheered
up with the message : “Compile successful : press any key”.
40.3 Running
40.4 Tracing
197
Computer Programming
If the program behaves unusually then we have to trace the program
carefully. There are several rules of tracing. These are given below :-
F7 key : By this key the program halts after execution of each statement
and waits for F7 key.
F8 key : This key is similar to F7 key but ignores all subroutine calls. For
F7 key the tracing inside particular subroutine is going on when a
subroutine call statement is found.
F4 key : Place the cursor at the line which you want to observe and press
the key. The tracing program will run from this line. Other lines will not
be traced.
CTRL F7 key : This key is used to watch the condition of any variable. It
invokes an editor to write the variable name. This variable is placed in
the watched window with their values they possess just now.
CTRL F8 key : This key is used for fixing some break points. While
running program, it halts at the breakpoints. For marking breakpoint
place the cursor at the desired line and press the CTRL F8 key.
40.5 Exercise
a) CTRL F8
b) F8
c) SHIFT F8
d) all of the above.
198
Executing Programs
a) Debugging program
b) Watching the value of constants for modifying
c) Watching the value of variables for correcting programs
d) all of the above.
1. Write down some common errors you have faced in running the
perfect number assignment in previous chapter.
199
Computer Programming
“Bug” is just a name for an error in your program. Anything that prevents
a program from compiling and running correctly is bug. Some program
bugs are catastrophic in their effects, while others are not so dangerous
Anything that prevents a and still others are so obscure that no one will ever discover them.
program from compiling and
running correctly is bug.
There are three main types of errors :
1. SYNTAX errors
2. RUN-TIME errors
3. LOGIC errors.
The compiler can easily detect the syntax errors. Usually you get an
error message and the line of your program causing this error is
highlighted; and the cursor stays at that line. Again there may be some
special occasions when the cursor position is not the true location of the
error at all.
Now lets have a look at some of the most common syntax errors in
Pascal and also discuss what to do with them.
41.3.1 “ ;” Expected
It is one of the most common bug. You know, semicolons are used to
Semicolons are used to separate statements from other statements in a Pascal program. To
separate statements from correct this bug, just add a semicolon at the end of the line from which it
other statements in a Pascal is missing. Normally the compilation error occurs on the line
program. immediately after the line without the semicolon.
200
Executing Programs
The compiler keeps track of nested BEGIN..END pairs, so it knows
when the main body of the program begins and when it ends. In a unit or
In a unit or a program, you
will get this error if the final a program, you will get this error if the final END statement is missing.
END statement is missing.
If you don’t know why you got this message, check your comments,
starting at the end of the program and working back toward the start. An
open comment with no other comments after it will cause the full last
part of the program to disappear from the compilers view. So check it!
When you get this error message, first check the highlighted statement to
make sure that it is not the source of the trouble. If it is not, somewhere
above that statement, another statement or a comment is not terminated
properly : you may have too few ENDs, mixed-up comment brackets, or
some variation on those errors. All you can do against this type of error
is to have a deep knowledge of the rules for constructing statements and
expressions in Pascal (the syntax of Pascal).
The only types you can use in The only types you can use in parameter lists are types that have already
parameter lists are types that been defined in your program. In this example, define a type
have already been defined in
your program. String35 = STRING[35]
41.4.2 “ ,” Expected
In general, this means you haven't passed all of the needed parameters to
a procedure or function you’re calling. If the compiler knows the routine
takes three parameters, then it expects a comma after the second.
41.4.3 “ )” expected
You’ll get this message if you pass too many parameters to a procedure
or function call. It will also come up if you accidentally separate two
parameters in the header of a procedure or function with a colon instead
of a semicolon.
41.4.4 “ =” expected
201
Computer Programming
After typing a lot of VAR declarations, it’s easy to forget and use a colon
instead of an equal sign when writing a TYPE declaration. That is the
common cause of this error.
Ordinal types are those that have a direct correspondence with whole
Ordinal types are those that numbers. Byte, ShortInt, Word, Integer, and LongInt types are ordinal,
have a direct correspon- and so are any subranges of these types. The remaining ordinal types are
dence with whole numbers. Char, Boolean, and user defined enumerated types. Floating-point types,
arrays, sets, files, records, strings, and pointers are not ordinal. If you
attempt to use a nonordinal type in a Set declaration, you’ll get this error.
This error can occur when you are using numeric types such as bytes,
which have very limited range of values. It also can occur with integers,
This error can occur when enumerated types, and subrange types.
you are using numeric types
such as bytes, which have
For example, let us have a variable of type byte named “Val”, an attempt
very limited range of values.
of assigning a value “550” to it causes a run-time error. As “Val” can take
values of only 0 to 255.
202
Executing Programs
41.5.3 Nonmatch in CASE statement: failure to handle it
CASE choice of
1 : Do Something1;
2 : Do Something2;
3 : Do Something3;
END;
Now, what is a logic error ? If you are like me, you should say to your
computer, “Do what I mean, not what I say !”. Remember, the computer
does exactly what it’s told. And the logic error can be understood by
observing the difference between what the computer did and what you
said.
Logic errors occur when the
programmer analyzes a Logic errors occur when the programmer analyzes a problem incorrectly
problem incorrectly and and comes up with the wrong solution. The best way to avoid or
comes up with the wrong minimize logic errors is to keep your code as simple as possible and also
solution. by following structured programming style (as described before).
Example :
203
Computer Programming
a, b , c : INTEGER;
{----------------------------------------------------}
PROGRAM no_2
VAR
a, b, c : INTEGER;
Surely you wish to add a and b and to store the value to c. But in the first
case c equals 0 and in the second case c equals 2.
204
Executing Programs
hand, evaluates the control variable at the end of each loop, so no matter
what the initial value of the control variable, a REPEAT loop will always
execute once.
Logical errors are the most difficult kind of errors to locate. This can
sometimes be accomplished by testing a new program with data that will
This can sometimes be yield a known answer. If the correct results are not obtained, then the
accomplished by testing a program obviously contains errors. Even if the correct results are
new program with data that obtained, however, one cannot be absolutely certain that the program is
will yield a known answer. error-free, since some errors cause incorrect results only under certain
circumstances (as, for example, with certain values of the input data or
with certain program options). So a new program should be thoroughly
tested. This is especially true of complicated programs or programs that
will be used extensively by others.
As a rule, a calculation will have to be carried out by hand, with the aid
of a calculator, in order to obtain a known answer. for some problems,
however, the amount work involved in carrying out a hand calculation is
problematic.
To detect logical errors almost every current Pascal compilers are well
equipped with a debugger. With the debugger, you can trace the
complete flow of the program, and you can see how each variable
changes every step of the way. In previous chapter several commands
have shown already.
Errors both large and small are a fact of programming life. Strangely
enough, the big errors are usually the easiest to correct. Sometimes, it is
difficult even to be sure that a small error is present until the program
crashes, of course. When you ask programmers how they learnt the
process of debugging, you are likely to get a single word in response :
experience.
41.8 Exercise
a) ';' expected
b) ',' expected
c) function 'sqr' not found
d) ')' expected.
205
Computer Programming
a) operating system
b) programmer
c) compiler
d) file server.
a) Pointer
b) Character
c) Integer
d) Array.
a) number of iterations
b) concept of semicolons
c) concept of BEGIN - END
d) none of the above.
1. How many type of logical and syntax errors you can find while
programming? Explain briefly.
206
Unit 12: Programming Style
Introduction
42.3 Adaptability
207
Computer Programming
The design technique that has probably received the most attention and
popularity is referred to as structured design. This technique, as
described by Larry Constantine, and further advanced by Edward
Yourdon and Genford Myers, uses functional decomposition of a system
into a set of well-structured modules. We have discussed dout
moderating is the paragraph 42.2. The main goal of structured design is
to generate a system structure in which the modules are loosely coupled
and highly cohesive.
The main goal of structured
design is to generate a It is desirable that the higher-level modules be relatively machine-
system structure in which the independent, that is, can be performed in any machine without
modules are loosely coupled modification. Usually each higher-level module specifies what actions to
and highly cohesive. be taken. A lower-level module, on the other hand, specifies how the
action is to be performed. Important decisions are made at the top of the
hierarchy, while less important decisions are made at lower levels. The
methodology is based on data flow in, out and through a system. This
flow of data (and its associated processing) is represented by data flow
diagrams. Designs are obtained from these data-flow diagrams.
There are two main strategies for generating a system (or module)
structure that matches the problem structure as described by data-flow
diagrams. In the first method, each independent data flow is regarded as
a transaction that requires a special response by the system. The structure
of a design contains a transaction centre, which consists of modules that
handle each type of transaction. This approach is called transaction
analysis or transaction-centred design. A second approach, transform
analysis, involves identification of important transformations (or
functions) in the system. Such transformations become a transform
centre in the design structure. Structured design also provides other
criteria (besides coupling and cohesion) for evaluating the quality of a
design. Structured design focuses primarily on the operations or
functions performed by a system, with less attention being given to the
design of data structures.
208
Programming Style
209
Computer Programming
42.6 Exercise
210
Programming Style
Assuming Rahim Toss and Karim Toss to have the values ‘H’ or ‘T’
depending upon whether ‘Head’ or ‘Tail’ comes up in their spin we may
organize our program as follows:
PROGRAM CoinMatch(INPUT,OUTPUT);
211
Computer Programming
PROGRAM CoinMatching(INPUT,OUTPUT);
BEGIN
Rahim’s Money : = 50;
WRITELN(‘Input Value of Rahim’s_Toss’);
READLN(Rahim’s_Toss);
WRITELN(‘Input Value of Karim’s_Toss’);
READLN( Karim’s_Toss’);
IF Rahim’s Toss = Karim’s_Toss
THEN Rahim’s Money : = Rahim’s Money + 1
ELSE Rahim’s Money : = Rahim’s Money - 1;
WRITELN(‘Rahim’s winning are’, Rahim’s Money);
UNTIL (Rahim’s Money = 100) or (Rahim’s Money = 0)
END {CoinMatch}
Having seen the form of code needed in the loop, we could program it
directly.
212
Programming Style
213
Computer Programming
43.2 Exercise
214
Programming Style
Although it is generally agreed that any large system, and hence any
large program, should be divided or partitioned into modules if it is
manageable, this division is no guarantee of a well-organized system. It
is imperative, however, that this partitioning be carried out so as to make
the modules independent of one another as much as possible. Let us first
examine this criterion of module independence, that is, module coupling.
A second criterion for partitioning a system is that each module should
carry out a single, problem-related function. We shall examine this
criterion of module cohesion next. In addition to the criteria of coupling
and cohesion, several other criteria or guidelines can be used to evaluate
and improve a design. A discussion of several of these guidelines will be
discussed at the end of this lesson.
215
Computer Programming
We examine the five types of coupling, from the least desirable (that is,
tightest coupling) to the most desirable (that is, loosest coupling). The
strength of coupling between two modules is influenced by the type of
connection, the type of communication between them, and the overall
complexity of their interface.
Two modules are said to be Two modules are said to be control-coupled if one passes data items,
control-coupled if one passes called control flags, to the other in order to control the latter’s inner
data items, called control logic. For example, assume that we have a module that can perform
flags, to the other in order to
either an insertion or a retrieval in a given data structure such as an array.
control the latter’s inner
logic.
One of the parameters required by this module is a Boolean control flag.
A value of true might denote an insertion and false a retrieval. If a
216
Programming Style
Two modules are termed Two modules are termed data-coupled if they communicate through a
data-coupled if they parameter list, each parameter in the list being either a single data item or
communicate through a a homogenous table (such as a vector of numbers). This is the simplest
parameter list, each and most desirable kind of coupling between two modules.
parameter in the list being
either a single data item or a
homogenous table. 44.3 Module Cohesion
Coupling is one of the criteria for evaluating how well a system has been
modularized. This criterion suggests that a well-modularized system is
one in which the module interfaces are clear and simple. Another
criterion for judging a design is to examine each module in a system, and
The internal strength of a
determine the strength of binding within that module. The internal
module, that is, how strongly strength of a module, that is, how strongly related the parts of a module
related the parts of a module are, is referred to as cohesion. A module whose parts are strongly related
are, is referred to as to each other and to the purpose or function of that module is said to be
cohesion. strongly cohesive. On the other hand, a module whose parts are not
related to each other is weakly cohesive.
217
Computer Programming
218
Programming Style
44.4 Exercise
a) 72
b) 82
c) 92
d) 11 2.
a) as low as possible
b) as high as possible
c) as short as possible
d) none of the above.
219
Computer Programming
Answers to MCQS :
220
Programming Style
FURTHER READING
221