You are on page 1of 492

Kindle

edition

COMPUTER
PROGRAMMING
PROBLEMS

Ruma Pal
Srimanta Pal

M-A-T-H
VALLEY
COMPUTER PROGRAMMING
PROBLEMS

Kindle edition

Ruma Pal
Srimanta Pal

M-A-T-H
VALLEY

v
vi

M-A-T-H
VALLEY
Published in India by
Math Valley
mathvalleypublication@gmail.com

Copyright
c 2018 by Authors

The moral rights of the author/s have been asserted.

All rights revised. No part of this publication may be reproduced, stored in


a retrieval system, or transmitted, in any form or by any means, without the
prior permission in writing of Authors, or as expressly permitted
by law, by licence, or under terms agreed with the appropriate reprographics
rights organization. Enquiries concerning reproduction outside the scope of the
above should be sent to the Rights Department, Math Valley, at the
address above.

You must not circulate this work in any other form


and you must impose this same condition on any acquirer.

Typeset in Times New Roman

This Kindle Edition is Publishing and Distributing Globally through


amazone kindle
PREFACE
When a new book is written on a well-known subject area of computers, sev-
eral questions may arise – why, what, how and for whom! Why is the book
written? What is new in it? How is it different from other books on this sub-
ject? For whom is it meant? Answers to these questions are often not mutually
exclusive. Neither are they entirely satisfactory except, perhaps, to authors.
Here it is certainly not under the illusion that altogether there is not a single
book on programming problems for computer courses till now. In India, com-
puter education started from 70’s and it had become popular in late 80’s, but
in the 90’s it came down to commercial level. In this context, there are number
of books published in India and abroad but there are few books directly deals
with the programming problems in sets on different topics of computer and
its applications. It is necessary because any of the computer courses may be
incomplete without assignments, projects and case studies.
However, this is a reference book of programming problems for different
computer courses starting from school level to college level. This book also
helps the undergraduate, graduate, and other professional and management
courses like AMIE; DoE-ACC’s O, A, B, and C level courses on computer
and bioinformatics; B. Sc., B. Tech., M. Tech., M.B.A., M.C.A., CA, ICWA,
etc. The objectives of this book are two fold – one is to improve the power of
programming logic of the beginners and – second, is to implement that logic
in a conventional programming languages such as BASIC, FORTRAN, Pas-
cal, C, C++, Visual Basic/C, Java etc. or using popular tools like MATLAB,
Mathematica, etc. In this connection different sets of problems with increasing
complexity have been considered and also covers different facets on Business,
Computer, Science and Technology.

vii
viii PREFACE

This reference book is organized in a need-based order: it contains 30 Chap-


ters of which Chapter 1 deals with the programming tools and techniques. In
Chapter 2, we have considered 2 simple problems such as (i) a quadratic equa-
tion and (ii) a score computation scheme; and solved them using different tools
and techniques from flow-chart, Basic, C, MATLAB to 4GL. Chapters 3-16
deal with general kinds of problems related to expressions, equations, con-
ditions, whole numbers, table, geometry, computer game, time and date etc.
Chapters 17-19 contain problems related to programming languages. Chap-
ters 20-22 contain problems related to the system softwares. Chapters 23-24
are related to software engineering (SE), SAD and decision table. Chapters 25-
26 contain problems related to data structure and data base (DBMS). Chapter
27 contains some problems related to worksheet. Chapter 28 contains image
processing problems and arranged them in a natural sequence so that one can
easily understand the technique of image processing and graphics. Also a part
of image data file is given at the end of this chapter. Last two chapters 29 and
30 contain case studies and some important project topics. These make the
learning process of logic development and programming to be complete.
This is a reference book for the beginners. A related reference list and an
index are included at the end of this book to enhance its utility.
We feel that these problems are mostly implementable and its arrangement
will improve the logic development power of the promising learners.

Calcutta Ruma Pal


January 15, 2004 Srimanta Pal
PREFACE ix

KINDLE EDITION

In this edition, the book is corrected and reformatted as per the requirement
of Amazone Kindle publication. Hope this will fulfil the requirements of the
reader using on-line devices.

Ruma Pal
July 18, 2018 Srimanta Pal
Contents

1 PROGRAMMING TOOLS AND TECHNIQUES . . . . . . . . . . . . . 1


1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 BASIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.1 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5 FORTRAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5.1 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 PASCAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.6.1 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.6.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.7.1 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.7.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.8 MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.8.1 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

xi
xii Contents

1.8.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.9 MATHEMATICA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.9.1 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.9.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.9.3 How to Run Mathematica? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.9.4 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.9.5 Exact and Approximate Results . . . . . . . . . . . . . . . . . . . . . . . . 27
1.10 C, Pascal and FORTRAN Constructs . . . . . . . . . . . . . . . . . . . . . . . 34

2 PROGRAMMING TWO PROBLEMS USING DIFFERENT


LANGUAGES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.1 Programming Using No File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.2 Programming Using File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

3 SIMPLE PROGRAMMING PROBLEMS . . . . . . . . . . . . . . . . . . . . 97

4 PROGRAMMING EXPRESSIONS AND EQUATIONS . . . . . . . . 103

5 SIMPLE COMPUTATIONAL PROGRAMMING PROBLEMS . 109

6 SIMPLE DESCRIPTIVE PROGRAMMING PROBLEMS . . . . . 121

7 PROGRAMMING USING SIMPLE CONDITIONS . . . . . . . . . . . 131

8 PROGRAMMING USING COMPLEX CONDITIONS . . . . . . . . 147

9 ADVANCED PROGRAMMING PROBLEMS . . . . . . . . . . . . . . . . 171

10 INPUT AND OUTPUT OPERATIONS . . . . . . . . . . . . . . . . . . . . . . . 185

11 PROGRAMMING WITH WHOLE NUMBERS . . . . . . . . . . . . . . 193


Contents xiii

12 PROGRAMMING FOR TABLE PRINTING . . . . . . . . . . . . . . . . . 205

13 PROGRAMMING GEOMETRICAL PROBLEMS . . . . . . . . . . . . 215

14 PROGRAMMING PROBLEMS WITH TIME AND DATE . . . . . 223

15 PROGRAMMING FOR COMPUTER GAMES . . . . . . . . . . . . . . . 231

16 MISCELLANEOUS PROGRAMMING PROBLEMS . . . . . . . . . 251

17 PROBLEM SET FOR FORTRAN . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

18 PROBLEM SET FOR C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

19 PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE . 287

20 PRACTICE PROBLEMS FOR DOS . . . . . . . . . . . . . . . . . . . . . . . . . 309

21 PRACTICE PROBLEMS FOR UNIX . . . . . . . . . . . . . . . . . . . . . . . . 317

22 COMPUTER PROBLEMS ON SOFTWARE ENGINEERING . 327

23 PROBLEMS ON DECISION TABLE . . . . . . . . . . . . . . . . . . . . . . . . 347

24 PROBLEMS ON DATA STRUCTURE . . . . . . . . . . . . . . . . . . . . . . . 357

25 PROGRAMMING PROBLEMS WITH DATABASE . . . . . . . . . . 371

26 SOLVE PROBLEMS USING WORKSHEET . . . . . . . . . . . . . . . . . 399

27 PROGRAMMING PROBLEMS ON IMAGE PROCESSING . . . 415

28 CASE STUDIES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441


xiv Contents

29 LIST OF PROJECTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Chapter 1
PROGRAMMING TOOLS AND TECHNIQUES

1.1 Introduction

Recent trend is to solve our real life problems on accounting, communicating,


word processing, engineering design, medical diagnosis etc. using computers.
But these tasks are not always simple. At first, it is necessary to understand the
problem through a series of steps and write a report which includes planning
, analysis , design , implementation and maintenance phases of development.
This is crudely known as (Table 1.1) for software development. All phases
and their steps of development would follow a cycle.
Table 1.1: Software Development life cycle
I. Planning
1.1 Request for a system study,
1.2 Initial investigation,
1.3 Feasibility study,
II. Analysis
2.1 Redefine the problem,
2.2 Understand the existing system if any,
2.3 Point out users requirement and constrains on a new system,
2.4 Logical model of the recommended solution,
III. Physical design
3.1 System design,
3.2 Detailed design,

1
2 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

IV. Implementation
4.1 Program coding,
4.2 Testing,
4.3 Installation,
4.4 Operations (i.e. refinement if any),
4.5 Post-implementation review,
V. Maintenance
5.1 Maintenance and enhancements.
This study provides a sequence of logical steps for the development of a
system. Furthermore, it is necessary to describe these logical operations us-
ing a suitable technique. Possibly these techniques are algorithms or . Al-
though, the actual implementation is done using some programming tools
(e.g., MATLAB, Mathematica etc.) or programming languages (e.g., BASIC,
FORTRAN, Pascal, COBOL, C, C++, Visual Basic, Visual C, JAVA etc.). In
the following sections, we describe some tools for software development.

1.2 Algorithms

Whenever we solve a problem, there must exist a method provided the prob-
lem is solvable. If the computational scheme of the problem is numeric or
non-numeric then we can write this scheme in a step-by-step fashion. These
step-by-step description of the method is known as algorithm. The concept of
an algorithm is the basis to a computational scheme and it may be defined as
follows:
Algorithm: An algorithm is a finite set of rules, which give a sequence of
operations for solving a specific type of problem.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 3

1.2.1 History

In 825 A.D., a famous Arabic mathematician Abu Jafar Muhammad ibn Musa
al-Khowarizmi who first suggested the method of adding decimal numbers by
taking one digit from each of the operands and a previous carry digit. In his
description of the above method an arabic word algorism is used. The meaning
of this word is the art of computing with arabic numerals. After him, the arabic
word algorism was originated another well known word algorithm.

1.2.2 Features

An algorithm must have the following important features:


Finiteness: An algorithm should be described in such a way that it must ter-
minate after a finite number of steps.
Definiteness: Each step of the algorithm should be described in such a way
that it must be precise, consistent (i.e. contradiction-free) and unambiguous.
Completeness: The algorithm must be complete, so that it can solve all prob-
lems of a particular type for which the algorithm is designed.
Input-output: An algorithm has certain inputs. Also it has certain outputs
which has a specific relations to the input.

1.3 Flowchart

A suitable language is required to describe an algorithm. Although, natural


languages with mathematical notations are used to describe an algorithm. But
the following drawbacks are observed.

1. Usually the algorithms are not concise.


4 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

(a) The natural language is not unambiguous also its context is sensitive.
2. The manner of expression does not reveal the basic structure of the algo-
rithm.
3. Mathematical notations are not always suitable to express some operations
in an algorithm such as replace the variable x by y.

One of the most popular languages for the communication and description of
an algorithm is the language of flowcharting.
Flowchart: It is a pictorial representation of the logic paths contained within
a computer program or an algorithm.
Flowcharting: It is a technique of drawing the flowchart after identifying the
logic paths of the given problem. The identification of logic paths of the prob-
lem and actual drawing of flowcharts are difficult.

The symbols in Fig. 1.1 are used to describe a flowchart.


Process: The process symbol is a rectangular or square box (Fig. 1.1(a)) with
only one exit and one or more entry points, indicates any complete process or
step. A process includes almost all the simple operations described inside the
symbols (Fig. 1.1(b), Fig. 1.1(c)). This symbol is also termed as function box
or assertion box .
Test or Decision: A decision box is a diamond shaped box as shown in
Fig. 1.1(d), normally the flow entered from the top corner of the diamond
shaped box and other corners of it are used to select for different process path.
It represents the occurrence of a question and the answer of this question de-
termines the path to be taken. So a decision box must have at least two exits
also a third exit may be added if necessary. A decision box with two exits may
contain a simple question whose answer is either yes (or y or Y) or no (or n or
N) type represents the exits as shown in Fig. 1.1(e). Sometimes a decision box
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 5

Fig. 1.1 Flowcharting symbols

may contains three exits (Fig. 1.1(f)). This type of decision box represent the
comparison of two quantities. The outcome of a comparison may be labelled
as (i) equal and not equal or (ii) less than, equal to and greater than. For the
first set of outcomes, we use two exits decision box and for the second set of
outcomes we use three exits decision box.
When the number of exits is more than three then we use a flat oval shaped
box (Fig. 1.1(g)) in which one entry point and multiple (more than three) exit
points. Also note that this type of box can be represented by a set of diamond
shaped boxes.
6 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Terminators: This is an oval or a circular shaped box (Fig. 1.1(h)) with either
one exit or one entry point. In case of START box (Fig. 1.1(i)) one exit and in
case of END or STOP box (Fig. 1.1(j)), one entry point.
Flow Lines: It is represented by arrow lines (Fig. 1.1(k)) which indicates the
direction of flow in the flow chart.
Remote Connector: This is a circular shaped box as shown in Fig. 1.1(l).
This type of box is used for the connection between two/more segments of
a flowchart (Fig. 1.1(m), Fig. 1.1(n)). Suppose a flowchart is too big or it
require multiple number of pages then this remote connector symbols are used
in between the segments of the flowchart.
Predefined Process: A subroutine or a predefined process is represented by a
double vertical lined rectangular box (Fig. 1.1(o)).
Input/OutputInput/Output: A parallelogram shaped boxes (Fig. 1.1(p)) are
normally used for input/output (I/O) operations. But a different kind of in-
put/output operations exist. The shape of each kind of I/O operations are
different. Some of the shapes of I/O operations are shown in Fig. 1.1(q)-(v)
like Punched card (Fig. 1.1(q)), Paper tape (Fig. 1.1(r)) are not in use. Some
other widely used I/O boxes are magnetic tape (Fig. 1.1(s)), magnetic disc
(Fig. 1.1(t)), printer device (Fig. 1.1(u)), terminal (Fig. 1.1(v)).

1.4 BASIC

BASIC is an acronym of Beginners All-purpose Symbolic Instruction Code .


It is a high level computer programming language but relatively less powerful
than others. The main objectives of this language are:

(1) BASIC is for beginners: This language is easy to understand by people


even if for non-computer professionals.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 7

(2) BASIC is all-purpose: It is used for the following: (a) simple computa-
tional work, (b) problem solving, (c) small business applications etc.

1.4.1 History

In 1964, Dartmouth College, America found a need for a simple computer


programming language for beginners. The language BASIC fulfilled their
needs and became very popular since then. Ultimately, an attempts have been
made for standardization to produce this software in industry. The Amer-
ican National Standards Institute (ANSI) produced a recommendation in
“ANSI X3JZ/76-01” for minimal BASIC. The National Computing Center
of United Kingdom (U.K.) published specification for standard BASIC, by
Bull, Freeman and Garland. During the span of time the BASIC language en-
riched/enhanced to BASICA, GW BASIC, BASIC+2, VISUAL BASIC etc.
for different kind of computers such as mainframe, mini, micro/personal com-
puters by different software development organizations. Most basic features
are available in all kinds of commercial BASIC compilers/interpreters.

1.4.2 Features

The BASIC language have the following features:

Character Sets
Alphabetic characters: A, B, ...,Z, a, b, ...,z.
Numeric Character: digit 0, 1, ..., 9.
Special Characters: The following characters are used in BASIC but many
other ASCII characters can be printed or displayed.
8 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Character Name
Blank.
= Equal sign or assignment symbol.
+ Plus sign or concatenation symbol.
− Minus sign.
∗ Asterisk or multiplication symbol.
/ Slash or division symbol.
\ Backslash or integer division symbol.
∧ Caret or exponentiation symbol.
( Left parenthesis.
) Right parenthesis.
% Percent sign or integer type declaration character.
# Number (or pound) sign, or double-precision type declaration
character.
$ Dollar sign or string type declaration character.
! Exclamation point or single-precision type declaration character.
& Ampersand.
, Comma.
. Period or decimal point.
’ Single quotation mark (apostrophe), or remark delimiter.
; Semicolon.
: Colon or statement separator.
? Question mark (PRINT abbreviation).
< Less than.
> Greater than.
” Double quotation mark or string delimiter.
Underline.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 9

Variables
There are two kinds of variable, such as
(1) numeric variable (e.g., I, J, X, ABC etc.), and (2) string variable (e.g., A, B,
etc.).
Reserved Words
The following reserve words have special meaning to BASIC.
ABS, AND, ASC, ATN, AUTO, BEEP, BLOAD, BSAVE, CALL, CDBL,
CHAIN, CHAR$, CINT, CIRCLE, CLEAR, CLOSE, CLS, COLOR, COM,
COMMON, CONT, COS, CSNG, CSRLIN, CVD, CVI, CVS, DATA, DATE$,
DEF, DELETE, DIM, DRAW, EDIT, ELSE, END, EOF, EQV, ERASE,
ERL, ERR, ERROR, EXP, FIELD, FILES, FIX, FN, FOR, FRE, GET, GO-
SUB, GOTO, HEX$, IF, IMP, INKEY$, INP, INPUT, INPUT#, INPUT$,
INSTR, INT, KEY, KILL, LEFT$, LEN, LET, LINE, BF, LIST, LLIST,
LOAD, LOC, LOCATE, LOF, LOG, LPOS, LPRINT, LSET, MERGE, MID$,
MKD$, MKI$, MKS$, MOD, MOTOR, NAME, NEW, NEXT, NOT, OCT$,
ON ERROR GOTO, ON n GOTO, ON n GOSUB, ON KEY(n) GOSUB,
ON PEN GOSUB, ON STRING(n) GOSUB, OPEN, OPEN ”COM, OP-
TION, OR, OUT, PAINT, PEEK, PEN, PLAY, POINT, POKE, POS, PRE-
SET, PRINT, PRINT USING, PRINT #, PSET, PUT, RANDOMIZE, READ,
REM, RENUM, RESET, RESTORE, RESUME, RETURN, RIGHT$, RND,
RSET, RUN, SAVE, SCREEN, SCREEN, SGN, SIN, SOUND, SPACE$,
SPC, SQR, STEP, STICK, STOP, STR$, STRIG, STRING$, SWAP, SYS-
TEM, TAB, TAN, THEN, TIME$, TROFF, TRON, USING, USR, VAL,
VARPTR, VARPTR$, WAIT, WHILE, WEND, WIDTH, WRITE, WRITE#,
XOR, etc.
10 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

1.5 FORTRAN

FORTRAN is an acronym of FORmula TRANslation. It is also another oldest


high level computer programming language but relatively less powerful than
modern languages (such as C, C++). The main objectives of this language are:

1. FORTRAN is for Scientists: This language is easy to understand by the


people of basic science background.
2. FORTRAN is also all-purpose: It is used for the following: (a) extensive
computational work, (b) scientific problem solving, (c) small business ap-
plications etc.

1.5.1 History

In 1956, John Backus and his associates developed a programming language


which was basically known as FORTRAN-II. This language was used for
mostly scientific applications. Due to fast development of computer technol-
ogy and its applications to real life problems, Computer languages are also
enhanced from FORTRAN II to FORTRAN IV, FORTRAN IV to FORTRAN
77, FORTRAN 77 to FORTRAN 90 etc. The modern FORTRAN language
even supports structure, recursion etc.

1.5.2 Features

The FORTRAN language have the following features:

Character Sets
Alphabetic characters: A, B, ...,Z, a, b, ...,z.
Numeric Character: digit 0, 1, ..., 9.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 11

Special Characters: The following characters are used in FORTRAN but


many other characters like ASCII characters can be printed or displayed.
Character Name
Blank.
= Equal sign or assignment symbol.
+ Plus sign or addition symbol.
− Minus sign or subtraction symbol.
∗ Asterisk or multiplication symbol.
/ Slash or division symbol.
∗∗ Exponentiation symbol.
( Left parenthesis.
) Right parenthesis.
$ Dollar sign or string type declaration character
, Comma.
. Period or decimal point.
’ Single quotation mark (apostrophe), or remark delimiter.
” Double quotation mark or string delimiter.

Constants
Integer constant: The range of the values of an integer constant depends upon
the word size of the machine, i.e. computer.
Real constant: Real constants are of two types (1) fractional form (e.g.,
0.001256) and (2) exponent form (e.g., 1.256E-3) with different precision.

Variables
The first character of a FORTRAN variable is a letter then followed by 0 or
more letters or digits (maximum size of a variable name depends on compiler,
typically 32). The variable types in FORTRAN are
12 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Integer: The first character of a default integer type variable name belongs to
{I, J, K, L, M, N} otherwise have to declare by INTEGER statement.
Example: KOUNT, LINENO etc. or INTEGER COUNT.
Real: The first letter of default real type variable name not belongs to {I, J, K,
L, M, N} otherwise have to declare by REAL statement.
Example: XMASS, ROLL etc. or REAL MASS.
Character: This type of variables can be created by an assignment statement
variable = ’ ’ or declare by CHARACTER statement.
Example: CHARACTER∗10 NAME.
Logical: This type of variables can be created by an assignment statement
variable = .TRUE. or variable = .FALSE. or declare by LOGICAL state-
ment.
Example: LOGICAL EOF, EOL.

Reserved Words
The following reserve words have special meaning to FORTRAN.
ABS, ACOS, AINT, ALOG, ALOG10, AMAX0, AMAX1, AMIN0, AMIN1,
AMOD, .AND., ASIN, ATAN, ATAN2, ATAN2, CABS, CCOS, CEXP, CHAR-
ACTER, CLOG, CSIN, CSQRT, COMPLEX, DABS, DCOS, DEXP, DLOG,
DLOG10, DMAX1, DMIN1, DMOD, DSIN, DSQRT, DTAN, .EQ., EXP,
FLOAT, GOTO, GOTO (n1 , n2 , ..., nm ), i, ASSIGN m TO i, GOTO i, (n1 , n2 , ..., nk ),
.GT., .GE., IABS, IDINT, IF, IFIX, INT, INTEGER, LOGICAL, .LT., .LE.,
MAX0, MAX1, MIN0, MIN1, MOD, .NOT., .OR., PRINT, READ, REAL,
SQRT, TANH, etc.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 13

1.6 PASCAL

Pascal is also a popular and general purpose algol-like block structured high
level computer programming languages with features that may support both
application and system programming.

1.6.1 History

This language was originally designed by Professor Niklaus Wirth, Techni-


cal University of Zurich, Switzerland in 1971, and named in honor of Blaise
Pascal, the famous French philosopher and mathematician.
Different commercial Pascal compilers are Standard Pascal, ANSI Pascal,
TURBO Pascal, etc. TURBO Pascal is closely follow the definition of stan-
dard Pascal as defined by K. Jensen and N. Wirth in the Pascal User Manual
and report. The syntax definition of a Pascal can be described using Backus
Normal Form or Backus-Naur Form (BNF).

1.6.2 Features

The Pascal language have the following features:

Character Sets
Alphabetic characters: A, B, ...,Z, a, b, ...,z.
Numeric character: digit 0, 1, ..., 9.
Special characters : Some of the special characters in Pascal is as follows but
many other ASCII characters can be printed or displayed.
+, −, , ∗, /, +, =, <, >, :
14 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Input output (IO) procedures and functions


Procedures: Read(var F:file of type; var V:type); Read(var F: text; var I: Inte-
ger); Read(var F:text; var R: Read); Read(var F: text; var C: Char); Read(var
F: text; var S: string); Readln(var F: text); Write(var F: file of type; var V :
type) Write(var F: text; I: Integer); Write(var F: text; R: Real); Write(var F:
text; B: Boolean); Write(var F: text; C: Char); Write(var F: text; S: string);
Writeln(var F: text);
Arithmetic functions: Abs(I: Integer): Integer; Abs(R: Real): Real; Arc-
Tan(R: Real): Real; Cos(R: Real): Real; Exp(R: Real): Real; Frac(R: Real):
Real; Int(R: Real): Real; Ln(R: Real): Real; Sin(R: Real): Real; Sqr(I: Inte-
ger): Integer; Sqr(R: Real): Real; Sqrt(R: Real): Real;
Scalar functions: Odd(I: Integer): Boolean; Pred(X: scalar): scalar; Succ(X:
scalar): scalar;
Transfer functions: Chr(I: Integer): Char; Ord(X: scalar): Integer; Round(R:
Real): Integer; Trunc(R: Real): Integer;

String procedures and functions


Procedures: Delete(var S: string; Pos,Len: integer); Insert(S: string; var D:
string; Pos: integer); Str(I: Integer; var S: string); Str(R: Real; var S: string);
Val(S: string; var R Real; var p : integer); Val(S: string; var I,p : integer);
Functions: Concat(S1,S2,...,Sn: string): string; Copy(S: string; Pos, Len: In-
teger): string; Length(S: string): Integer; Pos(Pattern,Source: string): Integer;

File handling routines


Procedures: Assign(var F: file; name: string); BlockRead(var F: file; var Dest:
Type; Num: Integer); BlockWrite(var F: file; var Dest: Type; Num: Integer);
Chain(var F: file); Close(var F: file); Erase(var F: file); Execute(var F: file);
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 15

Rename(var F: File); Reset(var F: file); Rewrite(var F: file); Seek(var F: file


of type; Pos: Integer);
Functions: Eof(var F: file): Boolean; Eoln(Var F: Text): Boolean; FilePos(var
F: file of type): Integer; FilePos(var F: file of type): Integer; FileSize(var F: file
of type): Integer; FileSize(var F: file): Integer; Seek(var F: file; Pos: Integer);

Heap control procedures and functions


Procedures: GetMem(var P: pointer; I: Integer); Mark(var P: pointer); New(var
P: pointer); Release(var P: pointer);
Functions: MemAvail : Integer; Ord(P: pointer): Integer; Ptr(I: Integer): pointer;
Screen related procedures: CrtExit; CrtInit; ClrEol; ClrScr; DelLine; Go-
toXY(X, Y: Integer); Insline; LowVideo; NormVideo;

Miscellaneous procedures and functions


Procedures: Bdos(func, param: Integer); Bios(func, param: Integer); De-
lay(ms: Integer); FillChar(var dest; length: Integer; data: Char); FillChar(var
dest; length: Integer; data: byte); Halt; Move(var source, dest, length: Integer);
Randomize;
Functions: Addr(var variable): Integer; Addr(<function identifier>): Integer;
Addr(<procedure identifier>): Integer; Bdos (Func, Param: Integer): Byte:
BdosHL (Func, Param: Integer): Integer; Bios(Func, Param: Integer): byte;
BiosHL (Func, Param: Integer): Integer; Hi(I: Integer): Integer; IOresult:
Boolean; KeyPressed: Boolean; Lo(I: Integer): Integer; Random(Range: In-
teger): Integer; Random: Real; SizeOf(var variable): Integer; SizeOf(<type
identifier>): Integer; Swap(I: Integer): Integer; UpCase(Ch: Char): Char;
16 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Operators
Here operators are grouped in order of descending precedence. Where type of
operand is indicated as integer, real, the result is as follows:
Operands −→ Integer, Integer Real, Real Real, Integer
Results −→ Integer Real Real
Operator Operation Type of operand(s) Type of result(s)
+ unary sign identity Integer, Real as operand
− unary sign inversion Integer, Real as operand
not negation Integer, Boolean as operand
∗ multiplication Integer, Real Integer, Real
set intersection any set type as operand
\ division Integer, Real Real
div Integer division Integer Integer
mod modulus Integer Integer
and arithmetical and Integer Integer
logical and Boolean Boolean
shl shift left Integer Integer
shr shift right Integer Integer
+ addition Integer, Real Integer, Real
concatenation string string
set union any set type as operand
− subtraction Integer, Real Integer, Real
set difference any set type as operand
or arithmetical or Integer Integer
logical or Boolean Boolean
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 17

Operator Operation Type of operand(s) Type of result(s)


xor arithmetical xor Integer Integer
logical xor Boolean Boolean
= equality any scalar type Boolean
equality string Boolean
equality any set type Boolean
equality any pointer type Boolean
<> inequality any scalar type Boolean
inequality string Boolean
inequality any set type Boolean
inequality any pointer type Boolean
>= greater or equal any scalar type Boolean
greater or equal string Boolean
set inclusion any set type Boolean
<= less or equal any scalar type Boolean
less or equal string Boolean
set inclusion any set type Boolean
> greater than any scalar type Boolean
greater than string Boolean
< less than any scalar type Boolean
less than string Boolean
in set membership see below∗ Boolean

. The first operand of the in operator may be of any scalar type, and the second
operand must be a set of that type.
18 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

1.7 C

C is a high level structured but not well structured programming language. It is


very powerful than others because it also acts as a low level programming lan-
guage (assembly level programming language). C is also suitable for writing
system software.

1.7.1 History

In 1972, the C language was developed at AT & T Bell Laboratories, Murray


Hill, New Jersey by one man, Dennis Ritchie who was working closely with
Ken Thompson on UNIX operating system. In the mid-1970s UNIX spread
throughout Bell Labs and to Universities. C began to replace the more famil-
iar languages available on UNIX. No one pushed C as official language of
Bell Labs. But Ritchie found that many programmers preferred C than others.
Today different commercial C compilers are available, many of them running
on non-UNIX systems.

1.7.2 Features

The following features of C programming language compared with others is


given below:

1. Types in C are not so strict as in Pascal. Because data types in C are to be


interchange freely.
2. There is no type Boolean as in Pascal but nonzero is equivalent to true and
zero is equivalent to false.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 19

3. C has aggregate types like array as in others and also structure as in other
structured programming languages (e.g. record in Pascal). But C has no
notation of files.
4. Declarations in C procedure may not be nested, so it is not block-structured.
5. C does not distinguish procedures from functions.
6. C supports recursive procedure calls as in others like Pascal.
7. The syntax of C language is concise. It uses { and } but in Pascal begin end.
8. In C, the brackets [ ] denote subscripts in an array and parentheses ( ) denote
procedure calls.
9. C has a powerful set of operators, also in bit-wise operations (such as shift,
and, or, complement and exclusive or).
10. C allows arithmetic operations on pointer variables.
11. In C statement, the terminator is semicolon (;).
12. The C macro preprocessor can handles parameterized macros.
13. In C, comments start with “/*” and end with the next “*/” as in PL/I or start
with // that indicate rest of the line is the comment.
14. Identifiers in C can contain letters, digits or underscores, they must begin
with a letter or an underscore.
15. An n-way conditional statement in C is switch statement but in Pascal case
statement. Here default in C is equivalent to otherwise in Pascal.
16. In C, data can be initialized at compile time; by default, the initial value of
an external data object is zero.
17. C supports separate compilation of procedures.
20 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

1.8 MATLAB

The name MATLAB stands for MATrix LABoratory. It is a high-performance


language for technical computation to provide easy access to matrix software.
Now MATLAB can be defined as:
MATLAB creates an easy-to-use technical computing and interactive en-
vironment for the user to perform high-performance numerical computation,
visualization and programming where problems and solutions are expressed
in familiar mathematical notation. Also one can able to write a program in a
language such as FORTRAN, BASIC or C.

1.8.1 History

The first version of MATLAB system was written in FORTRAN by Cleve


Moler, in an evolutionary process over several years. The project LINPACK
and EISPACK was the state-of-the-art in software for matrix computation.
The current version of the MATLAB software was written in C by The
MathWorks groups. The first release was written by Steve Bangert, who wrote
the parser/interpreter, Steve Kleiman. He also wrote the analytical routines,
the user’s guide, and most of the M-files. Since the first release, many other
people have joined the MATLAB development team and have made substan-
tial contributions.
MATLAB has evolved over a period of years with input from many users. In
university environments, it is the standard instructional tool for introductory
and advanced courses in mathematics, engineering, and science. In industry,
MATLAB is the tool of choice for high-productivity research, development,
and analysis.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 21

1.8.2 Features

The MATLAB tools have the following features:

1. Mathematical and numerical computation.


2. Algorithm development.
3. Modelling, simulation and prototyping.
4. Data analysis and visualization.
5. Scientific and engineering graphics.
6. Application software development.
7. Provides a family of application-specific toolboxes.
8. Toolboxes allow to learn and apply specialized technology.
9. Provides a collection of MATLAB functions (M-files) that extend the MAT-
LAB environment to solve particular classes of problems.
10. Includes signal processing, control systems, neural networks, fuzzy logic,
wavelets, simulation, and many others.
11. Useful to interact with data and programs external to MATLAB.
12. Provides an Application Program Interface (API)
• Calling C or Fortran programs from MATLAB.
• Importing and exporting data to and from the MATLAB environment.
• Establishing client/server relationships between MATLAB and other soft-
ware programs.

The MATLAB includes numerical analysis, matrix computation and graph-


ics features.
The MATLAB system consists of five main parts:

1. The MATLAB language


This is a high-level matrix/array language with control flow statements,
22 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

functions, data structures, input/output, and object-oriented programming


features.
2. The MATLAB working environment
Provide a set of tools and facilities to MATLAB users. It includes (a) man-
aging the variables in the workspace, (b) importing and exporting data, and
(c) tools for developing, managing, debugging, and profiling MATLAB files
(M-files), MATLAB applications.
3. Handle Graphics
MATLAB provides graphics facilities to the users. It includes both (a) high-
level commands for 2-D and 3-D data visualization, image processing, an-
imation, and presentation graphics, and (b) low-level commands for fully
customize the appearance of graphics.
Other functions are:
Function Description
ops Operators and special characters.
lang Programming language constructs.
strfun Character strings.
iofun File input/output.
timefun Time and dates.
datatypes Data types and structures.
general General purpose commands.

4. The MATLAB mathematical function library


It is a collection of computational algorithms ranging from elementary func-
tions like sum, sine, cosine, and complex arithmetic, etc. to more sophisti-
cated functions like matrix inverse, matrix eigenvalues, Bessel functions,
and fast Fourier transforms, etc.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 23

5. The MATLAB Application Program Interface (API)


User’s C or FORTRAN program can interact with MATLAB. Other facili-
ties are: (a) calling routines from MATLAB (dynamic linking), (b) calling
MATLAB as a computational engine, and (c) reading and writing MAT-files.
Function Description
graph2d Two-dimensional graphs.
graph3d Three-dimensional graphs.
specgraph Specialized graphs.
graphics Handle Graphics.
uitools Graphical user interface tools.
elmat Elementary matrices and matrix manipulation.
elfun Elementary math functions.
specfun Specialized math functions.
matfun Matrix functions numerical linear algebra.
datafun Data analysis and Fourier transforms.
polyfun Interpolation and polynomials.
funfun Function functions and Ordinary Differential Equations
(ODE) solvers.
sparfun Sparse matrices.

1.9 MATHEMATICA

Mathematica is an advanced interactive problem-solving system for numerical


and mathematical symbolic computation. Various practical problems repre-
sented by mathematical notations in algebra, differential and integral calculus,
differential equations etc. (both numerically and symbolically) can be solved
using Mathematica. Also it can tackle more advanced mathematical problems.
24 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

1.9.1 History

The Mathematica system was created by Stephen Wolfram in his Wolfram Re-
search, Inc. He started this work since late 1986. Its first version was released
on June 23, 1988, and the popularity grew rapidly. The second version was
released in 1991. Initially, its impact was felt mainly in the physical sciences,
engineering and mathematics. But to-day it is used throughout the sciences -
physical, biological, social and other. It has played a crucial role in many im-
portant discoveries. In engineering, It is a standard tool for both development
and production. In commerce, it played a significant role in the growth of so-
phisticated financial modelling, as well as being widely used in many kinds
of general planning and analysis. Also it is an important tool in computer sci-
ence and software development: its language component is widely used as a
research, prototyping and interface environment.

1.9.2 Features

The following features are found in Mathematica.

1. Use as a calculator,
2. A large power computing tools (xy ) where y is large,
3. Accessing algorithms,
4. Mathematical knowledge for numerical and symbolic computations,
5. Handling data and data files,
6. Data and image visualization,
7. Use notebooks for interactive calculations,
8. Use mathematical notations for numerical and symbolic computations,
9. Provide an unifying idea and a computing environment,
10. Use as a programming language,
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 25

11. Writing programs in mathematica to build mathematical systems,


12. Provide software components.

1.9.3 How to Run Mathematica?

Running Mathematica depends on installation to a computer system. But the


structure of computation in Mathematica is the same in all installation. Enter
the input for your problem, then Mathematica processes it, and returns an
output.

1.9.3.1 Notebook Interfaces

Double-click the ”Mathematica” icon to start it. Running Mathematica with


a notebook interface. Mathematica normally supports a ”notebook” interface,
so that one can interact with it by creating interactive documents.
Mathematica starts with a blank notebook. Now enter an input into this note-
book, then press Shift+Return key to process the input. Also one can use the
standard editing features of the graphical interface to prepare the input, which
may go on for several lines. The Shift+Return key indicates the end of input.
After sending Mathematica input from the notebook, Mathematica will label
the input with In[n]:=. It labels the corresponding output Out[n]=.
Example: Type 2 + 12 on the notebook, then end the input with Shift + Return
key. Mathematica processes this input, that is, adds the input label In[1]:=, and
gives the output as shown below:

In[1] := 2 + 12
Out[1]= 14

Note that, the notebook is a part of the ”front end” to Mathematica. The ac-
tual computation of the input in the notebook is perform by the kernel of the
26 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Mathematica system. In most cases, the kernel is not even started until actual
calculation is to perform with Mathematica.
To exit Mathematica, choose the Quit menu in the notebook interface.

1.9.3.2 Text-Based Interfaces

The following text commands are used to interface with mathematica.


math : A command to start Mathematica.
text ending with Shift-Return : Input for “Mathematica” on all systems.
text ending with Return : Simpler form for input available on some systems.
”Control-D” or Quit : To exit Mathematica.

1.9.3.3 Running Mathematica with a text-based interface

A text-based interface means typing text on the keyboard.


To start Mathematica with a text-based interface, do the following (1) type
the command math at an operating system prompt. or (2) by double-clicking
on a Mathematica Kernel icon. Mathematica starts with the prompt In[1]:=,
then type the input and press Shift-Return key (or in some system Return or
Enter alone) to finish the input. Mathematica will then process the input, and
generate the output with label Out[1]=.
To exit Mathematica, either type Control-D, Control-Z or Quit at an input
prompt.

1.9.4 Arithmetic

Mathematica performs the arithmetic operations like an electronic calculator


using the following operators.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 27

xˆy : power,
-x : minus,
x/y : divide,
x y z or x*y*z : multiply,
x + y + z : add

Arithmetic operations in Mathematica are grouped according to the standard


mathematical conventions. For example:

2ˆ3+4, means (2ˆ3)+4, and not 2ˆ(3+4).

You can always control grouping by explicitly using parentheses.

1.9.5 Exact and Approximate Results

A calculator calculates at a particular accuracy, say ten decimal digits. But


Mathematica can compute an exact value. For example, Mathematica gives an
exact result for 2100 , even though it has 31 decimal digits.

In[1]:= 2 ˆ 100
Out[1]= 1267650600228229401496703205376

Mathematica also give an approximate numerical result, just as a calculator


would, by ending the input with //N. The N stands for “numerical”. It must
be a capital letter.
This gives an approximate numerical result.
In[1]:= 2 ∧ 100 / / N
Out[1]= 1.26765 ×1030
In[2]:=FindRoot[x2 + x + 1 == 0, {x, 1 − i}]
Out[2]= {x − > -0.5 - 0.866025 i}
In[3]:=FindRoot[x2 + x + 1 == 0, {x, 1 + i}]
28 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Out[3]= {x− > −0.5 + 0.866025i}


In[4]:=FindRoot[6 − 5x + x2 == 0, {x, 4}]
Out[4]= {x− > 3.}
In[5]:=FindRoot[6 − 5x + x2 == 0, {x, 2}]
Out[5]= {x− > 2.}

Symbolic Calculations
Mathematica calculates both symbolic and numeric expressions. Parentheses
control the grouping of arithmetic operations. Note that the product of a and
b is written as a b. Without a space ab is a single variable.
In[1]:= Expand[(a b − c d)2 − (a d + b c)2 ]
Out[1]=a2 b2 − b2 c2 − 4a b c d − a2 d 2 + c2 d 2
In[2]:= Factor[%]
Out[2]= (a b − b c − a d − c d) (a b + b c + a d − c d)
Mathematica reduces an expression to its simplest forms.
In[1]:= Simplify[Cos[x]4 − Sin[x]4 ]
Out[1]= Cos[2 x]

List
A list is a collection of things or articles. These are used, to represent vectors,
matrices, tensors, sets, ranges of integrals and plots, and groups of arguments
in functions. Lists are given in curly brackets ( { } ) and their elements are
separated by commas ( , ).
Example: (1) {1, 2, 10}, (2) {x, a, 20}.
List generate command is Table. The list {x, 2, 10} specifies that x goes from
2 to 10, that is, {2, 3, 4, 5, 6, , 7, 8, 9, 10}. If x starts at 1, then use {x, 10}.
In[1]:= Table[3x , {x, 2, 11}]
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 29

Out[1]= {9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147}

A matrix is a list of lists. The = sign is used to define mx, a 3 × 5 matrix.


In[1]:= mx = Table[a xb , {a, 3}, {b, 4}]
Out[1]= {{x, x2 , x3 , x4 }, {2x, 2x2 , 2x3 , 2x4 }, {3x, 3x2 , 3x3 , 3x4 }}
Use Part[mx, a, j] to get the element in the ath row and jth column of a matrix
m. The short notation mx[[a, j]] works as well. Lists to group multiple results:
In[1]:= {Part[mx, 1, 3], mx[[2, 3]]}
Out[1]= {x3 , 2x3 }

Compute mathematical functions for every element in a list.


In[1]:= sin[π /{2, 3, 4, 7}]

2 , 2 , Sin[π /7]}
3 √1
Out[1]= ({1,

Graphics
Function of one variable
In[1]:= Plot[Sin[Exp[x]], {x, 0, 4}];
Out[1]=

Function of two variables


In[1]:= Plot3D[Cos[x] Sin[y], {x, 0, 2 π }, {y, 0, 2 π }];
30 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Out[1]=

Integration and Differentiation


1
Z
The result of an integration dx has no integration constant.
x2 + a2
In[1]:= Integrate[1/(x2 + a2 ), x]
ArcTan[x/a]
Out[1]=
a
Differentiate the previous result.
In[1]:= D[%, x]
1
Out[1]=
2
x2
a (1 + 2 )
a
Simplify the previous result
In[1]:= Simplify[%]
1
Out[1]= 2
x + a2
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 31

Definite Integration
NIntegrate
Z 0.5 p
finds numerical approximations. Suppose the definite integral is
2 − x2 − x6 dx.
0 p
In[1]:= NIntegrate[ {2 − x2 − x6 }, {x, 0, .5}]
Out[1]= 0.69167

Evaluations
The symbol ‘=’ used to assign values to variables. Semicolons (;) are used
to separate commands on one line. The commands are executed in sequence,
with the output being the result of the last command.
p
In[1]:= x = 3; y = x + 1; x2 + y2
Out[1]= 5
In[2]:= Clear[x, y]; Expand[(x + y)2 ]
Out[2]= x2 + 2xy + y2

Solve Equation Symbolically


Solve is used to find symbolic solution of an equation.
In[1]:= Solve[x2 + x == a, x]
√ √
Out[1]= {{x− > 12 (−1 − 1 + 4 a)}, {x− > 12 (−1 + 1 + 4a)}}
In[2]:= Solve[x2 − 5 x == −6, x]
Out[2]= {{x− > 2}, {x− > 3}}
In[3]:= Solve[x2 + 2x == −3, x]
√ √
Out[3]= {{x− > −1 - i 2}, {x− > −1 + i 2}}
In[4]:= Solve[{x2 - k2 == 0, y2 == x2 }, {x, y}]
Out[4]= {{x− > −k, y− > −k}, {x− > −k, y− > k},
{x− > k, y− > −k}, {x− > k, y− > k}}
√ p
In[5]:= Solve[Log[ x] == Log[x], x]
32 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

Out[5]= {{x− > 1}, {x− > e4 }}

Solve Equations Numerically


NSolve is used to find numerical approximations to the roots of a polynomial
equation.
In[1]:= solutions = NSolve[x3 + x + 1 == 0, x]
Out[1]= {{x− > −0.682328}, {x− > 0.341164 − 1.16154i},
{x− > 0.341164 + 1.16154i}}
NSolve returns a list of rules. To get a list of numbers for x instead, you just
apply these rules to x using the /. operator.
In[1]:= x /. solutions
Out[1]= {−0.682328, 0.341164 − 1.16154i, 0.341164 + 1.16154i}

Numerical Solutions to Systems of Simultaneous Equations


In[1]:= NSolve[{x + y == 2, x − 3y + z == 3, x − y + z == 0}, {x, y, z}]
Out[1]= {{x− > 3.5, y− > −1.5, z− > −5.}}
In[2]:= FindRoot[3 Cos[x] == Log[x], {x, 1}]
Out[2]= {x− > 1.44726}

Differential Equations
Symbolic solution to a simple differential equation with an initial condition:
In[1]:= DSolve[{y‘[x] == ay[x] + 1, y[0] == 0}, y[x], x]
−1 + eax
Out[1]= {{y[x]− > }}
a

Numerical Solution to a Nonlinear Differential Equation

In[1]:= result =
NDSolve[$\{y’’[t] + 0.1 y’[t] == -Sin[y[t]],
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 33

y[0] == 1, y’[0] == 0}, y, {t, 0, 50}]


Out[1]= {{y -> InterpolatingFunction[{{0., 50.}}, <>]}}

Manipulate Vectors and Matrices


Vectors in Mathematica are represented by lists. The dot product of two vec-
tors u and v is indicated by u.v.

In[1]:= {1, 2, 3} . {a, b, c}


Out[1]= a + 2 b + 3 c

Without the dot, the vectors are multiplied component-by-component.

In[1]:= {1, 2, 3} {a, b, c}


Out[1]= {a, 2 b, 3 c}

Matrix Operations

In[1]:= Inverse[{{1, 2}, {2, 3}}]


Out[1]= {{-3, 2}, {2, -1}}

The dot product of a matrix with its inverse gives the identity matrix.

In[1]:= {{1, 2}, {2, 3}} . %


Out[1]= {{1, 0}, {0, 1}}

Calculate the eigenvalues or eigenvectors of a matrix.


In[1]:= Eigenvalues[{{1, 2}, {2, 3}}]
√ √
Out[1]= {2 - 5, 2 + 5}

Define Functions f
In[1]:= f[x] := Expand[(1 + x)2 ]
Variables, numbers, or symbolic expressions as arguments to f.
In[1]:= {f[x], f[1.1], f[a + b]}
Out[1]= {1 + 2x + x2 , 4.41, 1 + 2a + a2 + 2b + 2ab + b2 }
34 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

In[2]:= g[x] := Expand[(1 + x)2 ]; {g[x], g[1.1], g[a + b]}


Out[2]= {1 + 2x + x2 , g[1.1], g[a + b]}
Use = instead of :=, the right-hand side of the definition will be evaluated im-
mediately, rather than each time the function is called.
In[1]:= h[x] = Expand[(1 + x)2 ]; {h[x], h[1.1], h[a + b]}
Out[1]= {1 + 2x + x2 , 4.41, 1 + 2(a + b) + (a + b)2 }

Summary of Important Mathematica Notation

(1) All built-in functions start with a capital letter e.g. Abs[−32]
(2) Use [ ] to enclose function arguments e.g., Mod[7, 3]
(3) Use { } to enclose list elements e.g., {1, 2, 3}
(4) Use ( ) to indicate grouping of terms e.g., a/(b c)
(5) expr/.x\[Rule]y means “in expr replace x by y” e.g., p2 /.p− > 2
(6) Use = to assign a value to a variable, e.g., y = 3.8
(7) Use == to express equality, e.g., Solve[x2 == 3, x]
(8) Use := to define a function. e.g., f [x ] := x2
(9) Use x to indicate an arbitrary expression named x, e.g., f [x ] := x2

1.10 C, Pascal and FORTRAN Constructs

Constructs for the languages C, Pascal and FORTRAN, are discussed below.
VARIABLES
C Pascal FORTRAN 90 Explanation
Construct Construct Construct
int x; var x : integer; integer :: x Declarations: integer
char y; var y : char; character :: y Character
char *x; var x : ↑char; character, pointer :: x Pointer to character
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 35

VARIABLES (cont.)
C Pascal FORTRAN 90 Explanation
Construct Construct Construct
int (*x)(); none none Pointer to procedure
that returns integer
char x[10]; var x: ar- Character*4 x(10) Array of characters
ray[0..9] of or Character, di-
char; mension(10) :: x or
Character, dimen-
sion(0:9) :: x, or
Character(len=10)::x
char x[10][15]; var x: ar- Character*4 x(10,15) 2-dimensional array of
ray[0..9,0..14] or Character, dimen- characters
of char; sion(0..9,0..14) :: x
or Character, dimen-
sion(0:9)::x
char *f[10]; var f: ar- none Array of pointers
ray[0..9] of
↑char;
char **x; var x: ↑↑char; none Pointer to pointer
36 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

LITERALS
C Pascal FORTRAN 90 Explanation
ConstructConstructConstruct
356 356 356 Decimal constant
O356 none none Octal constant (decimal value 236) has
leading zero
0x356 none none Hexadecimal constant (decimal value
854)
’p’ ’p’ ’p’ Character constant
’\013’ none none Character constant with value 013 (oc-
tal)
”xyz” none ”xyz” String constant
(some Array of contiguous characters termi-
Pascal nated by a null byte (i.e., ’x’, ’y’, ’z’,
compilers ′ \0’). Newline and tab denoted by \n
use ’xyz’) and \t. Value is the address of the first
character.

STRUCTURES
C Pascal FORTRAN 90 Explanation
Construct Construct Construct
struct x{ x = record type x Structure (record)
int T1; T1 : integer; integer :: T1 declaration with
char T2; T2 : char character ::T2 fields T1 and T2
} end end type x
struct x q[5]; var q: array type(x), dimen- q is an array of struct x
[0..4] of x; sion(5) :: q
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 37

# OPERATIONS
C Pascal FORTRAN 90 Explanation
Construct Construct Construct
#define T x const T = x; integer :: T, Symbolic constant
parameter (T =
x)
integer, param-
eter :: t = x
#define T(a) none none Parameterized macro
x(a)
#ifdef T none none Conditional compilation
F code F is compiled only
#endif if symbol T defined.
#ifndef T none none Negative conditional
F compilation, code F is
#endif compiled only if T not de-
fined.
#include pqr none none Source file inclusion (if pqr
is path then path is relative
to the current directory; if <
path > then relative to sys-
tem directory).
38 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

POINTER and ARRAY


C Pascal FORTRAN 90 Explanation
Construct Construct Construct
x[i] x[i] x(i) Array reference.
s. f s. f s% f Reference to field f in structure s.
p− > f p ↑ .f none Reference to field f in structure
pointed to by p.

OPERATORS
C Pascal FORTRAN 90 Explanation
ConstructConstruct Construct
= := = Assignment operator.
+ + + Addition arithmetic operator.
− − − Subtraction arithmetic operator.
∗ ∗ ∗ Multiplication arithmetic operator.
/ / or div / Division arithmetic operator (C does
integer division on integers).
% none none Modulus or remainder arithmetic op-
erator.
== = .EQ. or = Test equality operator.
!= <> .NE. or / = Test not equality operator.
> > .GT. or > Test greater than operator.
< < .LT. or < Test less than operator.
>= >= .GE. or >= Test greater than or equal to operator.
<= <= .LE. or <= Test less than or equal to operator.
& none none Bitwise and binary operator.
| none none Bitwise or (bitwise 1’s complement)
operator.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 39

OPERATORS (Contd)
C Pascal FORTRAN 90 Explanation
ConstructConstruct Construct
&& and .AND. Boolean and operator (C evaluates
left-to-right termination but Pascal
does not use early termination crite-
ria).
|| or .OR. Boolean or operator (C evaluates left-
to-right termination but Pascal does
not use early termination criteria).
! not .NOT. Boolean not operator.

Pre and Post operators


C Pascal FORTRAN 90 Explanation
ConstructConstructConstruct
++x x := x + 1 x = x + 1 Preincrement (when used in an expres-
sion + + x refers to the value of x after
increment.)
x++ x := x + 1 x = x + 1 Postincrement (when used in an expres-
sion x + + refers to the value of x before
increment.)
−−x x := x − 1 x = x − 1 Predecrement (when used in an expres-
sion − − x refers to the value of x after
decrement.)
x−− x := x − 1 x = x − 1 Postdecrement (when used in an expres-
sion x − − refers to the value of x after
decrement.)
40 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

INSTRUCTIONS
C Pascal FORTRAN 90 Explanation
Construct Construct Construct
e?a : b none none Conditional expression, if e
is nonzero then value is a else
value is b.
p(e1, e2, · · · , en)p(e1, e2, · · · , en)p(e1, e2, · · · , en)Procedure invocation.
while (exp) S; while exp <> do Indefinite iteration.
0 do S while(.TRUE.)
end do
if (exp) S; if exp<> 0 if (exp) S or Conditional if statement.
then S if (exp) then S
endif
if (exp) S1 else if exp <> 0 if (exp) then S1 2-way conditional if state-
S2; then S1 else S2 else S2 endif ment.
{S1; S2; · · · ; Sn}begin none Compound statement.
S1; S2; · · · ; Sn
end
for (S1; exp; S1; do i=S1,S2,exp Indefinite iteration with ini-
S2) S3; while exp S3 tialization and reinitialization
<> 0 do enddo (S1, exp and S2 are optional
begin S3; S2 – if exp is omitted, infinite
end loop results).
return return return end Procedure return i.e. finish
executing procedure.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 41

INSTRUCTIONS (Cont.)
C Pascal FORTRAN 90 Explanation
Construct Construct Construct
return(exp) function name return Return exp to caller as func-
:= exp; tion value i.e. finish execut-
ing function.
void name( procedure Subroutine Procedure declaration.
declaration of name(formals); name(formals)
formals)
declaration of declaration of declaration of
formals formals locals
{ begin
declaration of declaration
local variables; statements of locals
statements; return
} end; end or end
name
type function function Function declaration.
name(formals) name(formals); name(formals)
declaration of declaration of declaration of
formals locals locals
{ begin Statements
declaration of
local variables; statements return
statements;
} end; end
42 CHAPTER 1. PROGRAMMING TOOLS AND TECHNIQUES

INSTRUCTIONS (Cont.)
C Pascal FORTRAN 90 Explanation
Construct Construct Construct
for (i = 0; i < for i:= 1 to n do Do i=0,n-1,1 Typical loop to search.
n; i + +)
...x[i].... ...x[i].... x(i)= Array x, assuming x has size
n.
∗x + + none none Idiomatic expression for
pointer x: its value is
whatever x points to; x is
incremented after the ref-
erence according to pointer
arithmetic.
(type)exp none none Type casting the type of ex-
pression exp is changed.
1 + (int)&x none none Example: make the address
of x an integer before adding
1 to it (i.e., use integer, not
pointer, arithmetic).
/* ... */ (*...*) or {...} ! or C Comment.
Chapter 2
PROGRAMMING TWO PROBLEMS USING
DIFFERENT LANGUAGES

2.1 Programming Using No File

Problem 1: Solve a quadratic equation: ax2 + bx + c = 0.


Solution: The solution of the quadratic equation ax2 + bx + c = 0 can be ob-
tain by different ways such as using (1) a mathematical method, (2) flowchart
method, (3) algorithemically or (4) different programming languages.
Mathematical Methods: This problem can be solved either (a) using sym-
bolic notations, that is, Algebraic Method, (b) using numerical values, that is,
Numerical Methods.
Algebrical Method: The given equation is ax2 + bx + c = 0, where a, b and c
are coefficients, and x is the unknown variable. Our objective is to determine
the values of x in terms of a, b and c.
Case 1: Suppose a = 0, the equation transformed to bx + c = 0 which is a lin-
ear equation of x. Therefore the solution is x = −c/b, provided b 6= 0.
Case 2: Suppose both a = 0 and b = 0. Now c must be equal to 0, and the
given equation ax2 + bx + c = 0 becomes an identity, that means, any value of
x satisfies both the sides. √
−b ± b2 − 4ac
Case 3: Suppose a 6= 0, the solution is x = .
2a
Numerical Method: An infinite precision is assumed in algebraic computa-
tion of x from the equation ax2 + bx + c = 0. But in practice this is not true.
Numerical methods deals with
√ numbers only in finite precision. So in some
−b ± b2 − 4ac
cases the formula x = may not be suitable.
2a

43
44 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

Case 1: Suppose√a = 1, b = 2 and c √= −3


−b ± b2 − 4ac −2 ± 22 + 4.1.3 −2 ± 4
Then x = = = = 1, −3.
2a 2.1 2
The direct use of the formula provides a correct solution.
Case 2: Suppose
√ one root of the quadratic equation ax2 + bx + c = 0 is given
−b + b2 − 4ac
by .
2a
Consider the equation x2 + 0.4002x + 0.00008 = 0 using four-digit floating-
point arithmetic. By using the above formula, we get an answer of −0.00015.
The true root, with no limit on the number of digits used, is −0.0002. Now
consider the following √ curious phenomenon.
−b + b2 − 4ac −2c
Mathematically, is exactly equivalent to √ .
2a b + b2 − 4ac
That is, in infinite precision, both will yield the same true value. In our ex-
ample, with four-digit precision, the first formula does not give the true value,
but the mathematically equivalent second formula does give the true value
−0.0002. So, the mathematically equivalent entities are not computationally
equivalent.
Flow Chart Method: A flow-chart for the solution of the quadratic equation
is given in Fig. 2.1.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 45

Fig. 2.1 Flow Chart for Problem 1


46 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

Algorithmic Method: An algorithm for the solution of the quadratic equation


is given below:
Algorithm: Quadratic Equation
Step 1: Read the coefficients a, b, c.
Step 2: Compute the discriminant D = b2 − 4ac.
Step 3: Compute D2 , the square-root of absolute value of D, that is, D2 =
p
|D2 |.
b D2
Step 4: Compute xR = − and xI = .
2a 2a
Step 5: Check the sign of D for the determination of real or complex roots.
If D < 0 then
Roots are complex
root1 = xR + ixI and root2 = xR − ixI
else
Roots are real
root1 = xR + xI and root2 = xR − xI .
Step 6: Print root1 and root2 .
Step 7: Stop.

Programming Methods: Computer is used to solve this quadratic equation,


with the help of different programming languages, tools and techniques.

(a) BASIC Programming


Suppose the name of the BASIC program file is QUARD.BAS. This file is cre-
ated by a non-document editor. If it is externally created, then load quard.bas
file in the BASIC environment (say, GWBASIC). The LIST command shows
the program.
Program file name : QUARD.BAS

100 REM Solve a quadratic equation


COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 47

110 Rem axˆ2+bx+c=0


200 REM Step 1: Read coefficients a, b, c
300 INPUT "Input coefficient of xˆ2; a =",a
400 INPUT "Input coefficient of x; b =",b
500 INPUT "Input constant term; c =",c
510 IF (a <> 0.0) then 600
520 IF (b <> 0.0) then 540
525 PRINT " This is not a valid equation"
530 GOTO 940
540 PRINT " It is not a linear equation"
550 PRINT " Root is "; -c/b
560 GOTO 940
600 REM Step 2: Compute discriminant D
610 D = bˆ2-4*a*c
700 REM Step 3: Compute D2, the square root
710 REM of absolute value of D
720 D2 = SQR(ABS(D))
800 REM Step 4: Compute two components XR and XI
810 XR = -b/(2*a)
820 XI = D2/(2*a)
850 REM Step 5: Check the sign of D
860 IF (D < 0) THEN 870 ELSE 910
870 PRINT "Complex roots"
880 PRINT "Root1: ";XR;"+"; XI;"i"
890 PRINT "Root2: ";XR;"-"; XI;"i"
900 GOTO 940
910 PRINT "Real roots"
48 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

920 PRINT "Root1: ";XR+XI


930 PRINT "Root2: ";XR-XI
940 STOP
950 END

Now the RUN command execute this program as:

Run 1:
-----------------------------------------
RUN
Input coefficient of xˆ2; a =1
Input coefficient of x; b =-5
Input constant term; c =6
Real roots
Root1: 3
Root2: 2
Break in 940
Ok
-----------------------------------------
Run 2:
-----------------------------------------
RUN
Input coefficient of xˆ2; a =1
Input coefficient of x; b =1
Input constant term; c =1
Complex roots
Root1: -.5 + .8660254 i
Root2: -.5 - .8660254 i
Break in 940
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 49

Ok
SYSTEM
-----------------------------------------

Note: At the end of the session, type ”SYSTEM” command to exit from GW-
BASIC or BASICA.

(b) FORTRAN Programming

The FORTRAN version of this program is in file QUARD.FOR as given


below. First compile this program using a FORTRAN compiler by a com-
mand ”C:\FORTRAN>FOR1 QUARD” and it produces an executable file
QUARD.EXE. Now directly run this executable file by the command ”C:QUARD”.

Program file name : QUARD.FOR

C Solve a quadratic equation axˆ2+bx+c=0


REAL a, b, c
REAL D,D2,XR,XI,X1,X2
C Step 1: Input the coefficients a, b, c
Write(*,10)
Write(*,15)
15 FORMAT(’ Enter the coefficient of X, b = ’)
Read(*,12) b
Write(*,20)
20 Format(’ Enter the constant term, c = ’)
Read(*,12) c
C Step 2: Compute discriminant D
D = b**2-4*a*c
50 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

C Step 3: Compute D2, the square root of


C absolute value of D}
D2 = sqrt(abs(D))
C Step 4: Compute two components XR and XI
XR = -b/(2*a)
XI = D2/(2*a)
C Step 5: Check the sign of D
IF(D .LT. 0) THEN
Write(*,40) XR, XI
40 FORMAT(’ Complex roots’,/,’ Root1:’,2F10.4,’i’)
Write(*,45) XR, -XI
45 FORMAT(’ Root2: ’, F10.4,F10.4,’i’)
ELSE
Write(*,50) XR+XI
50 FORMAT(’ Real roots’,/, ’ Root1: ’,F10.4)
Write(*,55) XR-XI
55 FORMAT(’ Root2: ’,F10.4)
ENDIF
STOP
END
Output:
Run 1
-----------------------------------------
Enter the nonzero coefficient of Xˆ2, a = 1
Enter the coefficient of X, b = 1
Enter the constant term, c = 1
Complex roots
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 51

Root1: -.5000 .8660i


Root2: -.5000 -.8660i
Stop - Program terminated.
-----------------------------------------
Run 2
-----------------------------------------
Enter the nonzero coefficient of Xˆ2, a = 1
Enter the coefficient of X, b = -5
Enter the constant term, c = 6
Real roots
Root1: 3.0000
Root2: 2.0000
Stop - Program terminated.
-----------------------------------------

(c) PASCAL Programming

Turbo PASCAL programming language is used to solve the quadratic equa-


tion.

Program file name : QUARD.PAS

Program QuadraticEquation;
{Solve a quadratic equation axˆ2+bx+c=0}
var
a, b, c : real;
D,D2,XR,XI,X1,X2 : real;
begin {main}
{Step 1: Input the coefficients a, b, c}
52 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

writeln; writeln;
Write(’ Enter the nonzero coefficient of Xˆ2,a = ’);
Read(a); writeln;
Write(’ Enter the coefficient of X, b = ’);
Read(b); writeln;
Write(’ Enter the constant term, c = ’);
Read(c); writeln;
{Step 2: Compute discriminant D}
D := b*b-4*a*c;
{Step 3: Compute D2, the square root of
absolute value of D}
D2 := sqrt(abs(D));
{Step 4: Compute two components XR and XI}
XR := -b/(2*a); XI := D2/(2*a);
{Step 5: Check the sign of D}
if D < 0 then
begin
Writeln(’Complex roots’);
Writeln(’Root1: ’,XR:8:3, XI:8:3,’i’);
Writeln(’Root2: ’,XR:8:3, -XI:8:3,’i’);
end
else
begin
Writeln(’Real roots’);
Writeln(’Root1: ’,XR+XI:8:3);
Writeln(’Root2: ’,XR-XI:8:3);
end
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 53

end.
Output:
Run 1
--------------------------------------------
Enter the nonzero coefficient of Xˆ2, a = 1
Enter the coefficient of X, b = 1
Enter the constant term, c = 1
Complex roots
Root1: -0.500 0.866i
Root2: -0.500 -0.866i
--------------------------------------------

Run 2
--------------------------------------------
Enter the nonzero coefficient of Xˆ2, a = 1
Enter the coefficient of X, b = -5
Enter the constant term, c = 6
Real roots
Root1: 3.000
Root2: 2.000
--------------------------------------------

(d) C Programming

The C programming language is used to solve the quadratic equation. Suppose


the file name of this C program is QUARD.C. Turbo C compiler compiles this
program for execution. The C program and sample outputs are given below.
Program file name : QUARD.C

#include<stdio.h>
54 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

#include<stdlib.h>
#include<math.h>
void main()
{
float a, b, c;
float D,D2,XR,XI;
/* Step 1: Input the coefficients a, b, c */
printf("\nEnter the nonzero coefficient of Xˆ2,a = ");
scanf("%f",&a);
printf("Enter the coefficient of X, b = ");
scanf("%f",&b);
printf("Enter the constant term, c = ");
scanf("%f",&c);
/* Step 2: Compute discriminant D */
D = b*b-4*a*c;
/* Step 3:Compute square root of absolute value of D*/
D2 = sqrt(abs(D));
/* Step 4: Compute two components XR and XI */
XR = -b/(2*a); XI = D2/(2*a);
/* Step 5: Check the sign of D */
if (D < 0)
{ printf("\nComplex roots");
if(XI < 0) XI=-XI;
printf("\nRoot1: %8.3f+%8.3fi\n",XR,XI);
printf("Root2: %8.3f-%8.3fi\n",XR,XI);
}
else
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 55

{ printf("\nReal roots");
printf("\nRoot1: %8.3f\n",XR+XI);
printf("Root2: %8.3f\n",XR-XI);
}
}
Output:
Run 1
-------------------------------------------
Enter the nonzero coefficient of Xˆ2, a = 1
Enter the coefficient of X, b = -5
Enter the constant term, c = 6
Real roots
Root1: 3.000
Root2: 2.000
-------------------------------------------
Run 2
-------------------------------------------
Enter the nonzero coefficient of Xˆ2, a = 1
Enter the coefficient of X, b = 1
Enter the constant term, c = 1
Complex roots
Root1: -0.500+ 0.866i
Root2: -0.500- 0.866i
-------------------------------------------

(e) MATLAB
The MATLAB programming tool is used to solve the quadratic equation.
Suppose its MATLAB program is QUARD.M. If we run this QUARD.M file
56 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

using MATLAB. Then the system ask for inputs and produces outputs.
Program file name : QUARD.M

function q=QuadraticEquation
% Input: a = Coefficient of Xˆ2
% b = Coefficient of X
% c = Constant
% Output:Print two roots X1 and X2 may be complex / real
% Step 1:Input coefficients of the quadratic equation
% axˆ2+bx+c=0
a = input(’Enter the nonzero coefficient of Xˆ2: a =’);
b = input(’Enter the coefficient of X: b = ’);
c = input(’Enter the constant term: c = ’);
% Step 2: Compute discriminant D
D = bˆ2-4*a*c;
% Step 3: Compute square root of absolute value of D
D2 = sqrt(abs(D));
% Step 4: Compute two components XR and XI
XR = -b/(2*a); XI = D2/(2*a);
% Step 5: Check the sign of D
if D < 0
fprintf(’Complex roots \n’);
fprintf(’Root1: %8.3f %8.3f i \n’,XR,XI);
fprintf(’Root2: %8.3f %8.3f i \n’,XR,-XI)
else
fprintf(’Real roots \n’);
fprintf(’Root1: %8.3f \n’,XR+XI);
fprintf(’Root2: %8.3f \n’,XR-XI);
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 57

end
Output:
Run 1
--------------------------------------------
Enter the nonzero coefficient of Xˆ2 : a = 1
Enter the coefficient of X: b = 2
Enter the constant term: c = 3
Complex roots
Root1: -1.000 1.414 i
Root2: -1.000 -1.414 i
--------------------------------------------
Run 2
--------------------------------------------
Enter the nonzero coefficient of Xˆ2 : a = 1
Enter the coefficient of X: b = -5
Enter the constant term: c = 6
Real roots
Root1: 3.000
Root2: 2.000
--------------------------------------------

(f) MATHEMATICA
Mathematica can solve equations symbolically as well as numerically using
computer. Here equations are written with == notation. The second argument
of the function Solve is the variable to be solved for. Solutions are returned as
rules of the form x value.
Run MATHEMATICA in the program mode, the system provide In[1] :=
prompt. Now type “Solve[x2 + x == a, x]” instruction, it looks as
58 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

In[1]:= Solve[x2 + x == a, x]
Cursor is on that line, press enter key for execution. It produces an output as:

“Out[1]= {{x− > 21 (−1 − 1 + 4a)},

{x− > 21 (−1 + 1 + 4a)}}

Few samples are listed below:


Run 1
In[1]:= Solve[x2 + x == a, x]

Out[1]= {{x− > 12 (−1 − 1 + 4a)},

{x− > 21 (−1 + 1 + 4a)}}
Run 2
In[1]:= Solve[x2 − 5x == −6, x]
Out[1]= {{x− > 2}, {x− > 3}}
Run 3
In[1]:= Solve[x2 + 2x == −3, x]
√ √
Out[1]= { {x− > −1 − i 2}, {x− > −1 + i 2}}
The operator, ‘=’ is reserved for assigning values to variables.
Solve equations numerically using Mathematica
The function NSolve is used to find numerical approximations to the roots of
a polynomial equation.
Run 4
In[1]:= solutions = NSolve[x2 + x + 1 == 0, x]
Out[1]= {{x− > −0.500 − 0.866i}, {x− > −0.500 + 0.866i}}
The function NSolve returns a list of rules. To get a list of numbers for x in-
stead, you just apply these rules to x using the /. operator.
Run 5
In[1]:= x/. solutions
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 59

Out[1]= {−0.500 − 0.866i, −0.500 + 0.866i}


The function FindRoot is also used to find a root within the given interval.
Run 6
In[1]:=FindRoot[x2 + x + 1 == 0, {x, 1 − i}]
Out[1]= {x− > −0.5 − 0.866025i}
Run 7
In[2]:=FindRoot[x2 + x + 1 == 0, {x, 1 + i}]
Out[2]= {x− > −0.5 + 0.866025i}
Run 8
In[3]:=FindRoot[6 − 5x + x2 == 0, {x, 4}]
Out[3]= {x− > 3.}
Run 9
In[4]:=FindRoot[6 − 5x + x2 == 0, {x, 2}]
Out[4]= {x− > 2.}

(g) WORK-SHEET
A work-sheet in Excel can be used to solve this quadratic equation. The work-
sheet contains data as well as formula.
Suppose this work-sheet can be prepared as follows: we shall enter data
and formula in between columns A to E and rows 10 to 21 as shown below
(Table 2.1. Here entries are keying as “Step 1” in slot A10 and ”Read the coef-
ficients a, b, c” in slot B10. Other entries are shown in the table and it is stored
in the file QUARD.XLS.
Work-sheet file name: QUARD.XLS
60 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

Table 2.1: Work-sheet with formulae


A B C D E
10 Step 1 Read the coefficients a, b, c
11 a b c
12 1 2 −3
13 Step 2 Compute D
14 +$C$122̂ − 4 ∗ $B$12 ∗
$D$12
15 Step 3 Compute D2
16 +@SQRT (@ABS ($B
$14))
17 Step 4 Compute XR and XI
18 +(- $C $12 / (2 * $B $12 )) + $B $16 / ( 2 *
$B $12)
19 Step 5 Compute Roots
20 Root1 @IF( $B $14 < ’+i @IF( $B $14 <
0, $B $18, $B 0,$C $18, 0)
$18 + $C $18)
21 Root2 @IF( $B $14 < ’-i @IF( $B $14 <
0, $B $18, $B 0, $C $18, 0)
$18 - $C $18)
Here entries are keying as follows: A big cursor is in the opened work-sheet.
Now bring this cursor at the position A10 of the work-sheet using four arrows.
Type “Step 1” at A10 location and “Read the coefficients a, b, c” at B10 loca-
tion. Other entries can be typed as in Table 2.2.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 61

Table 2.2: Work-sheet with formulae


Cursor Type it in the cell
at the cell
A10 Step 1
B10 Read the coefficients a, b, c
B11 a
C11 b
D11 c
A12 1
B12 2
C12 -3
A13 Step 2
B13 Compute D
B14 +$C$122̂ − 4 ∗ $B$12 ∗ $D$12
A15 Step 3
B15 Compute D2
B16 +@SQRT (@ABS ($B $14))
A17 Step 4
B17 Compute XR and XI
B18 +(- $C $12 / (2 * $B $12 ))
C18 + $B $16 / ( 2 * $B $12)
A19 Step 5
B19 Compute Roots
B20 Root1
C20 @IF( $B $14 < 0, $B $18, $B $18 + $C $18)
D20 ′ +i

E20 @IF( $B $14 < 0,$C $18, 0)


62 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

Table 2.2: Work-sheet with formulae (cont.)


Cursor Type it in the cell
at the cell
B21 Root2
C21 @IF( $B $14 < 0, $B $18, $B $18 - $C $18)
D21 ′ +i

E21 @IF( $B $14 < 0, $C $18, 0)


Sample outputs
Run 1
Step 1 Read the coefficients a, b, c
a b c
1 2 -3
Step 2 Compute D
16
Step 3 Compute D2
4
Step 4 Compute XR and XI
-1 2
Step 5 Compute Roots
Root1 1 +I 0
Root2 -3 -I 0
Run 2
Step 1 Read the coefficients a, b, c
a b c
1 1 1
Step 2 Compute D
-3
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 63

Step 3 Compute D2
1.732050808
Step 4 Compute XR and XI
-0.5 0.866025404
Step 5 Compute Roots
Root1 -0.5 +I 0.866025404
Root2 -0.5 -I 0.866025404
Run 3
Step 1 Read the coefficients a, b, c
a b c
1 5 6
Step 2 Compute D
1
Step 3 Compute D2
1
Step 4 Compute XR and XI
-2.5 0.5
Step 5 Compute Roots
Root1 -2 +I 0
Root2 -3 -I 0

(h) FoxPro/Dbase Programming


The following FoxPro or Dbase program, QUARD.PRG solves a quadratic
equation.
Program file name : QUARD.PRG

**************************************
* Dbase or FOXPro Program to solve a *
* quadratic equation axˆ2+bx+c=0 *
64 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

**************************************
set talk off
set heading off
clear
clear all
clear gets
*var
a =1.0
b =1.0
c =1.0
* D,D2,XR,XI,
*begin {main}
* Step 1: Input the coefficients a, b, c
@08,10 say ’Enter the coefficient of Xˆ2,a =’ get a
@09,10 say ’Enter the coefficient of X, b =’ get b
@10,10 say ’Enter the constant term, c =’ get c
read
If a=0.0 .and. b=0.0
? ’It is not an equation’
return
else
If a=0.0
? ’It is not a quadratic equation’
? ’Root of this linear equation is’, -c/b
return
endif
endif
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 65

* Step 2: Compute discriminant D


D = b*b-4*a*c
* Step 3: Compute D2, the square root of abs(D)
D2 = sqrt(abs(D))
* Step 4: Compute two components XR and XI
XR = -b/(2*a)
XI = D2/(2*a)
* Step 5: Check the sign of D
if D < 0.0
? ’Complex roots’
? ’Root1: ’,XR, XI,’i’
? ’Root2: ’,XR, -XI,’i’
else
? ’Real roots’
? ’Root1: ’,XR+XI
? ’Root2: ’,XR-XI
endif
return

Some sample runs of the QUARD.PRG are given below.

Run 1
----------------------------------
Enter the coefficient of Xˆ2,a = 0
Enter the coefficient of X, b = 0
Enter the constant term, c = 1
It is not an equation
----------------------------------
Run 2
66 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

----------------------------------
Enter the coefficient of Xˆ2,a = 0
Enter the coefficient of X, b = 1
Enter the constant term, c = 1
It is not a quadratic equation
Root of this linear equation is -1
----------------------------------
Run 3
----------------------------------
Enter the coefficient of Xˆ2,a = 1
Enter the coefficient of X, b = 1
Enter the constant term, c = 1
Complex roots
Root1: -0.50 0.87 i
Root2: -0.50 -0.87 i
----------------------------------
Run 4
----------------------------------
Enter the coefficient of Xˆ2,a = 1
Enter the coefficient of X, b = -5
Enter the constant term, c = 6
Real roots
Root1: 3.00
Root2: 2.00
----------------------------------
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 67

2.2 Programming Using File

Problem 2: An instructor of a course was arranged 3 tests each of 30 marks


and 1 final examination for 40 marks. These marks are stored in a file with
students name and roll/ registration number. The composite score/marks of a
student is computed as the sum of marks for best 2 tests out of those 3 tests and
the marks obtained in the final examination. Create an output file that contains
(1) students registration number, (2) name, (3) marks obtained in test 1, (4)
marks obtained in test 2, (5) marks obtained in test 3, (6) marks obtained
in final examination, and (7) the composite score. Also find the registration
number, name of the student and composite score for the topper of this course
in the class.
Assumptions: Each student in the class of this course appeared for all tests
and the final examination. Suppose the class has 5 students and their marks
are shown in a tabular form. A sample input data is shown in the following
table.
Input data
Reg. No Name of students Test 1 Test 2 Test 3 Final
CS/01 C. V. Rajan 12 25 21 35
CS/02 B. X. Roy 25 07 23 29
CS/03 P. C. Sasikumar 10 27 7 36
CS/04 B. D. Box 26 26 26 35
CS/05 K. K. Mukerjee 29 0 23 30
Solution: The possible solutions of this problem are:
Alternative 1: One possible solution of this problem is given below:

(1) First compute the best 2 out of 3 tests (test 1, test 2 and test 3). For example,
the marks of 3 tests for the first record ”CS/01, C. V. Rajan, 12, 25, 21, 35”
are 12, 25 and 21. Therefore the best 2 out of these 3 tests are 25 and 21.
68 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

(2) Compute composite score: composite marks = Sum of best 2 tests’ marks +
Marks of Final = (25 + 21) + 35 = 81.
(3) Perform these task [both (1) and (2)] for all students.
(4) Find the maximum of the composite marks and puck up that student(s).

Alternative 2: Another possible solution of this problem is given below:

(1) Compute minimum marks obtained in 3 tests for a student.


(2) Compute total of all marks (3 tests + final) for the student.
(3) Subtract the minimum marks from the total to obtain the composite marks
for the student.
(4) Repeat step 1 to 3 for all students in the table.
(5) Compute maximum of composite marks for all students.
(6) Pick up those students whose composite marks is equal to the maximum of
the composite marks.

Flow Chart Method


A flowchart of problem 2 is given below. It represents the above procedure.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 69

Algorithmic Method
Consider two files: (1) input data file which contains 6 columns of data such
as first column with 5 characters for registration number (RegNo) of the stu-
dent, the second column with 16 characters for name (Name) of the student,
70 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

the third column contains marks of test 1 (Test1). Similarly 4th, 5th and 6th
columns contains marks of test 2 (Test2), marks of test 3 (Test3), and marks
of final examination (Final) respectively. (2) Output file that contains the com-
puted output in the desired form.
Algorithm: Score computation.
Step 1: [Open files:]
Open the input and output files.
Step 2: [Read a record from input file:]
Read Registration number (RegNo), name
(Name), marks of test 1 (Test1), marks of test
2 (Test2), marks of test 3 (Test3), and marks
of final examination (Final).
Step 3: [Compute minimum of these 3 tests]
MinimumTestMarks = Test1
If MinimumTestMarks > Test2 then
MinimumTestMarks = Test2
If MinimumTestMarks > Test3 then
MinimumTestMarks = Test3
Step 4: [Compute composite score:]
CompositeMarks = Test1 + Test2 + Test3 -
MinimumTestMarks + Final
Step 5: [Print name and marks in the output file:]
Print Registration number (RegNo), name
(Name), marks of test 1 (Test1), marks of
test 2 (Test2), marks of test 3 (Test3), marks
of final examination (Final) and composite
marks.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 71

Step 6: [Save for topper:]


If MaxMarks < Composite Marks then
MaxMarks = Composite Marks
MaxRegNo = regno
MaxName = SName
MaxTest1 = test1
MaxTest2 = test2
MaxTest3 = test3
MaxFinal = final
Step 7: [Print topper’s result:]
Print MaxRegNo), MaxName, MaxTest1,
MaxTest2, MaxTest3, MaxFinal and Max-
Marks.
Step 8: Stop

Programming Methods

(a) BASIC Programming


File name : MARKS.BAS

10 REM ***************************************
20 REM * Basic program for Marks computation *
30 REM ***************************************
40 OPEN "I", #1, "MARKBAS.DAT"
50 OPEN "O", #2, "MARKBAS.OUT"
60 MaxMarks= final
70 MaxRegNo$ = "CS "
80 MaxName$ = "Ram "
72 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

90 MaxTest1 = 0
100 MaxTest2 = 0
110 MaxTest3 = 0
120 MaxFinal = 0
130 IF EOF(1) GOTO 300
140 INPUT #1, REGNO$,SNAME$,TEST1,TEST2,TEST3,FINAL
150 mintests = test1
160 if mintests > test2 THEN mintests = test2
170 if mintests > test3 THEN mintests = test3
180 Compmarks=test1+test2+test3+final-mintests
190 PRINT #2, REGNO$; " "; SNAME$; " "; TEST1; TEST2;
TEST3;FINAL;COMPMARKS
200 If MaxMarks > CompMarks GOTO 130
210 MaxMarks = CompMarks
220 MaxRegNo$ = regno$
230 MaxName$ = SName$
240 MaxTest1 = test1
250 MaxTest2 = test2
260 MaxTest3 = test3
270 MaxFinal = final
280 GOTO 130
290 REM PRINT TOPPER
300 PRINT #2, "Highest score obtained by"
310 PRINT #2, MaxRegno$;" "; MaxName$;" ";
320 PRINT #2, Maxtest1;Maxtest2; Maxtest3;MaxFinal
325 PRINT #2, "Maximum Marks = ";MaxMarks
330 CLOSE #1, #2
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 73

340 STOP
350 END

Data file name : MARKBAS.DAT

"CS/01", "C. V. Rajan ", 12, 25, 21, 35


"CS/02", "B. X. Roy ", 25, 7, 23, 29
"CS/03", "P. C. Sasikumar ", 10, 27, 7, 36
"CS/04", "B. D. Box ", 26, 26, 26, 35
"CS/05", "K. K. Mukerjee ", 29, 0, 23, 30

Note: End-of-file marker must be just after 30, that is, at the end of the last
entry of the data file.
Output file name : MARKBAS.OUT

CS/01 C. V. Rajan 12 25 21 35 81
CS/02 B. X. Roy 25 7 23 29 77
CS/03 P. C. Sasikumar 10 27 7 36 73
CS/04 B. D. Box 26 26 26 35 87
CS/05 K. K. Mukerjee 29 0 23 30 82
Highest score obtained by
CS/04 B. D. Box 26 26 26 35
Maximum Marks = 87

(b) FORTRAN Programming


FORTRAN program for this problem is given below.
FORTRAN program file name : MARKS.FOR

C ***************************************
C * FORTRAN program for Marks computation *
C ***************************************
Character*16 MaxName, Sname
74 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

Character*5 MaxRegNo, RegNo


Real MaxMarks,MaxTest1,MaxFinal
OPEN(UNIT=5,FILE=’MARKFOR.DAT’,
*ACCESS=’SEQUENTIAL’,STATUS=’OLD’)
C Any non-blank character at column 6 is indicating C
continuation of the statements
OPEN(UNIT=6,FILE=’MARKFOR.OUT’,ACCESS=’SEQUENTIAL’,
1STATUS=’NEW’)
MaxMarks = 0.0
5 READ(5,10,END=100)REGNO,SNAME,TEST1,TEST2,
3 TEST3,FINAL
10 FORMAT(A5,1X,A16,4(1X,F4.1))
mintests = test1
if(mintests .GT. test2) mintests = test2
if(mintests .GT. test3) mintests = test3
Compmarks=test1+test2+test3+final-mintests
WRITE(6,20) REGNO, SNAME, TEST1, TEST2, TEST3,
2FINAL, COMPMARKS
20 FORMAT(1X,A5,2X,A16,5F6.2)
IF(MaxMarks .LE. CompMarks) THEN
MaxMarks = CompMarks
MaxRegNo = regno
MaxName = SName
MaxTest1 = test1
MaxTest2 = test2
MaxTest3 = test3
MaxFinal = final
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 75

ENDIF
GOTO 5
C REM PRINT TOPPER
100 Write(6,110)
110 Format(1X,’Highest score obtained by’)
Write(6,120) MaxRegno,MaxName
120 Format(1X,A5,1X,A16)
Write(6,160) MaxMarks
160 Format(1X,’with Maximum Marks =’,F6.2)
Write(6,130) MaxTest1,MaxTest2,MaxTest3,MaxFinal
130 Format(1X,’where tests and final marks are’,4F6.2)
CLOSE(5)
CLOSE(6)
STOP
END

Input data file name : MARKFOR.DAT

CS/01 C. V. Rajan 12.0 25.0 21.0 35.0 81.0


CS/02 B. X. Roy 25.0 7.0 23.0 29.0 77.0
CS/03 P. C. Sasikumar 10.0 27.0 7.0 36.0 73.0
CS/04 B. D. Box 26.0 26.0 26.0 35.0 87.0
CS/05 K. K. Mukherjee 29.0 0.0 23.0 30.0 82.0

Note: End-of-file marker is at the end of the last data line of the data file. (e.g.,
just after 0 of 82.0).
Output file name : MARKFOR.OUT

CS/01 C. V. Rajan 12.00 25.00 21.00 35.00 81.00


CS/02 B. X. Roy 25.00 7.00 23.00 29.00 77.00
CS/03 P. C. Sasikumar 10.00 27.00 7.00 36.00 73.00
76 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

CS/04 B. D. Box 26.00 26.00 26.00 35.00 87.00


CS/05 K. K. Mukherjee 29.00 .00 23.00 30.00 82.00
Highest score obtained by
CS/04 B. D. Box
with Maximum Marks = 87.00
where tests and final marks are 26.00 26.00 26.00 35.00

(c) PASCAL Programming


Turbo PASCAL program for this problem.
Program file name : MARKAS.PAS

{***********************************************
* Pascal program for Marks computation *
***********************************************}
Program MarksComputation;
Type
MarkRec = record
RegNo : string[5]; {Regn number of a student}
Name : string[16]; { Name of a students}
Test1 : real; {Marks of test 1}
Test2 : real; {Marks of test 2}
Test3 : real; {Marks of test 3}
Final : real; {Marks of Final }
end;
Var
Bt1 : MarkRec;
MaxRegNo : string[5];
MaxName : string[16];
MaxMarks,MaxTest1,MaxTest2,MaxTest3,MaxFinal : real;
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 77

minimum_of_tests, CompositeMarks : real;


MarksInputFile, MarksOutputFile: text;
begin{Main}
Assign(MarksInputFile,’MarkPas.dat’);
Reset(MarksInputFile);
Assign(MarksOutputFile,’MarkPas.Out’);
Rewrite(MarksOutputFile);
MaxMarks := 0;
MaxRegNo := ’ ’;
MaxName := ’ ’;
MaxTest1 := 0;
MaxTest2 := 0;
MaxTest3 := 0;
MaxFinal := 0;
While (not eof(MarksInputFile)) do
begin
Readln(MarksInputFile,bt1.RegNo, bt1.Name,
bt1.Test1, bt1.Test2, bt1.Test3, bt1.Final);
minimum_of_tests := bt1.test1;
if(minimum_of_tests > bt1.test2)
then minimum_of_tests := bt1.test2;
if(minimum_of_tests > bt1.test3)
then minimum_of_tests := bt1.test3;
CompositeMarks := bt1.test1+bt1.test2
+bt1.test3+bt1.final;
CompositeMarks:=CompositeMarks-minimum_of_tests;
If(MaxMarks < CompositeMarks) then
78 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

begin
MaxMarks := CompositeMarks;
MaxRegNo := bt1.RegNo;
MaxName := bt1.Name;
MaxTest1 := bt1.test1;
MaxTest2 := bt1.test2;
MaxTest3 := bt1.test3;
MaxFinal := bt1.final;
end;
write(MarksOutputFile,bt1.RegNo,’ ’,bt1.Name);
write(MarksOutputFile,,’ ’,bt1.Test1:7:2);
write(MarksOutputFile,bt1.Test2:7:2,bt1.Test3:7:2);
write(MarksOutputFile,CompositeMarks:8:2);
writeln(MarksOutputFile);
end;
writeln(MarksOutputFile,’Highest score obtained’);
write(MarksOutputFile,MaxRegNo,’ ’,
MaxName,’ ’,MaxTest1:7:2);
write(MarksOutputFile,MaxTest2:7:2,
MaxTest3:7:2,MaxMarks:8:2);
writeln(MarksOutputFile);
close(MarksInputFile); close(MarksOutputFile);
end.

A sample input and out files for this Pascal program are given below.

Input data file name : MARKPAS.DAT


CS/01 C. V. Rajan 12.0 25.0 21.0 35.0 81.0
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 79

CS/02 B. X. Roy 25.0 7.0 23.0 29.0 77.0


CS/03 P. C. Sasikumar 10.0 27.0 7.0 36.0 73.0
CS/04 B. D. Box 26.0 26.0 26.0 35.0 87.0
CS/05 K. K. Mukherjee 29.0 0.0 23.0 30.0 82.0
ˆz
Output file name : MARKPAS.OUT
CS/01 C. V. Rajan 12.00 25.00 21.00 81.00
CS/02 B. X. Roy 25.00 7.00 23.00 77.00
CS/03 P. C. Sasikumar 10.00 27.00 7.00 73.00
CS/04 B. D. Box 26.00 26.00 26.00 87.00
CS/05 K. K. Mukherjee 29.00 0.00 23.00 82.00
Highest score obtained
CS/04 B. D. Box 26.00 26.00 26.00 87.00

(d) Work-Sheet Method


A work-sheet file, MARKS.XLS, for the problem 2 is given below. This work-
sheet is shown into two parts: the first part from column A to H and the second
part from column I to column K for the rows 10 to 19. A sample output is also
shown below.
Work-sheet file name: MARKS.XLS
80 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

AB C D E F G H
10 Reg. Name of Test Test Test Final
11 No Students 1 2 3
12
13 CS/01 C. V. Rajan 12 25 21 35
14 CS/02 B. X. Roy 25 7 23 29
15 CS/03 P. C. Sasikumar 10 27 7 36
16 CS/04 B. D. Box 26 26 26 35
17 CS/05 K. K. Mukherjee 29 0 23 30
18
19 Maximum composite score:
Work-sheet file name: MARKS.XLS (continue)
I J K
10 Min. Comp- Topper
11 of 3 osite
12 tests score
13 @MIN(E13:G13) @SUM(E13:H13)-I13 @IF(J13 = $J$19,1,0)
14 @MIN(E14:G14) @SUM(E14:H14)-I14 @IF(J14 = $J$19,1,0)
15 @MIN(E15:G15) @SUM(E15:H15)-I15 @IF(J15 = $J$19,1,0)
16 @MIN(E16:G16) @SUM(E16:H16)-I16 @IF(J16 = $J$19,1,0)
17 @MIN(E17:G17) @SUM(E17:H17)-I17 @IF(J17 = $J$19,1,0)
18
19 @MAX(J13:J17)

Sample output:
Reg. Name of Test Test Test Final Min. Comp- Topper
No Students 1 2 3 of 3 osite
tests score
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 81

CS/01 C. V. Rajan 12 25 21 35 12 81 0
CS/02 B. X. Roy 25 7 23 29 7 77 0
CS/03 P. C. Sasikumar 10 27 7 36 7 73 0
CS/04 B. D. Box 26 26 26 35 26 87 1
CS/05 K. K. Mukherjee 29 0 23 30 0 82 0
Maximum composite score: 87

(e) FoxPro/Dbase Programming


A Dbase or Foxpro program (MARKS.PRG) and the file structure (mark1.dbf)
for problem 2 are given below:

Structure for table: MARK1.DBF


Number of data records: 5
Date of last update: 02/08/03
Code Page: 0
Field Field Name Type Width Dec Index Collate
1 REGNO Character 5
2 NAME Character 16
3 TEST1 Numeric 5 1
4 TEST2 Numeric 5 1
5 TEST3 Numeric 5 1
6 FINAL Numeric 5 1
** Total ** 42
Program file name : MARKS.PRG
************************************************
* Dbase or Foxpro program for Marks computation*
************************************************
set talk off
set heading off
clear
82 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

clear all
clear gets
select 1
use mark1.dbf
MaxMarks= final
MaxRegNo = regno
MaxName = Name
MaxTest1 = test1
MaxTest2 = test2
MaxTest3 = test3
MaxFinal = final
do while .not. eof()
minimum_of_tests = test1
if minimum_of_tests > test2
minimum_of_tests = test2
endif
if minimum_of_tests > test3
minimum_of_tests = test3
endif
CompositeMarks=test1+test2+test3+final
CompositeMarks=CompositeMarks-minimum_of_tests
If MaxMarks < CompositeMarks
MaxMarks = CompositeMarks
MaxRegNo = regno
MaxName = Name
MaxTest1 = test1
MaxTest2 = test2
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 83

MaxTest3 = test3
MaxFinal = final
endif
?Regno,name,test1,test2,test3,Final,CompositeMarks
skip
enddo
? "Highest score obtained"
?MaxRegno,MaxName,Maxtest1,Maxtest2,Maxtest3,MaxFinal
?MaxMarks
close all
return

Results: LIST
1 CS/01 C. V. Rajan 12.0 25.0 21.0 35.0
2 CS/02 B. X. Roy 25.0 7.0 23.0 29.0
3 CS/03 P. C. Sasikumar 10.0 27.0 7.0 36.0
4 CS/04 B. D. Box 26.0 26.0 26.0 35.0
5 CS/05 K. K. Mukherjee 29.0 0.0 23.0 30.0
OUTPUT
CS/01 C. V. Rajan 12.0 25.0 21.0 35.0 81.0
CS/02 B. X. Roy 25.0 7.0 23.0 29.0 77.0
CS/03 P. C. Sasikumar 10.0 27.0 7.0 36.0 73.0
CS/04 B. D. Box 26.0 26.0 26.0 35.0 87.0
CS/05 K. K. Mukherjee 29.0 0.0 23.0 30.0 82.0
Highest score obtained
CS/04 B. D. Box 26.0 26.0 26.0 35.0 87.0
(f) C Program
A C program (MARKS.C) for problem 2 with a sample input and output is
84 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

given below.
Program file name : MARKS.C
struct std
{
char rollno[6],name[16];
float test1,test2,test3,final,composite;
}s,stemp;
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int i;
float sm,min,smtemp;
clrscr();
fp=fopen("MarksC.dat","r");
smtemp=0;
printf("\nRoll No\tName \tTest1\tTest2\tTest3\tFinal\tComposite");
printf("\n-------\t---- \t-----\t-----\t-----\t-----\t---------");
do
{
fscanf(fp,"%s%s%f",s.rollno,s.name,&s.test1);
fscanf(fp,"%f%f%f\n",&s.test2,&s.test3,&s.final);
min=s.test1;
sm=s.test1+s.test2+s.test3+s.final;
if(min>s.test2)
min=s.test2;
if(min>s.test3)
min=s.test3;
sm=sm-min;
if(smtemp<sm)
{
strcpy(stemp.rollno,s.rollno);
strcpy(stemp.name,s.name);
stemp.test1=s.test1;
stemp.test2=s.test2;
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 85

stemp.test3=s.test3;
stemp.final=s.final;
smtemp=sm;
}
printf("\n%s\t%s \t%.1f\t%.1f",s.rollno,s.name,s.test1,s.test2);
printf("\t%.1f\t%.1f\t%.1f",s.test3,s.final,sm);
}while(!feof(fp));
printf("\n\nThe Record having the highest Composite value is:=>");
printf("\n=====================================================");
printf("\nROLLNO\tNAME \tTEST1\tTEST2\tTEST3\tFINAL\tCOMPOSITE");
printf("\n******\t****** \t*****\t*****\t*****\t*****\t*********");
printf("\n%s\t%s \t%.1f\t",stemp.rollno,stemp.name,stemp.test1);
printf("%.1f\t",stemp.test2);
printf("%.1f\t%.1f\t%.1f\n",stemp.test3,stemp.final,smtemp);
fclose(fp);
getch();
}

Results

Data file name : MarksC.dat


CS/01 C.V.Rajan 12.0 25.0 21.0 35.0
CS/02 B.X.Roy 25.0 7.0 23.0 29.0
CS/03 P.C.Sasikumar 10.0 27.0 7.0 36.0
CS/04 B.D.Box 26.0 26.0 26.0 35.0
CS/05 K.K.Mukherjee 29.0 0.0 23.0 30.0

OUTPUT
Roll No Name Test1 Test2 Test3 Final Composite
------- ---- ----- ----- ----- ----- ---------
CS/01 C.V.Rajan 12.0 25.0 21.0 35.0 81.0
CS/02 B.X.Roy 25.0 7.0 23.0 29.0 77.0
CS/03 P.C.Sasikumar 10.0 27.0 7.0 36.0 73.0
CS/04 B.D.Box 26.0 26.0 26.0 35.0 87.0
CS/05 K.K.Mukherjee 29.0 0.0 23.0 30.0 82.0

The Record having the highest Composite value is:=>


=====================================================
86 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

ROLLNO NAME TEST1 TEST2 TEST3 FINAL COMPOSITE


****** ****** ***** ***** ***** ***** *********
CS/04 B.D.Box 26.0 26.0 26.0 35.0 87.0

(g) C++ Program

A C + + program (MARKS.CPP) for problem 2 with a sample input and out-


put is given below.

Program file name : MARKS.CPP


#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
#define n 4
class inventory
{
public:
char rollno[6];
char name[16];
float test1;
float test2;
float test3;
float final;
float composite;
void writedata();
void readdata();
void getcompose();
};
void inventory::getcompose()
{ float mintest=test1;
if(mintest>test2)
mintest=test2;
if(mintest>test3)
mintest=test3;
composite=final+test1+test2+test3-mintest;
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 87

}
void inventory::readdata()
{
cout<<"\n Enter RollNo.=>";
cin>>rollno;
cout<<"\n Enter Name=>";
cin>>name;
cout<<"\n Enter Mark for Test 1:=>";
cin>>test1;
cout<<"\n Enter Mark for Test 2:=>";
cin>>test2;
cout<<"\n Enter Mark for Test 3:=>";
cin>>test3;
cout<<"\n Enter Final Mark:=>";
cin>>final;
}
void inventory::writedata()
{
cout<<"\n"<<rollno
<<"\t"<<name
<<"\t"<<test1
<<"\t"<<test2
<<"\t"<<test3
<<"\t"<<final
<<"\t"<<composite;
}
int main()
{
inventory item[n];
int i,j=0;float comp[30];
for(i=0;i<n;i++)
{
item[i].readdata();
item[i].getcompose();
}
cout<<"\n output\n";cout<<"\nRollNo."<<"\tName"<<"\tTest1";
88 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

cout<<"\tTest2";
cout<<"\tTest3"<<"\tFinal"<<"\tComposite";
for(i=0;i<n;i++)
{
comp[i]=item[i].composite;
item[i].writedata();
}
float topper=comp[0];
for(i=1;i<n;i++)
{
if(comp[i]>topper)
{
topper=comp[i];
j=i;
}
}
cout<<"\n Highest marks obtained by\n";
item[j].writedata();
return 0;
}

Results
INPUT:
Enter RollNo.=>BT01
Enter Name=>A.K.DAS
Enter Mark for Test 1:=>25
Enter Mark for Test 2:=>34
Enter Mark for Test 3:=>32
Enter Final Mark:=>40
Enter RollNo.=>BT02
Enter Name=>B.K.DUTTA
Enter Mark for Test 1:=>21
Enter Mark for Test 2:=>26
Enter Mark for Test 3:=>30
Enter Final Mark:=>36
Enter RollNo.=>BT03
Enter Name=>K.R.RAO
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 89

Enter Mark for Test 1:=>35


Enter Mark for Test 2:=>21
Enter Mark for Test 3:=>34
Enter Final Mark:=>31
Enter RollNo.=>BT04
Enter Name=>K.B.BANARJEE
Enter Mark for Test 1:=>23
Enter Mark for Test 2:=>12
Enter Mark for Test 3:=>0
Enter Final Mark:=>12
OUTPUT:
RollNo. Name Test1 Test2 Test3 Final Composite
BT01 A.K.DAS 25 34 32 40 81
BT02 B.K.DUTTA 21 26 30 36 71
BT03 K.R.RAO 35 21 34 31 79
BT04 K.B.BANARJEE 23 12 0 12 47
Highest marks obtained by
BT01 A.K.DAS 25 34 32 40 81
Press any key to continue

(h) COBOL Program


A COBOL program (MARKS.COB) for problem 2 with a sample input and
output is given below.
Program file name : MARKS.COB
*******8**1********0*********0*********0*********0****
IDENTIFICATION DIVISION.
PROGRAM-ID. SCORE-COMPUTATION.
AUTHOR. AUTHORS.
DATE-WRITTEN. 22-04-03.
DATE-COMPILED.
SECURITY. AUTHORS.
*******************************************
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.
INPUT-OUTPUT SECTION.
90 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

FILE-CONTROL.
SELECT SCORE-FILE ASSIGN TO DISK
ORGANIZATION IS SEQUENTIAL
ACCESS MODE IS SEQUENTIAL.
*******************************************
DATA DIVISION.
FILE SECTION.
FD SCORE-FILE
LABEL RECORDS ARE STANDARD
VALUE OF FILE-ID IS ’SCORE.OUT’
DATA RECORD IS PRINT-REC.
01 PRINT-REC PIC X(60).
WORKING-STORAGE SECTION.
01 MARKS-REC.
05 M-REG-NO PIC X(6).
05 M-NAME PIC X(16).
05 M-TEST1 PIC 9(3)V9.
05 M-TEST2 PIC 9(3)V9.
05 M-TEST3 PIC 9(3)V9.
05 M-FINAL PIC 9(3)V9.
01 MAX-SCORE-REC.
05 MX-REG-NO PIC X(6).
05 FILLER PIC X(2).
05 MX-NAME PIC X(16).
05 FILLER PIC X(2).
05 MX-TEST1 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 MX-TEST2 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 MX-TEST3 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 MX-FINAL PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 MX-SCORE PIC Z(3).9.
05 FILLER PIC X(7).
01 SCORE-REC.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 91

05 S-REG-NO PIC X(6).


05 FILLER PIC X(2) VALUE SPACES.
05 S-NAME PIC X(16).
05 FILLER PIC X(2) VALUE SPACES.
05 S-TEST1 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 S-TEST2 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 S-TEST3 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 S-FINAL PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 S-SCORE PIC Z(4).9.
05 FILLER PIC X(5) VALUE SPACES.
01 EOF-FLAG PIC X VALUE "Y".
01 MAX-SCORE PIC 999V9 VALUE 0.
01 X-REG-NO PIC X(6).
01 X-NAME PIC X(16).
01 X-TEST1 PIC 9(3)V9.
01 X-TEST2 PIC 9(3)V9.
01 X-TEST3 PIC 9(3)V9.
01 X-FINAL PIC 9(3)V9.
01 X-SCORE PIC 9(3)V9.
01 MIN-TEST PIC 9(3)V9 VALUE 0.
01 HEADER1.
02 FILLER PIC X(20) VALUE SPACES.
02 FILLER PIC X(6) VALUE "OUTPUT".
02 FILLER PIC X(34) VALUE SPACES.
01 HEADER2 PIC X(60) VALUE ALL "-".
01 HEADER3.
02 FILLER PIC X(6) VALUE "REG NO".
02 FILLER PIC X(8) VALUE SPACES.
02 FILLER PIC X(4) VALUE "NAME".
02 FILLER PIC X(8) VALUE SPACES.
02 FILLER PIC X(5) VALUE "TEST1".
02 FILLER PIC X(2) VALUE SPACES.
92 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

02 FILLER PIC X(5) VALUE "TEST2".


02 FILLER PIC X(2) VALUE SPACES.
02 FILLER PIC X(5) VALUE "TEST3".
02 FILLER PIC X(2) VALUE SPACES.
02 FILLER PIC X(5) VALUE "FINAL".
02 FILLER PIC X(2) VALUE SPACES.
02 FILLER PIC X(5) VALUE "SCORE".
02 FILLER PIC X VALUE SPACES.
01 HEADER4.
02 FILLER PIC X(12) VALUE SPACES.
02 FILLER PIC X(13) VALUE "MAXIMUM SCORE".
02 FILLER PIC X(35) VALUE SPACES.
***********************************************************
PROCEDURE DIVISION.
START-PARA.
OPEN OUTPUT SCORE-FILE.
PERFORM HEADING-OF-TABLE-1.
PERFORM PROCESS-PARA UNTIL EOF-FLAG = ’N’.
WRITE PRINT-REC FROM HEADER2.
PERFORM HEADING-MAXIMUM.
WRITE PRINT-REC FROM MAX-SCORE-REC.
WRITE PRINT-REC FROM HEADER2.
CLOSE SCORE-FILE.
STOP RUN.
HEADING-OF-TABLE-1.
WRITE PRINT-REC FROM HEADER1.
WRITE PRINT-REC FROM HEADER2.
WRITE PRINT-REC FROM HEADER3.
WRITE PRINT-REC FROM HEADER2.
HEADING-MAXIMUM.
WRITE PRINT-REC FROM HEADER4.
WRITE PRINT-REC FROM HEADER2.
WRITE PRINT-REC FROM HEADER3.
WRITE PRINT-REC FROM HEADER2.
PROCESS-PARA.
DISPLAY "ENTER MARKS:".
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 93

DISPLAY "Reg. No.:".


ACCEPT M-REG-NO.
DISPLAY "Name:".
ACCEPT M-NAME.
DISPLAY "Test 1:".
ACCEPT M-TEST1.
DISPLAY "Test 2:".
ACCEPT M-TEST2.
DISPLAY "Test 3:".
ACCEPT M-TEST3.
DISPLAY "Final:".
ACCEPT M-FINAL.
MOVE M-REG-NO TO S-REG-NO.
MOVE M-NAME TO S-NAME.
MOVE M-TEST1 TO X-TEST1, MIN-TEST, S-TEST1.
MOVE M-TEST2 TO X-TEST2, S-TEST2.
MOVE M-TEST3 TO X-TEST3, S-TEST3.
MOVE M-FINAL TO X-FINAL, S-FINAL.
IF MIN-TEST > M-TEST2
MOVE M-TEST2 TO MIN-TEST.
IF MIN-TEST > M-TEST3
MOVE M-TEST3 TO MIN-TEST.
COMPUTE X-SCORE=X-TEST1 + X-TEST2 + X-TEST3 + X-FINAL.
COMPUTE X-SCORE=X-SCORE - MIN-TEST.
MOVE X-SCORE TO S-SCORE.
IF MAX-SCORE < X-SCORE
MOVE SCORE-REC TO MAX-SCORE-REC
MOVE X-SCORE TO MAX-SCORE.
MOVE SCORE-REC TO PRINT-REC.
WRITE PRINT-REC.
DISPLAY "Continue ....(Y/N):".
ACCEPT EOF-FLAG.

Results
INPUT
CS/01 C. V. Rajan 0012 0025 0021 0035 0081
CS/02 B. X. Roy 0025 0007 0023 0029 0077
94 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

CS/03 P. C. Sasikumar 0010 0027 0007 0036 0073


CS/04 B. D. Box 0026 0026 0026 0035 0087
CS/05 K. K. Mukerjee 0029 0000 0023 0030 0082

The COBOL program, MARKS.COB is compiled using Microsoft COBOL


Compiler as given below:
C:\COBOL>COBOL MARKS

Microsoft COBOL Compiler


Version 2.20 (C)Copyright Microsoft Corp. 1982-87

Object filename [MARKS.INT]:


Listing filename [NUL.LST]:

** Scanning Environment Division...


** Scanning Data Division...
** Compiling Procedure Division...
** Generating Object Code...

No errors or warnings

Data area size = 1018


Code area size = 824

After compilation the program is run by the following instruction.


C:COBOL>RUNCOB MARKS
ENTER MARKS:
Reg. No.:
CS/01
Name:
C. V. Rajan
Test 1:
12
Test 2:
25
Test 3:
21
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 95

Final:
35
Continue ....(Y/N):
Y
...
...
....
Continue ....(Y/N):
Y
ENTER MARKS:
Reg. No.:
CS/05
Name:
K. K. Mukerjee
Test 1:
29
Test 2:
0
Test 3:
23
Final:
30
Continue ....(Y/N):
N
C:\COBOL>

Output file : SCORE.OUT


< OUTPUT
<------------------------------------------------------------
<REG NO NAME TEST1 TEST2 TEST3 FINAL SCORE
<------------------------------------------------------------
<CS/01 C. V. Rajan 12.0 25.0 21.0 35.0 81.0
<CS/02 B. X. Roy 25.0 7.0 23.0 29.0 77.0
<CS/03 P. C. Sasikumar 10.0 27.0 7.0 36.0 73.0
<CS/04 B. D. Box 26.0 26.0 26.0 35.0 87.0
<CS/05 K. K. Mukerjee 29.0 .0 23.0 30.0 82.0
<------------------------------------------------------------
96 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES

<MAXIMUM SCORE
<------------------------------------------------------------
<REG NO NAME TEST1 TEST2 TEST3 FINAL SCORE
<------------------------------------------------------------
<CS/04 B. D. Box 26.0 26.0 26.0 35.0 87.0
<------------------------------------------------------------
Chapter 3
SIMPLE PROGRAMMING PROBLEMS

Basic programming concept is to convert mathematical expressions with stan-


dard programming notations. In this chapter, a set of mathematical and logical
expressions, equations and simple programming problems have considered
for implementation using conventional programming languages (e.g., FOR-
TRAN, BASIC, PASCAL, C, C++ etc.).

1. Write down the following mathematical expressions using a conventional


programming language (e.g., FORTRAN/ BASIC/ COBOL /PASCAL /PL-
1 /ALGOL /C/C++ etc).

(1) 1 + ax2 + bx5 .


(x + y − z + u)2
(2) .
2a
(3) x2 + y3 /(−z) + 104 .
ax + b
(4) .
cx − d
(5) (a/b)n−1 + uv .
(6) a(−x).
(7) a−n + b−n .
1
(8) c p+z + (b2 + c2 ) 2 + a−p .
(9) 74 + (−17)−7 + x−a .
(10) π r2 + 2π rh.
4 3
(11) πr .
3
(12) ne/l + L. 
x+y n

a d
(13) + − .
bc e f g u−v

97
98 CHAPTER 3. SIMPLE PROGRAMMING PROBLEMS

(14) n
x + y.
(15) ||i| + | j||.
(16) ae−kt .
t i −µ t
(17) e .
i!  2
1 x−m

(18) √
1
e 2 . σ
2πσ
(19) T + t log(Vcc − K(VD +V0 ) + 1).
√4
(20) cos(x) + e 3 sin(π x).
2
sin(x) + | tan−1 t|e−x .
p
(21)
p
(22) cos p+1 (t) + loge x2 + y2 .
q
1 2
(23) R2 + (W L − WC ) .
WL
(24) √ .
2 L2 − a2
p
(25) s(s − a)(s − b)(s − c).
−x
e + ex
(26) .
2
(27) K cosh(x/a).
1
(28) .
2( fs / fc )(1 +rfs /n fc )
1
(29) 200, 000, 000 1− 2
.
(1 + 0.00000195V
√ )
(30) 2.5 log10 x + cos 320 + |x2 − y2 | + 2xy + cot−1 y.

2. Write down an arithmetic assignment statement for each of the following


formula, where letters in the formulae are used as variable names for pro-
gramming.

(1) v = u + f t.
(2) s = ut + 12 f t 2 .
(3) v2 = u2 + 2 f s.
(4) P = m f .
(5) α = 4/x + 7/y − z.
p
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 99

3
(6) β = 2x2 /(x2 + y2 ) 2 .
(7) V = 43 π r3 .
(8) A = π r2 .
(9) Area = 2π r sin(π /p).
(1 − x)/(1 + x)
(10) τ = .
(1 + y)/(1 − y)
(11) u = gD2 (βs − β )/(18µ ).
(12) Power = 2.9 × 10−5 (1.0 + 0.7854LD2 /V0 )LD2 R.
y2
(13) β = 3.
(1 + y21 ) 2  
20x
(14) ε = 57.29578tan −1
2 + 300
.
x
√ √
(15) Z = e 2 sin(x)/ 2ax.
(16) k = ||m| − |n||.
1 1 1 1 1
(17) e = 1 + + + + + .
1! 2! 3! 4! 5!
t t t2 t3
(18) e = 1 + + + .
p1! 2! 3!
(19) p = mv/ 1 − (v/c)2 .
q
(20) β = 2 (βx + βy ) + 12 (βy − βx )2 + g2xy .
1

(21) κ = ((s1 − s2 )2 + (s2 − s3 )2 + (s3 − s1 )2 ).
(22) ε = 100(1 − µ S)/(S + µ ).
(23) β = EI/(EI + P0 + I 2 R).
3
(24) H = 2π Ia2 /(a2 + x2 ) 2 .
 3
1+x 2
(25) Period = K .
1 − e
x2 y2
 
M
(26) Ω = 1− 2 − 2 .
π ab a b
2 √ 3
(27) q = 3 C 2gBH 2 .
(28) S = 16PR/(π d 3 )(1 + d/(4R)).
(29) β = 9.118/(1/N 2 − 1/M 2 ).
(30) ε = arctan[2τxy /(βx − βy )].
100 CHAPTER 3. SIMPLE PROGRAMMING PROBLEMS

(31) Current = leakage(e350 − 1).


(32) t = (x/y + 1)n + (1 − x/y)m .
(33) Ω = sin3 (x) cos(2y)
p
 + 3 cos(x).
1 1 1
(34) v = 3 2π 2 Me4 2 − 2 .
h n2 n1  
1 a
  1  a 2 1  a  1
(35) CN = 1 + + − −1
2  b 6 b 2 b b  
1 1 1 3 a 1 2 a 1
−β − +1 + β − β −1 .
2 b 3 b 2 b b
(36) b = (e−β + β )−1 .
t
(37) y = abc .

3. Write down each of the following logical expression or condition using a


programming language.

(1) X = A OR B.
(2) X = A AND B.
(3) X = NOT A.
(4) X = A NOR B.
(5) X = A NAND B.
(6) X = A XOR B.
(7) X = (Age < 15 AND Mental 6= Normal).
(8) X = Alive AND ((Age < 15 AND Mental = Normal) OR (Age ≥ 15
AND Status = Unmarried) OR Mental = Abnormal).
(9) P1 = P1 AND (A = 1) AND (2 < B < 6) AND (P2 AND P4 AND P6
OR P4 AND P6 AND P8 ),
where P1 , P2 , P3 , P4 , P5 , P6 , P7 and P8 are Boolean variables and A, B are
integer variables.
(10) Admit to the course = (Qualification ≥ Graduate) AND (Math at
graduate level) AND (Test1 Marks > 40) AND (Test2 Marks > 40) AND
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 101

((Test3Marks > 60) OR (Test2 Marks > 80)) AND (Typing speed ≥ 25)
AND (Age ≤ 30).

4. Write a program to determine the value of C by the following formula:


1 1
C = 1 + a + a2 , where a = 0.817.
2 6
5. Write a program to determine the value of C by the following formula:
1 N − 1 1 (N − 1)(N − 2)
C = 1+ + ,
2 M 6 M2
where N = 817 and M = 1000.
6. Write a program to determine the value
 of C N by the following formula:
1  a  1  a 2 1  a  1
CN = 1 + + − −1
2 b 6 b 2 b b   
1 1 1 3 a 1 2 a 1
−β − +1 + β − β −1 .
2 b 3 b 2 b b
1
where, = e−β + β for a = 0.817 and β = 2.
b
7. The ideal compressor outlet temperature and efficiency for a gas turbine are
 g − 1  g − 1
P2 g and e = 1 − P2 g , where T is the inlet
given by: T = T0 0
P1 P1
temperature, P1 is the outlet pressure, and g is the ratio of specific heats.
Write a program to compute T and e for T0 = 450, P1 = 10, P2 = 55 and
g = 1.5.
8. Internal volume (V) of a cylinder is 0.005m3 and it contains oxygen at a
pressure (P), 500Kg f /cm2 and at a temperature (T), 300o K (T). Write a
program to find the mass (m) of oxygen contained in the cylinder and the
capacity of the pressure vessel to contain this mass of oxygen at one physical
atmosphere (1.03Kg f /cm2 ) and at 293o K. The gas constant R for oxygen is
26.5Kg f /kgo K. [Hints: Gas equation PV = nRT ] [Ans: 3.14Kg, 2.365m3 ]
9. Write a program to calculate Cp and Cv given by the relations:
 β −1
T1 V2
(1) = ,
T2 V1
102 CHAPTER 3. SIMPLE PROGRAMMING PROBLEMS

Cp
(2) = β,
Cv
1
(3) W = nR(T1 − T2 ),
β −1
(4) Cp −Cv = R/J, and
(5) T1 = 273 + t1 , T2 = 273 + t2

where, T1 , T2 are temperatures in o K;V1 ,V2 are volumes, R = gas constant, J


= 427Kgf m/K.cal. Test the program using the following data, m = 0.45Kg,
t1 = 179oC, V3 = 3m3 , V1 = 1m3 , t2 = 15.5oC, W = 5300Kg f /m. [Ans:
Cp = 0.2382,Cv = 0.1693]
10. Integers I and J are given. Draw a flowchart and write a program to find the
quotient and remainder when I is divided by J.
11. A computer false floor designer is making a computer false floor of wide
W units and length L units with the wooden tiles of square size of sides s
units. How many tiles are required to complete it optimally. Assume that no
broken tiles are available in the market.
12. Read a number x and write a program to compute the function y(x) defined
as 
 15x + 7.4, if x ≤ 4.5,
y=
 17x + 1.6, if x > 4.5.
13. Read a number x and write a program to compute the function y(x) defined
as 
3
 3x + 5x , if 4.3 < x ≤ 9.1,


y = 6x + 8x2 , if 9.1 < x < 15.5,


0, otherwise.

Chapter 4
PROGRAMMING EXPRESSIONS AND
EQUATIONS

In this chapter, a set of mathematical problems is considered for the beginner.


These problems create some simple ideas, so that one can build up very sim-
ple logic for the computation of mathematical expressions, equations and def-
initions. Any conventional programming language helps to implement these
ideas.

1. Suppose a = 5.0. Write separate program to evaluate each of the following


expressions.
1
(1) a + .
1
1+
1+a
(2) (a) + an am , for n = 4 and m = 12 .
mn
 a m−1
(3) 3+ , for b = 4
b
3a2 + a3
(4) , for b = 4.
ab + a  
b2 a2 ab
(5) (a + b ) a + b + , given b = 2.2.
a+b
1 bc ab + bc + ca
(6) abc + + + , for b = 2, c = 3.15.
ab ab + bc a+b+c
abc
(7) | sin(a − |b|)|, for b = −2.5.
(8) cos(log(3a + b)), for b = 4.5.

2. Write a program that calculate the final velocity v and distance traversed d
by an automobile having a constant acceleration f for t seconds.
The formulae are v = f t and d = 21 f t 2 . Input f and t. Output t and v (choice
approximate input/output formats).

103
104 CHAPTER 4. PROGRAMMING EXPRESSIONS AND EQUATIONS

3. Assume a1 b2 −a2 b1 6= 0, the solution of two linear equations: a1 x+b1 y = c1


b2 c1 − b1 c2 a1 c2 − a2 c1
and a2 x − b2 y = c2 is given by: x = and y = . Write
a1 b2 − a2 b1 a1 b2 − a2 b1
a program that reads values of a1 , b1 and c1 for one equation in one line and
a2 , b2 and c2 for another equation in the second line. Calculate and print the
solution pair x, y, choose appropriate input/output format.
4. Solve the following:

(a) Read 3 numbers and print the largest and the smallest among them.
(b) Modify (a) above to print all the 3 numbers in ascending or descending
order.
(c) Read 2 numbers, exchange them and print them.
(d) Find the maximum and/or the minimum of a given set of integers as:
(1) Read an integer.
(2) Keep a temporary maximum and/or a minimum.
(3) If more numbers are left, go to step 1.
(4) Print the maximum and/or the minimum.

5. Two numbers n1 and n2 are relatively prime if they do not have any common
factor. Write a program to test, whether two given numbers are relatively
prime.
6. Write a program to compute the HCF of three given positive integer num-
bers.
7. Write a program to compute the LCM of three given positive integer num-
bers.
8. Write a program for each of the following problems.

(1) Find the largest among four given numbers.


(2) Find the total of odd and even integers (separately) from the given set
of 10 integers.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 105

(3) A Fibonacci sequence is defined as follows:


The first and second term in the sequence are 1 and 1 respectively. The
third and the subsequent terms in the sequence are formed by adding the
preceding two terms in the sequence. Find all numbers in the Fibonacci
sequence less than 300.
(4) Co-ordinates of n points are given in a plane. Find the number of points
in each of the four quadrants in the plane.
(5) The roll number and the marks obtained (in a subject) of n students are
given. Find the grade obtained by each student. Also find, the maximum
and average marks obtained by the students. [Note: You need not store the
supplied roll numbers and marks in array.]
x2 x3
(6) Find the value of y from the following series. y = −x + − +
n
2! 3!
x
· · · (−1)n . The values of n and x will be supplied as input.
n!
n n
9. Let Sn = ∑ i and Cn = ∑ i3. Write a program to compute Sn and Cn for
i=1 i=1
n = 1, 2, · · · , 10 and verify the relation Cn = Sn2 .
n
10. Let S(x) = ∑ xi /i!, where x is a real number and n is an integer. Write a pro-
i=1
gram to find the minimum n for which |S(x) − exp(x)| < 0.001 for a given x.
Suggest a method for the computation of exponential of x (i.e. ex or exp(x))
using the above series. Hence compute the following:
n 2i n 2i+1
ix i x
cos(x) : Using S(x) = 1+ ∑ (−1) . sin(x) : Using S(x) = ∑ (−1) .
i=1 2i i=0 2i + 1
n!
11. Write a program or a function for the computation nCr = for a
(n − r)!r!
given values of n and r (< n).
n
12. Write a program to compute the following function S(x, y) = ∑ nCixiyn−i,
i=0
where x and y are real numbers, and n is a positive integer. For any given x,
y and n numerically verify that S(x, y) = (x + y)n .
106 CHAPTER 4. PROGRAMMING EXPRESSIONS AND EQUATIONS

13. Write a program to search a particular element (known as key variable) from
a given array. If the key variable is in the array then print its position. If it is
not present in the array then report that the key variable is not found.
This program will first read an array of integers and then it should ask for the
key variable from the user. The program should search for the key variable
and find its position. Assume the array is an one dimensional array. [Hints:
Read an element and compare with the key variable.]
14. The transpose of a matrix A is obtained by interchanging the rows and
columns of A. Write a program that reads a matrix and print out its trans-
pose.
15. Let X be a (n ×m) matrix, i.e. X = [xi j ]n×m and Y be another (m ×n) matrix,
i.e. Y = [yi j ]m×n . The product P of X and Y is (n × n) matrix whose element
P(i, j) is given by the sum of the products of the elements in row i of X with
m
the elements of column j of Y , i.e., P(i, j) = ∑ xik yk j .
k=1
Write a program that reads two matrices X and Y . This program also prints
the possibility of multiplication (that is, whether the number of rows of the
second matrix is equal to the number of columns of the first one). If possible
multiply the matrices and print their product in the matrix format along with
other matrices.
16. Sorting an array means arranging the array in ascending or descending order
of elements. For example, the ascending order of an array [5 3 4 2] will be [2
3 4 5]. Write a program which will read an array and sort it in the ascending
order. Modify the program to sort the array in descending order.
17. Read a character string and sort it. Print the sorted string in reverse order.
18. Read a character string, including blanks and print it by removing all blanks.
19. Read a string of characters and print the number of occurrences of an alpha-
bet say ‘E ′ in it.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 107

20. Read name, roll number, department and CGPA of each student in your class
and print them according to the following format
Column 2-10 15-45 50-60 65-70
Contents Roll Number Name Department CGPA
21. Read the name of students in your class and store them in an array. Write a
program to search whether a given student is enrolled in your class.
22. Read the name of students in your class and sort them according to lexico-
graphic ordering. Print the sorted names.
23. Read two character strings X and Y . Write a program to check whether Y is
a substring of X.
24. Write a function subprogram to find whether a given square matrix is sym-
metric.
25. Write a program that will read a three character word and print all combi-
nations of these three characters.
26. A house building contractor is calculating the quantities of rod required for
casting a slab of size W ft × L ft, and the distribution of rods is x inch
between the rods. Calculate the total length of the rod. Note that, rods are
selling by weight in the market. Size of the rod is φ D mm. Write a program
to calculate the total weight of rod require for the slab. [Assume: Standard
values of D (in mm) are 6, 8, 10, 12, 16, 20, 24,· · ·]
Chapter 5
SIMPLE COMPUTATIONAL PROGRAMMING
PROBLEMS

In this chapter a set of problems have considered for programming assign-


ments. These problems are based on mathematical and logical computations
for numeric and non-numeric values.

1. Read the values of a, b and c which are positive numbers and represent the
lengths of the sides of a triangle. Compute the semi-perimeter (s) and area
(△) of the triangle, using the formulae
s = 12 (a + b + c) and △ = s(s − a)(s − b)(s − c).
p

Print a, b and c on one line, and, s & △ on the next line.


2. Write a program to convert Fahrenheit temperature to Centigrade, also re-
C F−32
verse. [Hints: 5 = 9 ].
3. Write a program to convert pounds (lbs) to kilograms (Kg) and its reverse.
[Hints: 1lbs = 453.6gm]
4. Write a program to convert an amount given in pound, shillings, and pence
to rupees and paise (assume, 1pound = Rs.48.16). Print the answer to the
nearest paise.
5. Write a program to express a quantity in millimeters (mm) in meters (m),
centimeters (cm) and millimeters (mm).
6. Write a program to compute and print the values of the safe loading y for
r = 25,
 50, 75, · · · , 250, where


 17, 000 − 0.485r2 , for r ≤ 120
18, 000

y= , for r > 120.
 r 2
 1+


18, 000
109
110 CHAPTER 5. SIMPLE COMPUTATIONAL PROGRAMMING PROBLEMS

7. In a pipe, the dimensionless flow, f is a function of the dimensionless head,


n andthe dimensionless roughness, p as given by the definition.


 64n, if |n| < 31.3
 |n| − 30.3
, if 31.3 ≤ |n| < τ

2000 sgn(n)

f= ( τ − 31.3 !)
9.35


, if |n| ≥ τ .
 p
 sgn(n) |n| 1.14 + 4.6 loge p + p


|n|
 2
4000
where, τ =
1.14 + 4.6 loge (0.0133 + 0.95p)
Write a program that inputs a given pair of values of p and n. Prints p, n and
f on the same line.
8. The system of linear equations ax + by = c and dx + ey = f has
(1) No solution if ae − bd = 0, but a f − cd 6= 0 or b f − ce 6= 0;
(2) A unique solution if ae − bd 6= 0; and
(3) An infinite set of solutions if ae − bd = a f − cd = b f − ce = 0.
Write a program that reads the values of a, b, c, d, e and f , and print the
values of x and y.
9. Write a program to read the coefficients a, b and c of a quadratic equation:
ax2 + bx + c = 0 and write two roots which may be real or imaginary. Imag-
inary roots write in a readable format.
10. Solve the following:

(1) Mr. Ali deposits Rs.10,000/- in bank A. The bank gives simple interest
of 12% per annum. Write a program to determine the amount in Mr. Ali’s
account at the end of 5 years.
(2) Mr. Bagchi deposits Rs.10,000/- in bank B. The bank gives compound
interest of 10% annually. Write a program to determine the amount in Mr.
Bagchi’s account at the end of 5 years.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 111

(3) Mr. Gupta deposits Rs.10,000/- in bank C. The bank gives compound
interest of 8% compounded every three months. Write a program to de-
termine the amount in Mr. Gupta’s account at the end of 5 years.
(4) If the banks A, B and C change their interest rates to 15%, 12% and
9.5% respectively. What would be the balance in their accounts?

11. A company manufactures three products, Product1 (say, iron), Product2


(say, heater) and Product3 (say, fan). They give a discount of 10% on or-
ders for Product1 if the order is for Rs.5,000/- or more. The same discount
of 10% is given on Product2 orders of value Rs.2,000/- or more and on
Product3 orders for Rs.10,000/- or more. On all other orders they do not
give any discount. It is required to write a program which implements this
policy.
12. Write a program, to add the individual digits in a 5 digit integer number.
Also write a generalized program for n digits integer number. [Number =
25634, 2 + 5 + 6 + 3 + 4 = 20].
13. Write a program to print a given 7 digits integer number in reverse order.
(For example, the program prints the output 3218749 for the input 9478123).
14. Two one-dimensional arrays A and B have n elements each. Write a program
to compute the array C which is the sum of A and B.
15. Write a program that finds and prints the following: (1) the largest number,
and (2) the smallest number from a given set where the size of the set is
unknown.
16. There are n students in a class and the marks obtained by each student in
an examination is given as input. A computer program is required which
will point out the highest and the second highest marks obtained in the ex-
amination with given number of students, also print the roll numbers of the
students if the marks are given accordingly to the roll number.
112 CHAPTER 5. SIMPLE COMPUTATIONAL PROGRAMMING PROBLEMS

17. Write a program which interchanges the odd and even components of a
vector.
18. Write a program to compute the values of the function shown below for
e−aak
integral values of k = 0 to 15. p(k) = , a = constant.
k!
19. An airfoil is to be plotted with a camber or skewed foil. The mean line of
the foil
 is given by 2
−m(2px − x )
, for x ≤ p


2

y= p
m(1 + 2px − 2p − x2 )
, for x > p.


1 − p2

Write a program that reads a set of records, where each record contains the
values of m, x and p in a given format. This program should compute and
print the values of y. The exact number of input is not known.
20. Write a program to compute the binomial coefficient
nC = n! n(n − 1)...(n − r + 1)
r =
r!(n − r)! 1.2...r
for the given values of n and r.
21. Read the values of n and r, and find the sum (S) as given below.
n
S = ∑ ir . Print n, r and S.
i=1
22. Read the values of n and r,and find the sum (S) as given below.
n  i sin(i), for i ≤ r
S = ∑ Bi e , where, Bi =
i
i=1
 i2 cos(i), for i > r.
Print n, r and S.
x x x2 x3
23. A power series represents e = 1 + + + + · · ·. Write a program to
1! 2! 3!
x
evaluate e to 5 significant digits for a given x.
x3 x5 x7
24. A power series represents sin(x) = x − + − + · · ·. Write a program
3! 5! 7!
to evaluate sin(x) to three significant digits for the following values of x and
input the following quantities : x = 0.5 radians, x = -2.5 radians, x = 22.2
radians.

(1) x in radians,
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 113

(2) The number of terms used in the series to obtain the required accuracy,
(3) sin(x) as given by the built in library program, and
(4) The percentage error between your answer and that of the library pro-
gram.

25. Write a program for the computation of the series.


x2 x4 x6
J0 (x) = 1 − 2 + 4 − 6 +···
2 .1.1 2 .2!.2! 2 .3!.3!
by direct summation of successive terms. The error magnitude is less than
10−8 . Test the program to compute J0 (x) for a given value of x, say 0.75.
26. Write a program that computes and prints the sum S = ∑ k−p for k = 1,2,3,...
and p > 1, where the real number p is read as input. The summation should
k1−p
be stopped when < 10−8 .
p−1
27. Suppose A and B are two one-dimensional arrays where each array contains
n (< 100) elements. Write a program to compute and print the value of the
n
scaler product C = ∑ A(k).B(k).
k=1
28. Compute the scaler product of vectors x and y given by the formula S =
n
∑ xiyi, where n, x = (x1, x2, · · · , xn) and y = (y1, y2, · · · , yn) are the inputs.
i=1
29. Given a set of n points (x1 , y1 ), (x2 , y2), · · · , (xn , yn ) in a plane it is required
to fit a straight line y = mx + c by least square method which gives
n ∑ xi yi − ∑ xi ∑ yi 1
∑ yi − m ∑ xi

m= and c = .
n ∑ xi 2 − (∑ xi )2 n
Write a program to compute m and c from the given n and n-points (x1 , y1 ), (x2 , y2 ),
· · · , (xn, yn ). Also write a generalized program for a polynomial of k-degree,
where the degree of the polynomial k will also be an input of the system.
30. Write a program to compute the following function for m = 1 to 5 and k =
e−x e−y xm yk
1 to 10. p(m, k) = , where x and y are constants.
m!k!
31. A jail has n rooms (numbered from 1 to n) initially all closed (status of
a room is either close or open). The jail administrator takes a decision to
114 CHAPTER 5. SIMPLE COMPUTATIONAL PROGRAMMING PROBLEMS

vacate some rooms by releasing some of the criminals. To do so they make


a process as:

(1) Starting from 1st room with a gap 1, The status of a room changes from
open to close or close to open till n.
(2) In the ith step starting from ith room with a gap i (i.e. next room num-
bers are 2i, 3i, etc.), change the status of the room till n and this process
repeats until the starting room is n i.e., for i = 1, 2, · · · , n.

Write a program to print the room numbers which are finally vacate.
32. The formula W = 1 + sin(x) + |Ax + By|e|x−|A|| is to be evaluated for all
combinations of
x : 0.1, 0.15, 0.20,..., 0.9
y : 10, 15, 20, ...50
A : -50, -45, -40, ..., 0, 5, 10, ..., 50
B : 0.0, 0.5, 1.0, ..., 10.
Write a program that are containing nested loops to calculate W, and print
each combination of x, y, A, B and W on a separate line.
33. Suppose X and Y are 2 two-dimensional arrays, each array of order m ×
n, where m, n ≤ 100. Write a program to compute and print R = X T , the
transpose of X, and S = X +Y .
34. A factory has 3 divisions and stocks 4 categories of products. An inventory
table is updated for each division and for each product as they are received.
There are three independent suppliers of products to the factory.

(1) Design a data card (i.e. record structure) to represent each transaction.
(2) Write a program to take a transaction card and update the inventory.
(3) If the cost per item is also given, write a program to calculate the total
inventory value.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 115

35. The stocks of bulbs of various brands and wattage was represented as a two-
dimensional array.
Wattage
Brand 15 25 40 60 100
code 1 2 3 4 5 code 1 2 3 4 5
GEC 1 10 12 0 14 9 1 0.95 1.00 1.05 1.05 1.25
Philips 2 0 10 5 2 8 2 1.00 1.00 1.10 1.15 1.30
Crompton 3 10 0 25 4 8 3 0.90 1.50 1.05 1.50 1.50
Bengal 4 19 8 0 10 12 4 0.95 1.00 0.95 1.20 1.50
Mysore 5 10 5 6 16 8 5 1.00 1.05 1.10 1.15 1.25
Bajaj 6 20 12 10 9 12 6 1.00 1.00 1.10 1.20 1.30
Bulbs Costs

Assume that the cost of each (brand, wattage) bulb is given in another array
shown on the right side of the table. Write a program for the following:

(1) Print out the brand and wattage codes for items which are out of stock,
(2) Calculate and print the total cost of bulbs in the inventory.

36. A trader bought 10 boxes of apples and wishes to sell them. Those boxes
which weight more than 10 kg, he has priced @Rs.16/- per kg, those which
weight 10 kg @ Rs.17/- per kg, and those which weight less than 10 kg @
Rs.18/- per kg. Find the total amount that he will get. [Hints: Generate 10
uniformly distributed random numbers with mean 10].
37. Write a programs to count numbers of an English alphabet (say, B) in a set
of names.
38. Write a function sub-program to find the length of a string.
39. Write a sub-program to copy a substring from a given string.
40. Write a sub-program to insert a string into a given string.
41. Write a program to delete a specified number of characters from a specified
position in a given string.
42. Write a program to concatenate a string at the right of a given string.
116 CHAPTER 5. SIMPLE COMPUTATIONAL PROGRAMMING PROBLEMS

43. Write a program to concatenate a string at the left of a given string.


44. Write a program to find the positions, where a given character occurs in a
string.
45. Write a program to rearranged name, that is, arrange among the first name,
second/middle name, last name.
46. Write a program to search a string in a given text.
47. Write a program to read a set of lines, right justifies trims to a given line
length and write them as output text.
48. Write a program to find whether a character string is a palindrome. A palin-
drome reads the same whether it is read from left to right or right to left (for
example, RAJABAJAR is a palindrome).
49. Write a program that calculate cube roots, using the fact that if b is an ap-
1 x
proximation for cube root of x, a better one is: c = 2b + 2 .
3 b
50. Write a program to delete all vowels from a sentence. Assume that the sen-
tence is not more than 80 characters long.
51. Write a program to count the number of words in a sentence.
52. Write a program which will read a line and squeeze out all blanks from it
and output the line with no blanks.
53. Write a program which will read a line and delete from it all occurrences of
the word ‘the’.
54. Write a program to encrypt a sentence using the strategy of replacing a letter
by the next letter in its collecting sequence. Thus every A will be replaced
by B, every B by C and so on and finally Z will be replaced by A. Blanks
and punctuation are left undisturbed.
55. Write a program which takes a set of names of individuals and abbreviate
the first, middle and other names except the last name by their first letter.
For example, Gopal Chandra Pal would become G. C. Pal.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 117

56. Write a program to read a sentence and substitute every occurrence of the
given word (say, RAM) by another word (say, HUMA). Example: Input:
RAM IN RAMAYANA, output: HUMA IN HUMAAYANA.
57. Write a program to count the number of occurrences of any two vowels in
succession in a line of text.
58. Write a program to sort a set of names in an alphabetic order with a key on
the first two characters of the last name.
59. (a) A class of students secured the following grades for the 6 tests taking
in a programming course:
Name Scores (%) for the tests
Ajoy 45 80 80 95 55 75
Babu 60 50 70 75 55 80
Devi 40 30 10 45 60 55
Farid 0 5 5 0 10 5
Hari 90 85 100 95 90 90
Jaba 95 90 80 95 85 80
Lalit 35 50 55 65 45 70
Osman 75 60 75 60 70 80
Pradip 85 75 60 85 90 100
Ravi 50 60 50 35 66 70
Sumit 70 60 75 70 55 75
Tahera 10 25 35 20 30 10
Uttam 25 40 65 75 85 95
Zarabi 65 80 70 100 60 95
Write a program that will accept each student’s name and their percentage
grades as input, and determine an average grade for each students make
the program as general as possible.
118 CHAPTER 5. SIMPLE COMPUTATIONAL PROGRAMMING PROBLEMS

(b) Modify the above program for unequal weights to the individual ex-
amination, in particular, assume that each of the first four examination
contributes 15% to the final score, and each of the last two exams con-
tributes 20%.
(c) Extend this program, so that an overall class average is determined in
addition to the individual student averages.
(d) Create a sequential data file which contains the name and examination
scores of each students in a computer science class.
(e) Write a program to read this data from the above file and process the
scores and output the results in a tabular form.
60. Write a program to create a random data file which contains the name of 50
students in a class, arranged alphabetically.
61. (a) Write a program that will create and utilize a sequential data file con-
taining fields for name, address and telephone number. Include a provision
for each of the following features.
• Add a new record (i.e, a new name, address and telephone number) to
the file.
• Find and display a particular record, based upon information entered
into the terminal (e.g., a name, or an address, or a telephone number).
• Delete a particular record, based upon identifying information entered
from the terminal.
• Alphabetize the records, based upon the last name in each record.
• List (i.e. print) the entire file.
• Terminate the computation.
(b) Repeat this problem utilizing a random data file. Compare the perfor-
mance with the sequential data file version from a standpoint of program-
ming case and execution speed.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 119

62. We will say that a sequence of open and closed parentheses is well formed
if such a sequence can appear in a legal algebraic expression. For example,
(( ) ( ( ) ( ))) is well-formed, while the sequence
(( ) ( ))) ( ) (( ) is not well-formed.
A sequence of open and closed parentheses is supplied to you as input. You
are required to determine if the sequence is well-formed.
(a) Draw the flow-chart. (b) Write the program.
63. An alphabetic array NAME having n elements is supplied as input. Each
element is a character string of length atmost m characters, and is to be
interpreted as the surname of an individual. You are required to print out the
surnames in alphabetical (i.e., dictionary) order, with consecutive surnames
on the same line separated by atmost two blanks. You will be supplied n, m
and NAME as input. (a) Draw the flow-chart. (b) Write the program.
64. A string A of characters and digits is supplied as input. You are required to
check whether the string reads the same forwards and backwards, and print
out an appropriate message. For example, the string “A A 1 2 B C B 2 1 A
A” reads the same forwards and backwards, but the string “1 2 3 4 2 3 4 2 3
1” does not.
65. The pension rules in a certain country state that a man receives Rs.50/- a
week, if he is over 65 years and an additional Rs.20/- if he is over 70 years.
A woman receives Rs.45/- a week, if she is over 60 years and an additional
Rs.25/- if she is over 65 years. Write a program which leads in the sex (0 for
man and 1 for woman) and age of a person, and print out the amount of their
pension. If the person is under pensionable age, a suitable message should
be computed.
66. Many banks, savings organizations and loan institutions compute interest on
a daily basis. On a balance of Rs.1000/- with an interest rate of 6% the in-
120 CHAPTER 5. SIMPLE COMPUTATIONAL PROGRAMMING PROBLEMS

terest earned in one day is 0.06 times Rs.1000/- and divided by 365 because
it is for only one day of 365 days in a year. This yields Re.0.16/- in interest
so that the balance at the end of the first day is Rs.1000.16/-. Interest for
the second day is calculated in the same way and so on. Write a program
which will take 3 (three) inputs: amount of a deposit, annual interest rate
and the duration in weeks, and output the balance at the end of the specified
duration.
Chapter 6
SIMPLE DESCRIPTIVE PROGRAMMING
PROBLEMS

In this chapter a set of problems have considered as a programming assign-


ments to practice one of the conventional programming languages as on the
previous chapters. Here the objective is to design the programming logic from
the problem description.

1. Two sorted integer arrays A and B of sizes m and n respectively are given.
From these two arrays you have to create another array C of size m + n
which is a combination of A and B in sorted order. You are not supposed to
sort C explicitly. Write the program.
2. There are n persons stand in a ring. We number them from 1 to n sequen-
tially in a clockwise direction, so that person n and person 1 are neighbors.
We start counting in a clockwise direction from person 1 and when we reach
a given number m, we throw out person m from the ring. We then start count-
ing from the next man and again when we reach a count of m, we throw out
that person from the ring. Once a person is out of the ring, he never comes
back and is not counted.
Example:
If n = 7 and m = 5 the sequence of persons thrown out will be 5 3 2 4 7
1 6.
Write a program that inputs n and m and outputs the corresponding se-
quence.
3. Write a program which will accept n data items between 0 and 9. Print out
the number of runs in the data set. A run is defined as a consecutive series of

121
122 CHAPTER 6. SIMPLE DESCRIPTIVE PROGRAMMING PROBLEMS

two or more occurrences of the same number. The program should output
the number of runs for each digits.
Example:
n = 20, and given data :
1, 1, 0, 0, 0, 2, 3, 4, 4, 5, 2, 1, 1, 6, 0, 7, 7, 9, 0, 0.
Then total number of runs = 6.
Number of runs for 0’s = 2;
Number of runs for 1’s = 2;
Number of runs for 2’s = 0;
Number of runs for 3’s = 0
. . . etc.
4. Input a sequence of integers and integer groups terminated by −1. Output
the sequence of integers.
Example:
Input : 7 6 4 ∗ 9 3 2 ∗ 1 5 -1
Output : 7 6 9 9 9 9 3 1 1 5
(Here 4 ∗ 9 in the input means there are four occurrences of 9 in the string,
etc.).
Write the program.
5. Given two integers m and n, where m > n. Write a program to print the first
m natural numbers in n columns reading down the page. Arrange that the
last row is short if necessary.
Example:
m = 23 and n = 5 your program should print
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 123

1 6 11 16 20
2 7 12 17 21
3 8 13 18 22
4 9 14 19 23
5 10 15
Write the program.
6. A line of data consists of a sequence of characters terminated by a period.
In this sequence there are one or more subsequences within parentheses.
Input the sequence and output it omitting the subsequences lying within
parentheses by writing a program.
Example:
Input : A B C ( D E F ) H ( I ) J K
Output : A B C H J K
7. Write a program which sorts the contents of a two-dimensional array, so that
they are in ascending order when the array is scanned row by row, and left
to right. Your program should not use any storage for additional arrays.
8. Input a list of names in an arbitrary order where each name is in the form
of first name, second name and third name. Output the list which is sorted
over third name where each name is in the form of third name, first name
and second name. If some of the third names are same then prints them in
a sorted order over the first name. Note that some names in the list may not
have any second name.
Write the program.
9. Write a program which reads a sequence of single digit positive integer ter-
minated by −1 and outputs a sequence in which subsequences of repeated
integers are replaced by a single instance of the integer preceded by an ap-
propriate count and the character ∗.
Examples:
124 CHAPTER 6. SIMPLE DESCRIPTIVE PROGRAMMING PROBLEMS

(1) Input : 4 3 3 3 3 2 5 5 5 9 −1
Output : 4 4 ∗ 3 2 3 ∗ 5 9 −1
(2) Input : −1
Output : −1
(3) Input : 4 3 5 7 9 −1
Output : 4 3 5 7 9 −1
Note that: (1) Output should end with −1. (2) In the output two successive
integers must be separated by at least one space.
10. An array RAIN contains rainfall data for a particular city over a period of
one year. There are 365 entries in RAIN, one for each day of the year num-
bered consecutively for 1 to 365. The data is in millimeters (mm), and each
entry in RAIN is either 0 or a positive integer. We define a dry spell as a
consecutive sequence of days without any rain at all. Similarly, a wet spell
is a consecutive sequence of days with at least 5mm of rain each day.
You are given an array RAIN of m entries as input, where m lies between 1
and 365 (both inclusive). You have to determine

(1) The length of the longest dry spell (in days) starting at day 1 upto and
including day m.
(2) The length of the longest wet spell (in days) starting at day 1 and upto
and including day m.
(3) The average rainfall per day over the period 1 to day m, correct to one
decimal place.

Write the program.


11. Write a program to read a 20×20 array of real numbers representing heights
above sea level at grid points and to print a map of the area covered as a
20 × 20 pattern of characters. The map is to show sea by space characters
and land by “.” characters except for the highest point which is to be a “∗”
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 125

character. The map is to be surrounded by “X” characters and followed by a


line stating the height of the highest point.
12. An airline reservation system maintains records for possible flights consist-
ing of
Starting point : 3 character code,
Destination : 3 character code,
Starting time : integer on scale 0001-2400,
Arrival time : integer on scale 0001-2400,
Seats : positive integer in suitable range.
Your program is to read n such records followed by queries of the form :
starting point-destination. For each query find whether there is a possible
flight with a seat available; if so reduce the number of seats by one and print
out the flight details (or an apology).
Write this program.
13. Write a program that reads a real number, treat it as an amount of money
(rupees and paise) and output it in equivalent English.
Example:
The number 108.76 thus becomes
ONE HUNDRED AND EIGHT RUPEES AND SEVENTY SIX PAISE.
14. The responses of an individual to a market survey questionnaire is supplied
in the form of a character string A. Each response to a question has encoded
as a single digit. To ensure reliability, it has been decided to check the con-
sistency of data in A in the following manner. A positive integer n gives the
number of consistency checks to be performed on A. Two other numeric
arrays B and C are given, each containing n entries. The check to be made
on A is as follows: for each i lying between 1 and n, whenever the B(i), the
character in A is not 1, the C(i), the character in A must be non-zero.
You are supplied n, A, B and C as input. You have to determine whether the
126 CHAPTER 6. SIMPLE DESCRIPTIVE PROGRAMMING PROBLEMS

data in A is consistent. If not, you have to output the number of inconsistent


pairs of entries in A, and the positions in A of each such pair.
(a) Draw the flow-chart.
(b) Write the program.
15. A list of project (P) is given with a preference number attached with each
project. A set of students (S, P > 3 × S) arranged in ascending order of their
rank is to choose projects out of this given set of projects such that

(a) No two students have the same name.


(b) Each student will have to select a set of three projects from the given
set.
(c) No two students can select the same project.
(d) The project assignments are done in order of the rank of students.
(e) In case of tie, the lexicographic order of student names are considered
for order of assignments.

Write a program which will assume the projects and their preference num-
bers, and will take as input the individual student roll numbers and their
ranks. It will then do the project selection and output the student roll num-
bers with the associated project numbers.
16. Certain characteristics of a hotel room may be coded in a simple way.
Example:
(1) the number of single beds,
(2) the number of double beds,
(3) whether or not there is a bathroom, and
(4) whether or not there is a television.
Thus a room with two single beds and a television but no bathroom or double
beds could be represented by 2001.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 127

Write a program which reads in the characteristics of the rooms in an n-


roomed hotel and requests for booking. A request is of the form name, re-
quirements where requirements are coded in the same way as room char-
acteristics. If a room meeting the requirements is available, your program
should reserve it and exclude it from further considerations. The hotel
wishes to turn away as few clients as possible, so your program should min-
imize the resources allocated over those requested.
17. One simple but effective coding system depends on an arrangement of 25
letters of the alphabet in a square based on a keyword. The remaining letter
of the alphabet is transmitted unaltered.
Example:
if the keyword were BREAK and the letters to be sent unaltered were J then
the square would be
BR E AK
CD F GH
I L MNO
PQ S TU
V W X Y Z.
A pair of successive letters is coded by replacing each one by the one in the
same row but in the column of the other.
Example:
The message
CO-MP-UT-ER-SC-IE-NC-E → HI-IS-TU-RE-PF-MB-IG-E
Single last letter, if any, is left unaltered. Input a five letter keyword and
the letter to be sent unaltered. Then read in the message to be coded and
output the code. Choose a proper terminator for the message and ignore all
punctuation and spaces in the message.
Write the program.
128 CHAPTER 6. SIMPLE DESCRIPTIVE PROGRAMMING PROBLEMS

18. Consider a Boolean matrix of size 3 × 3 as given below:


P9 P2 P3
P8 P1 P4
P7 P6 P5
where, Boolean variables P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 are the 8-neighbors of
the Boolean variable P1 . Pi ∈ {T, F}, for i = 1, 2, · · · , 9. Design a logical
expression for the count of trues (T ′ s) of 8-neighbors of P1 is lies between
2 and 6, and only one ′ FT ′ pair of the 8-neighbors of P1 in a clockwise
direction.
Write a program using only logical statements and logical operations for the
above computation, and also the program returns a Boolean flag.
Example: Let us consider a Boolean matrix as given below:
TTF
TTF
TFF
Here, number of True (T) in the 8-neighbor of the central element (P1 ) = 3,
and the number of ′ FT ′ pattern in clock-wise direction = 1. So the program
will return ′ T RUE ′ as output.
19. A man leaves work at the end of a day. If the time is 6.00p.m. or earlier he
travels home by bus. If the time is later than 6.00p.m. he has a meal in a cafe
before travelling home, by bus. Draw a flow-chart of the man’s activities.
20. A man leaves work at the end of a day. If the time in 6.00p.m. or earlier
he travels home by bus. If the time is later than 6.00p.m. he has a meal in
a cafe before travelling home. After the man has had a meal if the time is
later than 7.00p.m. he is too late to travel home by bus so he travels home
by taxi; otherwise he travels home by bus, as usual.
Draw a flow-chart of the man’s activities.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 129

21. Three coins of the same value are labelled X, Y and Z. Either X or Y is coun-
terfeit since it is not the required weight. Coin Z is known to be genuine. A
simple balance is used to weigh one coin against the other. Flow-chart a
procedure to detect the counterfeit coin, and state whether it is heavier or
lighter than the genuine one.
22. The weights of newly born babies are input to a computer. Draw a flow-chart
to find the maximum, minimum and mean weights of all the weights of the
babies. A value of zero can be used at the end of the list of baby weights.
Draw a flow-chart and write the program.
23. In a theater hall, films are exhibited to the public throughout the week. The
ticket charges are as follows: Adults pay Rs.25/- on weekends (i.e., on Sat-
urday and Sunday) and Rs.20/- on weekdays. Those of 60 years or older
pay half of the adult price. Children 12 or older are considered adults. Chil-
dren of 6 through 11 pay Rs.10/- on weekdays and Rs.15/- on weekends.
Children under 6 will not to be admitted.
Input for a customer consists of two positive integers i and j, where i stands
for age in years and j for the day in the week, with 1 for Sunday, 2 for
Monday, · · ·, 7 for Saturday.
Chapter 7
PROGRAMMING USING SIMPLE
CONDITIONS

In this chapter, a set of descriptive problems have been considered for com-
puter programming. Logic of these problems is to be design based on the
described conditions. Program the following problems.

1. Consider the following rules for calculating income tax. Personal allowances
are Rs.3,600/- for a single person and Rs.6,000/- for a married man. A child
allowance is Rs.1200/- per child. Taxable income is the amount remaining
after deducting the personal allowance and total child allowance from the
gross income.
Income-tax is calculated from taxable income according to the following
table.
Taxable Income on Percentage tax
on
Taxable Income
First Rs.10,000 No Tax
Next Rs.10,000 20%
Next Rs.20,000 30%
Above Rs.40,000 40%
If the gross salary, personal status (married or single) and number of chil-
dren are input to a computer. Draw a flow-chart to determine the tax paid on
that income.
2. An examination has conducted for n students of a class. The following four
pass grades are awarded:

131
132 CHAPTER 7. PROGRAMMING USING SIMPLE CONDITIONS

P1 for marks between 100 and 85 inclusive,


P2 for marks between 84 and 68 inclusive,
P3 for marks between 67 and 49 inclusive, and
P4 for marks between 48 and 35 inclusive.
Two fail grades are awarded:
F1 for marks between 34 and 20 inclusive, and
F2 for marks between less than 20.
Each student is identified by a code number. Draw a flow-chart to input n,
the student’s code and percentage mark gained by each student, and output
each student’s mark as a grade along with the student’s code, and also the
totals in each grade of pass or fail.
3. A travelling salesman must visit cities B, C, and D each month, always
starting from city A and returning to A. Let d1 be the distance from A to B,
d2 from A to C, d3 from A to D, d4 from B to C, d5 from B to D and d6 from
C to D. Assume that each city is to be visited exactly once.
Draw a flow-chart that inputs the distances (say, in Kilometers) and deter-
mines the order of visits to the cities that use the shortest route. Write a
program for this problem.
4. A welfare fund has been instituted by depositing Rs.X on January 1, 1994
in a bank. The annual rate of interest is 1%. Each year only once a transac-
tion takes place on December 31, when a sum of money is withdrawn from
this account number. First year (i.e., on 31 − 12 − 1994) Rs.Y is withdrawn;
and on any subsequent year the amount of withdrawal is Z% more than the
amount that was withdrawn in the previous year. However, on 31st Decem-
ber of any year, the interest of the year is computed and accumulated to the
balance; and only after that, the transaction is made.
You are required to prepare a statement of transactions of this account num-
ber for a period of fifty years, or until the fund expires whichever occurs
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 133

earlier. The statement should include, for each year, the opening balance,
interest, withdrawal and closing balance.
Example:
If X = 100000, I = 10, Y = 5000 and Z = 20 your output should look like
the following:
Year Opening Interest Withdrawal Closing
Balance Balance
1994 100000 10000 5000 105000
1996 105000 10500 6000 109500
Write a flow-chart and a program that inputs I, X and Z, and output the bank
statement.
5. A manufacturer has one product line and three types of customers. He has a
discount procedure which varies with the customer and the amount of order.
The complete discounting policy is summarized in the table below:
Order value
Customer Less than Greater than or
Type Rs.1000/- equal to Rs.1000/-
1 5% 10%
2 10% 15%
3 15% 20%
Net order value of an order is computed as follows :
Net order value = Order Value − Discount.
Write a program to find the net order value for each of 100 such orders.
Read order number, customer type and order value as inputs and print order
number, customer type, net order value, as outputs.
6. A student takes five examinations. Scores (out of 100) in these examinations
are given by S(1), S(2), S(3), S(4), S(5). Best four of these five scores are
134 CHAPTER 7. PROGRAMMING USING SIMPLE CONDITIONS

totaled to give his final score. A student passes if (i) he gets at least 30 in
each of the five examinations and (ii) his final score is at least 50%.
Given the array S as input, you have to output his final score and also to
determine whether he passes or fails. Write a flow-chart and a program.
7. An electric supply company gives a rebate to its customers, who pay their
bills in time. The rate of rebate (in paise) per unit of electricity consumer is
given by the following table.
Customer type −→ 1 2 3
Upto 60 units 10 8 6
Exceeds 60 units, but does not exceed 100 units 5 4 3
Exceeds 100 units 4 2 1
Your input will consist of the customer type (an integer 1, 2 or 3) and number
of units consumed (a positive integer). You must output the amount of rebate
in Rupee-Paise form. Write a flow-chart and a program.
8. An array SALE of 52 entries gives the weekly sales; during a year Y of a
salesman selling calculators. He is eligible for an award for his sales perfor-
mance if

(1) he sells calculators worth Rs.M/- or more every week in the year Y,
and
(2) he sells calculators worth a total of Rs.N/- or more during at least one
consecutive period of atmost 4 weeks in the year Y.

You are supplied M, N and the array SALE, and you have to determine
whether the salesman gets the award.
(a) Draw flow-chart, and (b) Write the program.
9. Each week the employees of a local manufacturing company turn in time
cards containing the following information:

(1) An identification number (a five digit number),


COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 135

(2) Hourly pay rate (a real number),


(3) Time worked Monday, Tuesday, Wednesday, Thursday and Friday
(each one is a four digit integer of the form hhmm, where hh is hours
and mm is minutes).

Example:
Last week’s time cards contained the following data for few employees
Employee Hourly Time worked (hours, minutes)
number rate(Rs.) Mon Tues Wednes Thurs Fri
12345 4.00 0805 0930 0900 0800 0720
20046 4.50 0615 0904 1000 0900 0800
10015 4.25 0808 0800 0935 1115 0735
.. .. .. .. .. .. ..
.. .. .. .. .. .. ..
.. .. .. .. .. .. ..
99999 .. .. .. .. .. ..
For each employee gross pay is required to be computed. This can be done
by first computing total hours worked (in hour and minutes) and then round-
ing total hours worked to the nearest quarter hour.
Example:
If total hours worked = 3810, then it should be rounded to 3815.
If total hours worked = 3805, then it should be rounded to 3800.
Assume overtime is paid at 1.5 times the normal hourly rate and is com-
puted on a weekly basis on total hours rounded to the nearest quarter hours
in excess of 40 hours.
Given the time card date as stated above, print out employee number, total
hours worked (rounded to nearest quarter hour) and gross salary. (a) Draw
flow-chart, and (b) Write the program.
136 CHAPTER 7. PROGRAMMING USING SIMPLE CONDITIONS

10. A large manufacturing company has n divisions, numbered 1 through n. The


divisions manufacture are distinct sets of products, and each division has its
own team of salesmen to market its products. An array BEF of n entries
gives the average monthly sale in rupees of each division in a year, Y (say,
1997). It was decided early in next year, Y + 1 (say, 1998) to introduce an
incentive scheme for the salesmen on a trial basis for a few months. The
array AFT of n entries gives the new average monthly sale in rupees of each
division during the trial period. The incentive scheme requires the company
to pay out a specified R% of the total sale of each division as incentive to
the salesmen of the division. The company also incurs a constant additional
administrative overhead of Rs.H per division per month to run the scheme.
Moreover, the company must always maintain an inventory of finished
goods equal in value to two months’ sale, and incurs a cost of C paise per
rupee of inventory each month to maintain the inventory. Since the incentive
scheme increases the total sale, a larger cost is incurred in this connection.
There is no other new item of expenditure. The company now has three al-
ternatives before it: (1) to scrap out the incentive scheme; (2) to introduce
the incentive scheme in all divisions; (3) to introduce the incentive scheme
selectively in some of the divisions.
You have been retained to advise the company. In case you suggest alter-
native (3), you must also specify the divisions in which the scheme will be
introduced. n, R, H, C and the arrays BEF and AFT are supplied as input.
(a) Draw flow-chart, and (b) Write the program.
11. Software Experts is an organization employing n persons. The employees
have been assigned identification numbers from 1 to n in some arbitrary
orders. Each employee except the Managing Director reports to some other
employee immediately above him in the organization hierarchy. The rank of
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 137

the Managing Director is 1, while an employee has rank R + 1 if the rank of


his immediate boss is R. There are atmost nine different ranks. The monthly
salary of an employee at rank R is, in hundreds of rupees, 50 − 5(R − 1).
An array REP of n entries tells us who reports to whom. Specifically,
REP(K) = 0 if K is the Managing Director; otherwise, REP(K) is the per-
son to whom K reports. For example, with n = 6 then REP can have the
following form.
REP(1) REP(2) REP(3) REP(4) REP(5) REP(6)
4 1 5 0 4 1
This says that 4; is the Managing Director, 1 and 5 report to him, 2 and 6
report to 1, and 3 reports to 5.
You are supplied n and the array REP as input, and you have to determine
the monthly expenditure incurred by Software Exports in paying salaries to
its employees.
(a) Draw flow-chart, and (b) Write the program.
12. A matrix MAT of positive integer elements of size m × n is supplied. An
element MAT(i, j) of the matrix is called a saddle point if one of the follow-
ing conditions holds. (i) MAT(i, j) is the largest number in row i of MAT
and the smallest number in column j of MAT (ii) MAT(i, j) is the smallest
number in the row i of MAT and the largest number in column j of MAT.
Example:  
8 30 17 9
 
 2 10 7 10 
If MAT is the matrix as MAT = 
 

 2 30 13 15 
 
5 70 8 4
then MAT(1,1) and MAT (2,2) are the only saddle points. Given m, n and
MAT as input, determine all saddle points of MAT if any.
138 CHAPTER 7. PROGRAMMING USING SIMPLE CONDITIONS

13. NAME is an alphanumeric string of size 40. In NAME, there are names of a
person, with his first name appearing at the left most position in NAME. An
individual has 1 to 3 names; the last of which is the surname. Two consec-
utive names are separated by a single space (i.e., the blank character). You
have to output the names in a different sequence: the surname must appear
first and will be followed by a comma (,) and a space, and then the rest of
NAME (if any). Output all names in one line.
Example:
if NAME = “BISWAS”, then print BISWAS
if NAME = “SAMIR BISWAS”, then print BISWAS, SAMIR
if NAME = “SAMIR KUMAR BISWAS”, then print BISWAS, SAMIR KUMAR.
Draw a flow-chart and write a program.
14. A well known management institute has held an admission test, and you
have been mentioned to process the results. There are n candidates, and
each candidate has a registration number between 1 and n. The test has
100 questions of the multiple choice type, with 5 choices per question. The
questions are divided into five sections of 20 questions each; questions 1 to
20 belonging to section 1, questions 21 to 40 belonging to section 2, and so
on.
KEY is an array of length 100, and each entry in KEY is a digit between
1 and 5. The ith entry in KEY gives the correct answer to question i. The
responses of the candidates have been encoded in the array ANS. For each
j and each i, ANS(i, j) is the answer of candidate j to question i, and is a
digit between 0 and 5. The digit 0 indicates j has not answered the question.
The score of a candidate is determined as follows.
The answers are matched with KEY. If the answer matches, +1 point is
1
awarded; if the answer is wrong, the candidate gets − points; zero is
4
awarded for an unanswered question. In order to gain admission, the can-
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 139

didate must score at least 95. In addition, it is required to qualify in each


section. To determine this, an array Q of 5 entries is supplied. For each i
between 1 and 5, Q(i) gives the qualifying mark for section i.
Draw a flow-chart and write a program to input n, Q, KEY and ANS and
output the list of all candidates who are to be admitted. The list must have a
tabular format with three columns; the first column will give the registration
number, the second column will give the total score rounded off to the near-
est integer and the third column will give the percentile score. To find the
percentile score of candidate j, we have to find the total number of candi-
dates whose total score is strictly greater than that of j; suppose the number
 m
is m. Then the percentile score of j is 100 1 − . Also output the score
n
in each section in a separate list.
15. In an objective test some students take part. In the test there are m ques-
tions to be answered by any student; where m is a fixed positive integer for
a particular test paper. Each question has n possible alternative answers to it
(where, n is a fixed positive integer for a particular test paper); there are 1,
2, 3, ...; only one of these n alternatives is correct for any specific question.
CORRECT is an array of m correct answers. Right answer to a question car-
ries +x marks, whereas a wrong answer to a question carries −d marks. A
question that is not answered by a student does not contribute to his score.
ROLL is an integer array containing roll numbers of all students; ROLL[i]
is the roll number of the ith student. ANSWER is a two dimensional array
containing answers of all students in the test. ANSWER[i, j] is a charac-
ter symbol representing the answer of the ith student in the jth question. If
ANSWER[i, j] is 0 other than 1, 2, 3 etc. it is assumed that question j has
not been answered by the student i.
The m questions are divided equally or unequally in q sections, A student
140 CHAPTER 7. PROGRAMMING USING SIMPLE CONDITIONS

is said to have qualified in section k if his score in section k is atleast


QUALIFY[k], k = 1, 2, 3, · · · , q. A student passes the test if he qualifies in
all the q sections.
You are required to write a program which will do the following:

(a) Input the relevant data interactively or through a file.


(b) Output for each student: Roll number, scores in each sections, total
score, whether passed or failed.
(c) Output a merit list of passed students only. This list should be an or-
dered list of students, with the top score appearing at the top. In this list,
for each passed student his roll number, total score and rank are to be
included.

16. A sequential data file named “STUDENT” containing student’s records of


length 80 character (bytes). Each record has the following format (layout)
Column Type Remarks
From To
1 - 8 Alphanumeric Record identification
9 - 18 Alphanumeric Roll number
19 - 58 Alphanumeric Student’s name
59 - 60 Numeric Marks in Physics
61 - 62 Numeric Marks in Chemistry
63 - 64 Numeric Marks in Mathematics
65 - 80 – Blank
Write a program that takes an input from the file and generate the following
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 141

report as
STUDENTS RESULT
Sl No Roll No Name Phy Chem Math Total
1 C/001 S.K. De 50 69 70 189
2 B/005 P.K. Sen 81 79 60 220
etc.
17. There are m number of students in a class and there is a list of n projects
(n > 3m), numbered as 1, 2, · · · , n. These projects will be assigned to the
students satisfying the following conditions:

(1) Each student will do 3 projects


(2) No two students will be have a project common between them.
(3) Every student will be assigned projects based on his own rank and
preferences given as (SR, SN, R, p1 , p2 , · · · , pn ) where SR is the student
registration number, SN is the student name, R is a rank (may not be
unique) of a student, and (p1 , p2 , · · · , pn ) is a permutation of 1, 2, · · · , n,
that means p1 = project number of his first preference, and pn = project
number of his last preference
(4) Priority of assignment of a project to a student will depend on his rank.
Example: The student of Rank 1 will get assigned all first 3 preferences.
Similarly, the student of Rank m will have projects assigned from the list
of projects not assigned to any other student.
(5) In case of tie in rank, the lexicographic order of student name or regis-
tration number are considered for order of assignments.

Write a program which will assume the projects and their preference num-
bers, and will take as input the individual student registration numbers as
well as their ranks. It will then do the project selection and output the stu-
dent registration numbers with the associated project numbers.
142 CHAPTER 7. PROGRAMMING USING SIMPLE CONDITIONS

Example:
Input: Let m = 5 and n = 16.
The rank of students and their preferred project numbers are given below:
Preference → 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
Reg Name Rankwise Projects
3 A.B. 01 03 02 04 05 06 08 09 11 10 12 14 13 07 16 15
1 R.P. 01 08 02 05 04 06 03 09 12 11 10 13 07 14 16 15
2 K.B. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 16 15
4 U.A. 14 12 10 08 06 04 02 01 03 05 07 09 11 13 15 16
5 S.P. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
Regn. Name Rank Projects
1/02 R.P. 1 → 01 08 02
2/02 K.B. 2 → 03 04 05
Output:
3/02 A.B. 3 → 06 09 11
4/02 U.A. 4 → 14 12 10
5/02 S.P. 5 → 07 13 15
18. There are m empty track trucks, numbered 1 through m, each able to carry
C Kgs of cargo. There are n packs of cargo which have to be loaded onto
the trucks. An array CARGO of n entries gives the weights of the n packs
in Kgs. The packs are loaded onto the trucks using the following scheme.
The packs are loaded in the same left-to-right order as in CARGO. At step 1,
we consider those trucks which have not already been allocated greater than
C −CARGO(i) Kgs of cargo. Among these, we select that truck for which
the weight of the cargo already allocated is closest in value to C −CARGO(i)
and allocate CARGO(i) to that truck. In case of a tie, a truck with a smaller
number is given preference.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 143

Example:
Let C = 30Kgs, m = 4, n = 5 and let CARGO be the array
Index 1 2 345
.
Content 20 20 30 5 6
Then only 3 trucks are used, as follows:
Truck No. Cargo
1 CARGO(1), CARGO(4)
2 CARGO(2), CARGO(5) .
3 CARGO(3)
4 Empty
C, n, m and the array CARGO are supplied as input. You are required to find
out.

(1) the number of trucks required for loading the cargo; and
(2) the loading pattern for each truck, i.e., the weights of the cargo packs
placed in that truck.

You may assume that the given cargo would fit in the m trucks using the
above scheme; in particular, CARGO(i) is less than or equal to C or 1 ≤ i ≤ n
and the total weight of the cargo is less than or equal to m ×C.
(a) Draw a flow-chart, and (b) Write the program.
19. We are interested in coding English test in binary. Each letter and punctua-
tion mark (including blank) will have a binary code (i.e., a string of 0′ s and
1′ s), but the codes can have different lengths. To minimize the length of the
coded text (viewed as a string of 0′ s and 1′s) we use a method suggested by
Hoffman:
Let there be n characters (including punctuation marks and blank) to be
coded. We are supplied an array FREQ of n entries which gives the fre-
quency of occurrence of a character in standard English. Let us assume
144 CHAPTER 7. PROGRAMMING USING SIMPLE CONDITIONS

FREQ(i) for each i is a positive integer lying between 1 and 100. First
find the two smallest entries in FREQ. Call these entries FREQ(i) and
FREQ( j), where i < j, note that FREQ(i) may or may not be equal to
FREQ( j). Replace FREQ(i) with FREQ(i) + FREQ( j), and FREQ( j)
with infinity (i.e., a very large positive number). Repeat the process until
only one non-infinite value remains in FREQ. Now the binary code can be
obtained as explained below the example:
Example:
Let n = 6, the array FREQ is
Index 1 234 56
.
Content 15 20 5 3 15 7
The combinations take place as shown below:
15 20 5 3 15 7
15 20 8 - 15 7
15 20 15 - 15 -
30 20 - - 15 -
30 35 - - - -
65 - - - - -
Where ’-’ represents infinity.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 145

Here row 1 is same as previous table. But row 2 is as 15, 20, 8 (= 5+ 3), -,
15, 7. Similarly other rows. This can be depicted as in the structure as shown
in figure.
So the codes correspond to the different characters (specified by their entry
numbers i the FREQ array) are:
FREQ corresponding
entry number binary code
1 00
2 10
3 0100
4 0101
5 11
6 011
We are supplied n and FREQ as input, and we want to output the corre-
sponding Hoffman code.
(a) Draw a flow-chart, and (b) Write the program.
Chapter 8
PROGRAMMING USING COMPLEX
CONDITIONS

Program the following conditional computing problems using a conventional


programming language.

1. A typing test has been given to six applicants from the position of an op-
erator of a word processing system. The test duration is 1 hour. Errors the
operator finds and corrects during the hour are not counted but errors found
after the test ends are counted. Each applicant has specified the minimum
wage he or she will work for the results follows:

Person’s Words Hourly Errors


Sl. No. per minute wage (Rs.) per hour
1 47 6.00 13
2 62 6.75 19
3 60 7.00 7
4 53 5.60 9
5 35 4.90 21
6 51 5.40 12

(a) Write a program that will determine and print the cost per word for
each applicant.
Example:
The cost per word for the applicant 1 is Rs.6.00/(47×60) = Rs.0.0021277.

147
148 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

The output format will be : 0.212766E −02. (Ignore the “Errors per Hour”
data for this part.)
(b) Modify the program in part (a) assuming that the correction of an error
requires 30 seconds. Thus, if an applicant makes 10 errors in 1 hour he
or she would be paid for 65 minutes of work (1 hour plus 10 one-half
minutes) for each hour’s worth of typing.

Before writing the program, manually compute the cost per word for 100
of the applicants. Then, write the program and check your results. Whom
would you hire?
2. In many cities and states, supermarkets are now required to “unit price”
their products. All products of a particular type (e.g., canned beans, oil, de-
tergent, breakfast cereals) must carry an indication of the price for some
common unit quantity of the product.
Example:
Coconut oil may be required to carry a unit price of Rs. per Kg. Since
coconut oil is packaged in a number of different sized containers, with a
group of containers often carrying a single price, it is necessary to know the
contents per container (in Kg), the number of containers packaged together
(e.g., 0.250, 0.500, 1.000, 1.500, 2.000, 5.000), and the price for the pack-
age to determine the price per Kg.
Write a program that will input the number of containers in a package, the
Kgs in each container and the price for the package, and then compute and
output the unit price.
3. Write a program for pay cheque preparation based on the following data and
rules:

(a) An employee is paid based on the hours worked in a week and his or her
hourly wage rate. The input data provides these two pieces of information.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 149

(b) For 40 or less hours worked, gross pay is equal to hours worked times
hourly wage rate.
(c) If hours worked exceed 40, the wage rate is increased by 50% and gross
pay is 40 times wage rate plus (hours worked −40) times 1.5 times wage
rate.
Example:
Suppose 50 hours at Rs.8.00 per hour results in gross pay of Rs.440.00
(e.g., 40 × 8.00 + (50 − 40) × 1.5 × 8.00 = 440).
(d) Income tax withholding is 14% of gross pay.
(e) Net pay is gross pay less income tax withholding.

For each employee, input the hours worked and the wage rate. Determine
and print the gross pay, withholding and net pay. Use the following data:

Employee Hours Wage


Worked Rate
1 37 8.50
2 40 8.00
3 42 8.00
4 47 7.50
5 38 9.00
4. A driver who drives mostly in the city has kept records to determine if pre-
mium or regular unleaded fuel (gasoline) is more economical in his car.
He is careful to run the car until its 18 litter tank is nearly empty. Record-
keeping started with 6166Kms on its meter (odometer). The data are in the
following order: mileage at fill up, type, litters, price of fuel (gas) in rupees.
The program should find and print Kms per litter at each fill-up and cost per
Km, indicating the type of fuel (gas). It should also determine the overall
150 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

cost per Km for each type of fuel (gas) for the entire period covered. Use
the following data (“P” is premium, “R” is regular):

6166 P 17.0 130.9


6453 P 17.1 130.9
6766 R 17.2 121.9
7025 R 17.6 122.9
7306 P 17.3 131.9
7600 R 17.8 121.9
7874 P 17.9 133.9
8167 P 17.5 131.9
8430 R 17.1 118.9
8681 R 17.2 120.9
-1 0 0 0 (end)

(Note that, the Kms travelled for the second period is 6166 − 6453, the type
of fuel (gas) used was premium since that was used in the fill-up at 6453,
17.2 litters were consumed, and the price per litter of that fuel (gas) was
130.9).
The output should looks like the following table.

Mileage
Start End Type Kms per litter Rs. per Km
6166 6453 P 16.7836 7.79927

5. The management of a dock facility for ship traffic collects data on the traffic
passing through each week. There are two separate, parallel docks; a large
one, which can handle many small boats as well as large ships, and a small
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 151

one, which can handle small boats only. Let us consider: “S” and “L” are
the codes for the small and the large docks, and “E” and “W” are the codes
for east and west respectively; and a number, which is the number of vessels
in that operation. Use the following data

S,E,2; L,W,3; L,E,4; L,W,1; S,E,3; S,W,3; S,W,2; L,E,6; L,W,3; L,E,2;
S,E,2; S,W,2; S,E,3; L E,3; L,W,5; S,E,1; S,E,3; S,W,4; L,W,4; L,W,1;
L,E,4; S,W,2.

Your program should read the data, and print the number of vessels going in
each direction in each dock. A tabular display such as:

LARGE SMALL
WEST 17 13
EAST 19 14

would be convenient where the values are from the above data.
6. In a certain class, both graduates (G) and undergraduates (U) are enrolled.
Both receive a course grade based upon total weighted score:

Total Weighted Score Grade


< 60 F
≥ 60 and < 70 D
≥ 70 and < 80 C
≥ 80 and < 90 B
≥ 90 A
152 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

Undergraduates take two midterms, each weighted 30%, and a final, weighted
40%. For the graduates, two midterms are each weighted 25% and the final
is weighted 30%. A project accounts for other 20% of their grade. The pro-
gram should count and print the number of each grade for each of the two
groups and print student name, whether graduate or undergraduate, total
points and course grade, as given below.

Name G or U Points Grade


Ram U 70.3 C
Samir U 84.0 B
Bablu G 87.7 B
.. .. ..

Grade Distribution
Grade Graduates Undergraduates
A 3 3
B 4 4
C 1 3
D 0 1
F 0 1

The records are as following: The first column is a string, i.e., first name
(Name). The second column is a code for level of students (Level). The third
and fourth are the scores for the two midterms (Mid-I, Mid-II). The fourth
and fifth are also score for final examination (Final) and project (Project)
when applicable.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 153

Name Level Mid-I Mid-II Final Project


Amar U 56 89 67 –
Babu U 100 80 75 –
Star G 100 93 95 92
Cross G 77 89 94 90
Dalia G 88 92 97 94
Eila U 65 58 72 –
Fish U 98 86 94 –
Gouri U 52 71 48 –
Habu G 68 66 78 82
Tutul U 84 91 93 –
Illu U 94 81 74 –
Jamil G 96 87 90 88
Kali G 82 86 92 84
Labu U 76 84 79 –
Milon G 85 92 87 90
Nila U 95 89 91 –
Outo U 75 78 73 –
Palu G 75 80 88 79
Quta U 98 100 95 –
Rafi U 92 92 84 –

7. In dealing with foreign monetary systems it is often necessary to convert


their monetary units to the equivalent Indian rupee value. A particularly
troublesome conversion was the old English system, which used pounds,
shillings and pence as the basic monetary units. In the English system, one
pound equaled 20 shillings and one shillings equaled 12 pence. The problem
154 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

here is to write a program that will accept prices in the old English System
and convert them to the Indian System based on a conversion rate of one
pound equals Rs.x/−. Include in your output both the input English price
and the calculated Indian equivalent price. Assume the data appear in the
order pounds, shillings, and pence.

Example:
Let x = 50
Pounds Shillings Pence Rupees
4 10 0 225.00
0 15 0 37.50
10 0 6 501.25

8. A college charges tuition fee based on the number of credits taken, whether
or not the student is a state resident and whether the student is a graduate
or undergraduate. Undergraduates are charged Rs.100 per credit-hour up
through 15 credit-hours per quarter, with no additional charge beyond that
amount. Graduates are charged Rs.125 per credit-hour up through 12 cred-
its, with no additional charge for more credits. If the student is an in-state
resident, there is no further charge. If the student is an undergraduate from
out of state, there is a surcharge of Rs.500 per quarter; if he or she is an
out-of-state graduate student, there is a surcharge of Rs.200.

(a) Write a program to compute tuition fee based upon data input from the
terminal in the order : “G” or “U”, “R” or “N”, number of credits. (G and
U indicate graduate and undergraduate respectively, and R and N indicate
resident and nonresident respectively.) Here are some sample data and
results:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 155

Level Residency Credits Tuition (Rs.)


U R 17 1500
G N 18 1700
U N 12 1700
G R 3 375

(b) Write the same program described in part (a), but this time write a
single expression to compute tuition given level, residency and credits.
That is, do not use any conditional jump i.e., IF statements.

9. Write a payroll program that will accept data for each employee (such as
employee number, hourly pay rate and hours worked) during the past week.
Determine total pay as follows:
(1) Pay rate times hours worked up through 40 hours, plus
(2) 1.5 times pay rate times hours worked over 40 hours.
The program should print employee number, pay rate, hours worked and
total pay for each worker, and these grand totals (across workers): total reg-
ular rate pay, total overtime pay and total pay. The following data produce
the sample answers:

Employee Number Rate (Rs./Hr.) Hours Worked (Hrs.)


328 3.75 44
424 2.86 38
503 5.54 45
559 4.05 40
586 4.10 40
640 4.00 37
156 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

Employee Number Rate (Rs./Hr.) Hours Worked (Hrs.)


418 4.15 40
461 3.85 42
533 3.50 20
567 3.75 44
609 2.86 41

Employee Rate Hours Pay


Number (Rs./Hr.) Worked (Rs.)
(Hrs.)
328 3.75 44 172.50
418 4.15 30 124.50
424 2.86 38 108.68
...

Total Regular Rate Pay : 1608.68


Total Overtime Pay : 102.39
Total : 1711.07

10. An electric utility has a variable billing rate per kilowatt-hour (KWH). The
rate is a function of the type of consumer and number of kilowatt-hours
used. There are three consumer types with these codes: C (Commercial), I
(Industrial) and R (Residential).
Each consumer category has its own rate per kilowatt-hour as a function of
the number of kilowatt-hours used per month as given in the table below:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 157

Consumer Type Number of KWH Paise per KWH


C First 1000 50
Next 4000 80
Additional consumption 100
I First 1000 75
Next 4000 100
Next 5000 125
Additional consumption 150
R First 500 25
Next 500 40
Additional consumption 75

Example:
If a type C consumer consumed 5200 KWH, the bill (in Rs.) would be:
0.5 × 1000 + 0.8 × 4000 + 1.0 × 200 = Rs.3900.

(a) Write a program to input data from the terminal and print the amount of
the customer’s bill that includes: consumer’s type code and total kilowatt-
hours. A sample data is given below:

Code KWH Bill (rounded to


whole Paise)
R 1,237 Rs.502.75
I 12,361 Rs.14541.50
C 5,128 Rs.3828.00

You should also allow for the entry of “garbage” as a consumer type, for
example, if “Z” were accidentally entered as the consumer code, your
158 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

program should tell the operator that it is not a valid consumer code and
ask him or her to try again.
(b) Solve this problem using integer variables to indicate the true condition
for each class of customers.

11. A police department is counting crimes by hour of the day and type of crime
(i.e., whether against person or property). Times are recorded on the 24-hour
clock and coded as, for example, 1217 = 12:17 P.M., 23 = 0:23 A.M. (i.e.,
23 minutes after midnight), or 2359 = 11 : 59P.M. The codes “E” and “R”
denote crimes against person and property respectively. They counts each
type of crime for each hour of the day and totals for each type of crime.
Example:
Input:
Crime Crime Crime
type Time type Time type Time
E 0022 R 0037 R 0121
R 0137 E 0230 E 0230
R 0602 R 2117 E 1752
R 1442 E 2316 R 1519

Output:
Number against
Hour Person Property
0-1 1 1
1-2 0 2
... ... ...
— — —
Total 5 7
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 159

12. [Word Game]

(a) Write a program for the following student geography quiz. When the
program begins, the student should be greeted and asked to enter his or
her name, where the first and the last names are separated by a blank. In
the messages described below, the student should be addressed by his or
her first name, which you will have to extract from the name that was
input. The program should ask the student to name the capital of each of
several countries. The country names should be displayed one at a time
and the student prompted to type a response. If the response is correct,
an appropriate message should be printed. If the response is incorrect, the
capital name should be printed along with an appropriate message. The
program should also count the number of correct and incorrect answers
and print these for the student when the quiz is over. Here are several
countries and their capitals, which you can use:
Country Capital Country Capital
Bangla Desh Dacca Ecuador Quito
Belgium Brussels France Paris
Burma Rangoon Germany Berlin
Canada Ottawa India New Delhi
China Beijing Sri Lanka Colombo
Chile Santiago
The program should be set up to trap end of data so that arbitrarily many
countries can be used in the quiz.
(b) When the student enters an incorrect capital, the program should give
hints. After the first miss for a given country the first letter of the capital’s
name should be printed as a hint; after the second miss print the first
two letters; and after the third miss print the first three letters. If a wrong
160 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

answer is given after the third hint, the program should treat it in the same
way as a wrong answer is treated in (a). In addition, variable points should
be awarded based on how many hints the students requires:
Number of Number
hints before of Points
Correct An-
swer
0 4
1 3
2 2
3 1
An incorrect answer after three hints results in zero points. When the quiz
is over, the student’s total points and the maximum possible points should
be printed. (Maximum possible points is the number of countries times 4,
so the program has to keep track of the number of countries.)

13. [Word Game]

(a) Write a program to play the game of “Hangman”. In this version of the
game there is a player and an opponent, in this case the opponent is the
computer. The opponent thinks of a word and you try to guess what is
by guessing letters that might be in the word. If you make three incorrect
guesses on a given word you are “hanged”; that is, you lose the game.
The words the computer “thinks” of are in a file and the player is asked
to select the number of a word between 1 and the total number of words
in the list. The program then counts down the list and selects the word
that corresponds to the number entered. Here is a sample of part of a
game. Assume the word is “dumetose”; note that the number of dashes
corresponds to the number of letters in the word:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 161

Select a word between 1 and 10 (0 to stop)? 10


The word is : "----------"
Guess a letter ? e
Correct; "----e----e"
Guess a letter ? a
Sorry, no "a"; miss number 1
Guess a letter ? t
Correct; "----et---e"
Guess a letter?

and so on.
If the player loses the game, the program should respond with an appro-
priate message and tell the word to the player:

Guess a letter? n
Sorry, no "n"; miss number 3
You lose this game; the word is "dumetose"
Select a word between 1 and 10 (0 to stop) ?

If the player wins, the program should congratulate him or her. In both the
win and loss cases, the program can go back to the beginning and print
the “Select a word...” prompt.
(b) Instead of asking the player to choose a word, use a random number
generator (with fixed seed) to generate the number of the word to be cho-
sen. Your program should be set up so that each word will have equal
probability of being selected and so that it will adjust the probabilities
162 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

automatically when the number of words changes. Use another random


number generator (with system time as the seed) at the start of the pro-
gram to generate a different sequence of words each time the program
is run. If you do not use this, the program will always select the same
sequence of words.

14. Write a program which will generate a deck of randomly suffeled 52 playing
cards which contains 4 types (club, diamond, heart and spade) and also each
types of cards numbered from 2 to 14 (the number 11 = J, 12 = Q, 13 = K
and 14 = A). Also divide them into 4 sets each set contains 13 cards. Print
all these 4 different sets. Also sort each of the sets and print them.
15. Consider the problem of converting from Roman numerals to Arabic nu-
merals, and vice verse. Since this is rather complicated to do, this problem
has several parts to it, to make it a bit easier. The following table shows the
Roman symbols, we will be using together with their Arabic values.

Roman Arabic
M 1000
D 500
C 100
L 50
X 10
V 5
I 1

As you probably know, there are many peculiar conversions in using Roman
numerals. For example, 4 is usually written as IV instead of IIII, and 90 as
XC instead of LXXXX. Presumably the point is to minimize the length
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 163

of the Roman expression. You can ignore these conversions, and assume
instead that the Roman expressions will be written so that the Roman values
get no larger going left to right - for the following problems (a), (b) and (c).

Example:
XXXX instead of XL for 40, or LXXXX instead of XC for 90. Here is a set
of data you can use to test your programs:

Roman Roman
Arabic (Parts a, b and c) (Part d)
6 VI VI
9 VIIII IX
24 XXIIII XXIV
52 LII LII
99 LXXXXVIIII XCIX
1449 MCCCCXXXXVIIII MCDXLIX
1999 MDCCCCLXXXXVIIII MCMXCIX
(a) Write a program to test a Roman-represented number for correctness
in the sense noted above (i.e., as you move from left to right the values
get no larger).
(b) Write a program to translate from Roman numerals into Arabic. The
program should input the Roman representation as a string. Print the Ro-
man and Arabic representations.
(c) Write a program to translate from Arabic representation into Roman.
164 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

(d) Write both of the above programs with the following conversions:
Arabic Roman Conversion
4 IV
9 IX
40 XL
90 XC
400 CD
900 DM
This gets fairly messy, but rather interesting. You can get an idea from the
examples above how these conversion works. The conversion from Roman
to Arabic is probably the easier of the two cases. You might also think about
some method for checking Roman input for correct form, given these con-
versions.
16. Mr. I.N. Bagchi is the manager of a vacuum cleaner sales team. Mr. Bagchi
is responsible for paying commissions to his staff on the basis of their sales
performance relative to a negotiated goal. The table below shows the staff’s
performance for the last quarter. The sales representatives are paid a com-
mission of Rs.1000 times the percentage of goal achieved. For example,
Amar Kumar Saha will receive a commission of Rs.1100 for exceeding his
directed goal by 10%.

Sales Person Goal (Rs.) Sales (Rs.)


Amar Kumar Saha 8000 8800
Uttam K. Dan 9000 8200
Probir Dhar 7000 7300
C. V. Rajan 7000 7800
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 165

Mr. Bagchi has asked you to write a program to calculate each sales per-
son’s commission. The output from your program should include each sales
person’s name, goal, sales value and commission for the quarter.
17. The following three problems involve in experiments and variations on hash
functions.

(a) The performance of a hashing method depends on the “quality” of the


hashing algorithm and on the amount of space allocated for the table. In
general, the more space available in a hash table means better the search
performance in better. An experiment performs on a hashing algorithm
with the 50 state code and 79 table slots (space). Perform the same exper-
iment on different table sizes; for example, in addition to the 79 spaces
try 59, 67, 73 and 89. For each table size, determine the total number of
table “probes” to find all 50 codes. A probe is the comparison of one table
entry with the desired value.
(b) It is possible to develop a perfect hash function - one that requires only
one space per table value yet has no synonyms (i.e. alternatives); that is,
each value hashes to a unique location. Unfortunately, the algorithm re-
quired for a perfect hashing is very expensive in computer time to derive if
there are over about 30 values in the table. Nevertheless, it may be worth-
while to search for an “almost” perfect or “minimally” perfect function.
A minimally perfect function is one that requires only slightly more space
in the table than there are values. An almost perfect function would be
one that didn’t require any extra space but had a (very) few synonyms.
Try different functions and space on the state codes to see how well you
can do. Examples of varieties of hash functions include
(1) Instead of multiplying the numeric value of the first letter by 26, try
other multipliers.
166 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

(2) After converting the two letters to a numeric value, say STNUM,
square STNUM and “extract” the digits in the thousands and ten thou-
sands places. This will give a value in the range 0 to 99, which may
then be multiplied by a value less than 1 to transform the result into the
range of addresses of the hash table. For example, suppose the numeric
conversion of CA is 1807; 1807 squared is 3265249. The two digits in
the ten thousands and thousands places are 65. If we have 79 positions
in the table, we multiply by 0.79, take the integer part, and add 1. The
result is 52.
(c) Another method of improving hash performance lies in the way syn-
onyms are handled. Here are some ideas you might experiment with:
(1) Rather than stepping by 1 when a key value hashes to an occupied
location, make the step size function of the hash location. For exam-
ple, given a key value V with hash value H, the step size might be
set to (H MOD 13) + 1. A numeric example, suppose V hashes to
H = 67. If hash table location 67 is occupied (on a store operation)
or does not contain the value V (on a search operation), the step size is
(67 MOD 13) + 1 = 3. If V hashes to location 26, the step size would
be 1 (26 MOD 13 + 1). The effect of this method of handling synonyms
is to scatter them out. It is always better than a fixed stepping by 1. It
usually reduces the number of probes.
(2) Store synonyms in a separate area.
Example: suppose a key V is to be stored in location H of a hash table
and a key value already occupies that location H. Using a different hash
function, hash V into a new table. If it encounters a synonym there also,
use the synonym handling method described above.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 167

(3) Use a linked list to chain synonyms together. They may be chained
together in the table or the chain may lead into another separate table
called the “independent overflow area with chaining”.

18. A different variety of search scheme uses an “index” to spend finding the
location of a value in a table. We use indices very frequently when doing
manual searches in reference material. For example, encyclopedias use sev-
eral indices, one in the form of a range of topics printed on the cover of each
volume of the encyclopedia. Another example of an index is the card cata-
log in a library. Each drawer of the catalog has a range of letters indicating
the range of subjects (or titles or author names) on the cards in the drawer.
Consider now the use of an index to speed the search for a state code. First,
the codes must be in alphabetic order. We show them below along with their
element numbers:

1 2 3 4 5 6 7 8 9 10
AK AL AR AZ CA CO CT DE FL GA
11 12 13 14 15 16 17 18 19 20
HI IA ID IL IN KS KY LA MA MD
21 22 23 24 25 26 27 28 29 30
ME MI MO MN MS MT NC ND NE NH
31 32 33 34 35 36 37 38 39 40
NJ NM NV NY OH OK OR PA RI SC
41 42 43 44 45 46 47 48 49 50
SD TN TX UT VA VT WA WI WV WY

An index that will provide very fast retrieval, this can be constructed to
indicate the starting position in the table of codes where codes are beginning
168 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

with the letter A, B, · · · , Z. This index would be:

ABCDEF G H I J K L M N O PQ R S T U VWXYZ
1 0 5 8 0 9 10 11 12 0 16 18 19 27 35 38 0 39 40 42 44 45 47 0 0 0

Example:
The index shows that the codes beginning with a letter “A”, start at location
1; those beginning with an I starting at location 12, and so on. The index
shows 0 for letters that do not exist as first letters of codes: B, E, J, Q, X, Y
and Z. The letters themselves do not need to be stored in the index; rather
we access the index directly using the ASCII function as follows: The first
character of a desired code is extracted and its alphabetic position deter-
mined using ASCII. Since A has position 65, B position 66, · · · , Z position
90, the index position for a letter is the ASCII value of the letter minus 64.
Given a code, we extract the first letter, determine its ASCII value, and sub-
tract 64. The index is entered at that location and it tells us where to begin
the search for codes with that first letter. We enter the table of codes and
search for a match using a linear search. The longest linear searches require
7 probes - to find NY or MT. Write a program to input the table of codes,
create the index from the codes, and use the index to locate codes.
19. The following problems involve in searching methods including variations
on bisection search.

(a) A linear search is a search in which values are examined in consec-


utively higher storage locations until the desired value is found. An im-
provement on linear search is to skip forward in the table by greater than
1 location at a time until you locate the desired value or determine that
you have skipped past it. If you skip past it, use a linear search backward
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 169

to find the desired value. As an example, consider the following 10 values


that were used to demonstrate bisection search:
Element 1 2 3 4 5 6 7 8 9 10
Value 12 17 20 25 29 31 36 49 55 56
The value we want to find is 25. Suppose we use a skip size of 3. Then, the
first value examined is 20, at location 3. This is smaller than the desired
value so we skip ahead another 3 elements to element 6 with value 31.
This is too large, so we search sequentially backward until we find the 25.
To implement the search we must handle the problem caused by the last
element 10, not being a multiple of our skip size. One way to handle this
is to define elements 11 and 12 as large values that will never be sought,
e.g., 1.0E20.
How should the skip size be selected? It is possible to show that under rea-
sonable assumptions the skip size that minimizes the number of probes is
a skip size equal to the square root of the number of elements in the table.
For example, with a table of 100 elements the skip size should be 10; with
1000 elements a skip size of about 31 or 32 is appropriate. How many
probes do we expect with the skip size selected this way? The average
number of probes will also equal the skip size. Thus, a table of 1000 el-
ements can be searched in an average of about 32 probes. This is vastly
superior to the linear search, which would require about 500 probes but
is not as good as the bisection search, which requires only 9 probes on
the average; however, in some ways the skip search probes tend to be less
expensive than bisection search probes. Write a program using, for exam-
ple, the state code data entered in alphabetic order. Use the skip search to
retrieve values.
(b) A variation on the bisection search is to search until we have nar-
rowed the possible elements to, say, 10 or less, then use a linear search on
170 CHAPTER 8. PROGRAMMING USING COMPLEX CONDITIONS

these remaining values. While the number of probes is greater, the linear
probes will be cheaper, hence the overall search time may be reduced by
this scheme. Write a program that utilizes this variation on the bisection
search.

20. Read an English sentence and code it using some technique known only to
you and the computer. The computer must be able to decode it. Start with
just a simple exchange of letters. You can then start using random number
series to cope either with type or groups of letters.
The cracking of codes is a science in itself (cryptography), but it is often
worth working with a friend to crack each others’ code.
Chapter 9
ADVANCED PROGRAMMING PROBLEMS

In this problem set, number of mixed application programs has considered


to learn programming techniques. Implement the following problems using a
conventional programming language.

1. In a data processing course , 4 quizzes will be held. Each quiz carries 15


marks. For each student, the total marks for the quizzes will be obtained
by summing up the best three scores out of four scores. A student who is
absent in a quiz gets zero for that quiz. Each student is identified by an inte-
ger registration number. You are required to write a program which accepts
the student registration number and scores in the four quizzes and this will
output the quiz total.
2. The bubble sort procedure works as follows. Suppose the list of numbers 7,
5, 2, 11 and 8, is to be rearranged in ascending order. The first two numbers
are compared, and if out of order, they are swapped. Then the second and
third number are compared and if out of order, they are swapped and so on.
If the bottom of the list is reached without any swap being made, then the list
is stored. Otherwise another pass is made. With the given list, the following
stages occur.

171
172 CHAPTER 9. ADVANCED PROGRAMMING PROBLEMS

Input Pass 1 Pass 2 Pass 3


7 5 5 5 5 2 2 2 2 2
5 7 2 2 2 5 5 5 5 5
2 2 7 7 7 7 7 7 7 7
11 11 11 11 8 8 8 8 8 8
8 8 8 8 11 11 11 11 11 11
Note that, in every pass the largest number moves to the bottom and the size
of the list yet to be sorted decreases by 1.
3. A is an array of integers of size n. We want to sort these numbers in an
ascending order. To accomplish this, we have to make n − 1 passes over this
array. In the first pass we find the maximum of n numbers in the array A
and then interchange this number with the nth number. In the second pass
we find the maximum of first n − 1 numbers of A, and then interchange this
number with the (n − 1)th number of A; so on in the subsequent passes.
Write the program.
4. A file, EVENTS consists of records of events that have occurred during a
calendar year. Each record describes one event and starts with a data file
giving the number of day in a year during which the event occurred. The file
is ordered in ascending order by this number.
A file SELECT consists of single-field records, the field being a day number.
This file is ordered in ascending sequence by this field.
Write a program which reads these 2 files and produces a report which
shows, for each data in SELECT, the number of events which occurred on
that date. For example
Day 13 45 ... 352
Events 12 6 ... 4
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 173

5. A publishing company holds in a file details of all books they publish. How-
ever, in future they wish to maintain two distinct files (i) paperbacks, (ii)
hardbacks.
Write a program which reads a file having details of both paperback and
hardback books, and creates two files as specified above. Assume that the
first character in each input record indicates if book is paperback (p) or
hardback (h) or both (b).
6. A file contains following information about the shareholders of a company.
(1) Ledger folio number,
(2) Name of the shareholder,
(3) Address of the shareholder,
(4) Number of share held, and
(5) Value of share held (at par).
When a transaction takes place, the file has to be appropriately updated. You
are required to write a program which inputs information about the trans-
action (folio number of buyer, folio number of seller, name and address of
buyer, name and address of seller, number of shares transacted) and update
the file. Your program must take care of the following situations.

(a) When the shares held by a shareholder drop to zero, the corresponding
record must be deleted.
(b) In case the folio number of buyer is not specified then he is to be treated
as a new shareholder and a new record (and ledger folio number) have to
be created for him.
(c) If the ledger folio number either does not exist or does not correspond
to the name of the seller or buyer as given in the file, then an error message
must be displayed.
174 CHAPTER 9. ADVANCED PROGRAMMING PROBLEMS

7. An n×2 array, JOB is supplied as input. The data in JOB refers to a job shop.
For each i lying between 1 and n, JOB(i, 1) and JOB(i, 2) give the number of
two jobs such that JOB(i, 1) must be completed before JOB(i, 2) can begin,
i.e., the array JOB defines the precedence constraint existing between the
jobs. In order for the data to be consistent, the precedence constraint on the
jobs must be loop free, i.e., it should not be implied that there is a job which
must precede itself. You are supplied n and JOB, and you have to check
whether the data in JOB is consistent. If the data is consistent you have to
output the job numbers in a linear sequence which is consistent with the
given precedence constraint.
8. A company’s actual sales data (in number of units sold) for the past n years
(say, upto 1993) is available, and the company wants to forecast the sales
figures for the next m years (starting with the current year). The forecasting
method is explained with an example below. As will be seen from the ex-
ample, the forecasting for any specific year is the weighted sum of the sales
data (actual, or forecast if actual is not available) for the previous p years.
Example:
Let n = 6, p = 5, m = 3
Weights 0.10 0.20 0.20 0.20 0.30
Year 1988 1989 1990 1991 1992 1993
Sales 1200 900 800 700 1000 1100
with these data the forecasts will be shown below:

Year Forecast
1994 900 ∗ .1 + 800 ∗ .2 + 700 ∗ .2 + 1000 ∗ .2 + 1100 ∗ .3 = 920
1995 800 ∗ .1 + 700 ∗ .2 + 1000 ∗ .2 + 1100 ∗ .2 + 920 ∗ .3 = 916
1996 700 ∗ .1 + 1000 ∗ .2 + 1100 ∗ .2 + 920 ∗ .2 + 916 ∗ .3 ≃ 949
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 175

(The figures in bold above illustrate the use of forecasts in calculating other
forecasts.)
You are required to write a program that inputs n, m, p the actual sales data
for the previous n years and the values of the p weights, and outputs the
sales forecasts for m years starting from the current year.
9. Write a program to produce monthly statements for the customers of a bank.
Assume that a file is sorted (i.e. ordered) by account numbers and it contains
the balances in the accounts at the end of the previous statement period. A
second file contains details of payments to and withdrawals from the account
during the current statement period.
The program should output a statement for each customer. The statement
should be headed by the account number and list the balance brought for-
ward, the transactions and the balance carried forward.
Ensure that your program also produce an updated balances file and records
any invalid data in an error file.
10. Write a program which reads n followed by a set of n numbers and m fol-
lowed by a set of m numbers. Determine whether the second set is one of
the following three. (a) a subset of the first, (b) a proper subset of the first,
and (c) neither (a) nor (b).
11. Write a program which takes a pattern (P) and a dictionary of words (D) and
outputs a list of those words in D that match P. The P may be composed of
letters plus 2 special characters:
176 CHAPTER 9. ADVANCED PROGRAMMING PROBLEMS

. Matches any single character, and


∗ Matches any sequence of characters including the empty string.
Example:
The pattern CAT matches the word CAT,
The pattern C.T matches the words CAT, COT, etc.
The pattern C.T ∗ S matches the words CATS, CATCHES, etc.
Note that, there may be atmost one occurrence of ∗ in any P.
12. You are required to write a program which processes requests for seats on
an aircraft. The aircraft has 40 rows of seats with 8 seats in each row. As-
sume that the rows are numbered 1 to 40 and that the seats within a row are
numbered from 1 to 8.
Seats within each row are arranged as shown below:
WSSASSSSASSW
Seat No. 1 2 3 4 5 6 7 8
where W represents a window, S a seat and A the aisle (passage).
The first 10 rows are first class (F), the next 20 rows are ordinary class (O),
and the remaining 10 rows are economy class (E). A request for seats will
be in the form of a pair with the first entry giving the number of seats re-
quired and the second entry gives the class. For example, 13 and F means
that 13 first class seats are required.
Initially, the aircraft is empty and you are to process a number of requests
till the number of seats required is entered as zero. For each request, the
allocation of seats is done as follows:

(1) The minimum possible number of rows should be used to satisfy a re-
quest for seats. If enough seats within the requested class are not available,
then the request is completely rejected.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 177

(2) Within a row, attempt is made to seat people without an aisle interven-
tion. If this is not possible, allocation is done arbitrarily.

Note that, condition (1) is independent of condition (2), that is, while select-
ing the rows to use in order to satisfy a request, one need not take condition
(2) into account. For each request your program should output:
(a) The request itself, and
(b) The row numbers and seat numbers used to fill the request or a suitable
message if the request was rejected.
13. An executive based in Delhi wants to fly to Calcutta-Kolkata and fly back
to Delhi as soon as possible with a stopover of at least n hours at Calcutta-
Kolkata. He has available with him a time table in the form of an array
of records. Each record contains the following information. Flight number,
source and destination of the flight, the days of the week on which the flight
operates (e.g., MWF means that the flight operates on Mondays, Wednesdays
and Fridays. S stands for Saturday and U for Sunday) and the departure and
arrival times on a 24 hour clock (e.g. 0900 means 9 a.m., while 1630 means
4:30 p.m.). You are required to write a program which accepts the value of n
from the user, the day of the week and the earliest time when the executive
can leave, and suggests a flight pair which will meet his requirements.
14. In a factory X there are n jobs to be completed. Each job contains two op-
erations, the first one is to be done on machine 1 and the second one on
machine 2 (order is important). For each of the n jobs the processing times
on machine 1 and machine 2 are given and our task is to find a processing
sequence of the jobs which will complete all jobs in the shortest possible
total time. Note that, the sequence will be identical on both machines. A
method which will accomplish the task is as follows:
178 CHAPTER 9. ADVANCED PROGRAMMING PROBLEMS

Find that job which requires minimum time on machine 2 and sequence it as
the nth job; then find that job which requires the minimum time on machine
1 and sequence it as the first job; and so on, till all jobs have been sequenced.
Break ties arbitrarily.
Write a program which will input n, the processing times for the n jobs on
each of the machines. Output the processing sequence and the total time
taken for processing all jobs. Also output machine ideal times for each ma-
chine.

Example:
Let n = 6 and the processing times as given below:
Job 1 2 3 4 5 6
Machine 1 30 120 50 20 90 110
Machine 2 80 110 90 60 30 10

The best sequence is 4, 1, 2, 3, 5, 6. The total processing time and machine


ideal time (if any) can now be easily calculated.
15. A bank pays monthly interest to depositors on the minimum balance in their
accounts between the 10th and the end of the month. You are given two
files containing the relevant data. The first is a Master File containing the
opening balance of each account (assumed to be ≥ 0); the significant fields
are the account number and the opening balance. This file is kept sorted
on account number and obviously, contains only one record per account.
The second file is the Transaction File which contains all the transaction
data (deposits and withdrawals) of the account number (as before), type
of transaction (Character : D for deposit, and W for withdrawal), amount
transacted and date of transaction (containing 8 integers for year, month and
day). This file is sorted by account number and date of transaction. You are
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 179

required to write a program which will read the master and transaction files,
and produce a new file (sorted on account number) which gives, for each
account, the amount of interest (at the annual rate r%) to be paid for the
month.
16. A company which is raising Rs.N/- through a public issue of shares is pro-
cessing share applications. Each share has a face value of Rs.F/-. Each ap-
plication contains the following data: Application number (unique integer),
name and address of applicant, and number of shares applied for (only in
multiples of U, and a maximum of M shares). The total amount applied for
is much greater than N and hence there is the issue of allocation of shares
to applications. The process followed is described below. Applications are
sorted and the applications are divided into separate categories in (M div
U). Within each category the applications are arranged by increasing order
of application number. Then the following process is followed. First a table
ALLOT is prepared as shown below (You are not to be concerned with how
this table is prepared): (assume U = 50, M = 200, N = 100,000, for the fol-
lowing table)
Category Amount to Block size Allot for blocks to
be raised
50 50,000 20 2, 5, 9, 15, 17
100 25,000 15 1, 14
150 15,000 20 2, 6
200 10,000 8 3, 4, 5
The above table implies that a sum of Rs.50,000/- will be raised from the
applications in the 50 share category. These applications are divided into
blocks containing 20 applicants each, and from each such block the second,
fifth, ninth, fifteenth and seventeenth applicants will be allotted shares.
180 CHAPTER 9. ADVANCED PROGRAMMING PROBLEMS

You are given the application data in a file, sorted in ascending order of
number of shares applied for (category), and secondly by application num-
ber within each category. You are to input N, M and ALLOT and output the
application number, name and address, and number of shares applied for, for
each successful allotment. Your output should be sorted just like the input
file is.
17. In a certain questionnaire based survey, a particular question has R (≤ 9)
possible choices, and a single respondent may tick any number of these.
Responses to these questions are stored as arrays of characters (with each
array containing R characters) For example if R = 7, and a particular respon-
dent choose alternatives 1, 5 and 6 then this response may be represented by
156bbbb (b represents space) or as bb56bb1 etc. Note that, the responses
may be encoded in any order and there may be any number of spaces in-
terspersed in the encoding. Given R, N and the responses of N respondents
you are required to output the number of respondents who choose only ‘1’,
only ‘2’ etc, as well as those who choose ‘1’ with some other(s) (but not ‘1’
alone), ‘2’ with some other(s) (but not ‘2’ alone), etc.
18. You are given a piece of English text. Count the relative frequency of indi-
vidual letters in the text. Using these frequencies design an optimal binary
code (Hoffman code) for the letters to achieve minimum coded text length.
Convert the given text to this binary coded form.
19. A toy manufacturer in Kolkata is expecting a bumper sale during the forth-
coming Puja fortnight. Each of his toys cost less than two rupees, and the
price is always a multiple of five paise. He knows that most customers will
pay for a toy with a two rupee note. He has a supply of five paise, ten paise,
twenty five paise, fifty paise and one rupee coins. In view of the acute short-
age of small change, he wants to be able to return the change to a customer
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 181

with the smallest possible number of coins. He has turned to you for help.
Given the price of a toy as input, needed for returning the change, assuming
that the payment in coins of each denomination as well as the total number
of coins. Draw the flow-chart and write a program.
20. A transport operator in Bombay has m trucks with each truck having a spec-
ified carrying capacity in kilograms. There are n items to be carried: each
item has specified weight in kilograms and is to be transported to a partic-
ular destination. We assume that the shapes and sizes of items loaded on
a truck do not matter in considering the carrying capacity of a truck, and
that weight is the only relevant factor. Initially all trucks are empty and may
be directed to any destination. A given truck, if used, may go only to one
destination, and only items bound for that destination may then be loaded
on it. Each item must be reached to its destination whether or not the truck
on which it is loaded is filled to capacity. The objective is to minimize the
number of trucks used for transporting the given lot of n items. It may be
assumed that the given m trucks are always sufficient to carry the n items.
The above problem is generally quite difficult, but the transport operator
uses the following method which he has found to be satisfactory (though
not always giving the best possible solutions).

(1) Items are taken one by one for allocation;


(2) To allocate the ith item, all the trucks on which it can be allocated are
considered first and their unutilized capacities noted;
(3) The item is then allocated to that truck among these in which there will
be minimum unutilized capacity after allocating this item (This method is
usually referred to as ‘Best Fit’).
182 CHAPTER 9. ADVANCED PROGRAMMING PROBLEMS

Example:
Suppose the ith item has a weight of 10kgs, and there are three trucks in
which it can potentially be loaded, with the unutilized capacities in these
being 14, 12 and 17 respectively, then the item will be allocated to the sec-
ond of these trucks.
The above allocation procedure is followed till there are no more items to
be allocated.
A detailed illustration is worked out as follows:
Illustration:
Let M = 8, N = 10.
Truck capacities: 1000, 1000, 2000, 2000, 1500, 3000, 3000, 2000 Kgs.

Item Details
No. 1 2 3 4 5 6 7 8 9 10
Wt 200 700 200 500 700 100 1000 900 1000 250
Dt Cal Del Del Cal Cni Del Cal Cal Cni Cal

The solution will be as follows:


Truck loading and destination
Truck No. Destination Item Numbers allocated
to truck
1 Cal 1, 4, 10
2 Del 2, 3, 6
3 Cal 7, 8
4 Cni 9
5 Cni 5
Truck 6, 7 and 8 are not used.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 183

Item loading
Number 1 2 3 4 5 6 7 8 9 10
Truck No 1 2 2 1 5 2 3 3 4 1
(Note that, the solution obtained using the suggested method is not the best
possible one. A better solution would be to load items 9 and 5 into truck 4
itself, but you need not worry about such things).
You are to write a program which will input m, n, the capacities of the m
trucks and the weights of the n items. It should use the allocation method
employed by the transport operator, and output the following: (1) Truck
loading and destination (for each truck its destination, as well as the item
numbers which will be loaded onto it); (2) Item loading (for each item, the
truck on which it should be loaded).
21. Five teams are participating in a football tournament. Each team has already
played once against all the other teams. For each team, data on the goals
scored by it and the goals scored against it are available. As per (nonstan-
dard) rules of the tournament, two teams having the top two goals (score),
differences should clash in the final. Goals difference for a team is the dif-
ference between the goals scored by it and the goals scored against it. You
are to write a program which will accept for each team, its team number
(between 1 and 5), goals scored by it and goals scored against it, and output
the team numbers for the two teams which will clash in the final. Ties, if
any, are to be resolved in favor of the team with largest team number. An
example is provided below. With this data, teams 4 and 5 will clash in the
final.
184 CHAPTER 9. ADVANCED PROGRAMMING PROBLEMS

Team Goals Goals


No. for against
1 9 7
2 12 13
3 0 8
4 11 6
5 7 5
Also give a brief description of the logic used in your program.
22. (a) There are n cities in a country which a sales person needs to travel. It
is possible to go from any one city to another traversing a distance equal
to the Euclidean distance between them. The salesperson starts from one
city and after traversing all n cities comes back to the starting city. Find a
total length (called the optimal tour ).
(b) Run your program for n = 5 or 6. Is it taking too long time? Modify
your program so that it runs really fast. You may have to sacrifice opti-
mally and find a tour which is at most twice as long as the minimal one.
23. Let (a1 , a2 , a3 , · · · , an ) be a permutation of (1, 2, 3, · · · , n). The inverse of (a1 ,
a2 , a3 , · · · , an ) is a permutation (b1 , b2 , b3 , · · · , bn ) such that for all i, j ≤ n,
bi = j if a j = i.
For example, 351642 is an inverse of 361524. Write the program which
inputs a positive integer n and a permutation (a1 , a2 , a3 , · · · , an ) and outputs
its inverse. You should use only one array of n entries in your program.
24. Chebsyshev polynomials are defined as follows:
T (0, x) = 1, T (1, x) = x,
T (n + 1, x) = 2xT (n, x) − T (n − 1, x), for n ≥ 1.
Write a recursive program which reads positive integer i and x, and calculate
the value of T (i, x).
Chapter 10
INPUT AND OUTPUT OPERATIONS

Implement the following problems related to input and output operations using
a conventional programming language.

1. Write a program which asks your name as input. Print out the message
“Good morning ”, where your name is put in the gap by the computer.
2. Write a program which accepts three names of your friends as input. Output
a message such as “Computer programming is nothing but a fun. Why don’t
you try it?” three times, putting one name at a time in the space.
3. Write a program which accepts few first names of the members of your fam-
ily members and the family name. Output a list of members of the family,
adding the family name in each case.
Example:
Input : Joti, Moti, Bali, Sur
Output : Joti Sur, Moti Sur, Bali Sur
4. Write a program which accepts the name of each member of a society as
input and print out membership cards for the society, including the expire
date and member’s name.
5. Write a program which accepts the name, date of birth and status of a mem-
ber as employee (permanent/temporary) or students/research scholars (one-
year, 2-years, 3-years, 4-years, 5-years) or others of an Institute as input.
Print out an identity card, an user’s card for the computer center and li-
brary card of the Institute. Each card includes name, age, status and the
expire/validity date also keep a space for a passport size photograph and a

185
186 CHAPTER 10. INPUT AND OUTPUT OPERATIONS

space for his/her signature. The expire date depends both on date of birth
and status. Note that, a permanent employee can work upto 60 years of age.
6. Write a program for which a list of names (each on a new line) is input and
get the computer to print after the first five names “The list is now full but
the next two names are reserves”. The computer stops running after these
two names have been added.
7. Write a program which asks for two words which may be joined either way
round. Arrange for the computer to print the pair of words both ways round;
you may include a gap between the words if you wish. For example, OUT
and LAST can combine to give OUTLAST or LASTOUT.
8. Program the computer to ask a question to which the answer is yes or no
(recognized by YES or Y/y or NO or N/n). Provide a suitable reply for the
computer to make.
Example:
“Are you hungry?” Y/y
“You should have eaten your breakfast!” N/n
“Good, time for another program!”.
9. Type in a list of words, each on a new line, and arrange for the computer to
cause you to type them diagonally. Your output might look like:
What
is
your
name?
10. Write a program which accepts a number up to 3 as input. Output “You
typed in ” where ONE, TWO or THREE is put in the space by the com-
puter.
11. Write a program to find the first
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 187

(a) 20 square numbers, for example,


4 as xx and 9 as xxx
xx xxx
xxx
(b) 10 triangle numbers, for example,

3 as x and 10 as x
x x xxx
x x x

12. Write a program to print the alphabet in (a) upper case, (b) lower case letters.
(Hints: Use ASCII code).
13. Write the following programs:

(a) Input upper case letters and output the same letter in lower case. (Hints:
Use ASCII code).
(b) Input a word in upper case lettering. Output (i) the entire word in lower
case lettering, (ii) all but the first letter in lower case.

14. Write a program which will pick up all names, beginning with C, from a list
of data.
15. Write a program which accepts a word as input and print out a string of ∗
equal in length to the number of characters in the word.
16. Input n words in a program and its outputs are (a) the total number of let-
ters used, (b) the average length of word, (c) the longest word, and (d) the
shortest word.
17. (a) Input a simple sentence without gaps at the beginning or end, and detect
how many words are there by the number of spaces. (Assume that there
188 CHAPTER 10. INPUT AND OUTPUT OPERATIONS

are no punctuation marks such as , ; : ”). Hence deduce the average


length of word in the sentence.
(b) Extend this idea for (i) different technical subjects and (ii) foreign lan-
guages.
18. Input a full name in a program and output the family name preceded by
initials.
19. Input the latitude and longitude of two places on the Earth’s surface. Output
the Great Circle distance and bearing of the second with relation to the first.
20. A file contains (with particular uniform format) the following: the students
registration/roll number, name, course code, grade, gpa, cgpa, rank and an-
other file contains course code and its full name. Write a program which
will print the grade sheet where students registration number as input. Also
extend this printing program for a range of registration number as input.
21. Write a computer program to print a Boolean matrix as ′.′ for false and ′ ∗′
for true with no blanks.
22. On an input card (i.e., 80 column line) there is just one string of consecu-
tive non-blank alphanumeric characters. We will call a string of consecutive
characters, that is, a block of all characters in the string are identical. You
are required to find the length of the largest block of non-blank characters
in the given input string. For example, the input card may have ten blanks
followed by the string. B L L L C ” - D D D K M M M M 1 1
3 B followed by fifty blanks. Then the length of the largest block (namely
MMMM) is 4.
You are required to output the length of the largest block and number of
such largest blocks.
23. Two input cards (i.e., lines) are supplied. On the first input line there is
a string of non-blank alphanumeric characters of length atmost 80 which
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 189

starts at column 1. Any blanks are at the right end of the string. No blanks
are interspersed among the non-blank characters. The second input line con-
tains a similar string of non-blank characters starting from column 1, but of
length atmost five. If the string in the second input line occurs as a substring
anywhere in the first input line, then you are required to delete such an
occurrence from the first input line, and pack the remaining non-blank char-
acters, i.e. move them to the left so that no blanks remain embedded among
the non-blank characters. For example, if the first and second input strings
are ‘CDBCABABCCDDEABCAB’ and ‘ABC’ respectively. And the rest of
them are blanks (or null) then after modification the first string would look
like ‘CDBCABCDDEAB’.
You are required to print out the modified string.
24. Write a program which will accept a character as an input directly from
the key-board. Print this character with its scan/ASCII code. [Don’t use re-
turn/enter].
25. Write a program which will accept an input string directly from the key
board. Print this as a character string.
26. Suppose a file or a matrix of size n × m contains a set of integers between
0 and 9. Generate another matrix of size 3n × 3m by replacing each num-
ber (0, 1, · · · , 9) of the input matrix by the following 3 × 3 patterns which
corresponds to a number indicated in the first bracket under each pattern.

0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0
0 0 0 0 1 0 0 1 1 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
(0) (1) (2) (3) (4) (5)
190 CHAPTER 10. INPUT AND OUTPUT OPERATIONS

0 1 0 0 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
1 1 0 1 1 0 1 1 0 1 1 1
(6) (7) (8) (9)

Print the output matrix as ′ .′ for 0 and ′ ∗′ for 1.


Modify the above program in the space constrained environment such as

(a) Directly print ′.′ and ′∗′ pattern without generating the output matrix,
where input matrix is in the primary memory.
(b) Repeat (a) where input matrix is on a file not in the primary memory.
(c) Directly display the output on the screen as OFF the pixel for 0 and ON
the pixel for 1.
(d) If the terminal does not have any graphics facilities then use the user’s
manual for the terminal to generate the required patterns from the cursor
which is a matrix of pixel and any of the pixel is accessible to the user by
a set of ESC sequence. Display the output on the terminal.
(e) If a dot matrix printer is not in a graphics mode then use the user’s
manual for the printer to generate the required patterns from the dot matrix
of the printing head of the printer. Any of the dot of the printing head is
accessible to the user by a set of ESC sequence. Print the output on a
paper.

27. A recording company organizes a poll to determine the success of its prod-
ucts. Its products are records on tapes or CDs, and the most popular hits
are to be broadcast in a hit parade. The polled population is to be divided
into four categories according to sex and age (say, less or equal to 20, and
older than 20). Every person is asked to name five hits. Hits are identified
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 191

by numbers 1 to n (say, n = 30). The results of the poll are organized as


follows.
Each element represents a respondent and lists his name, sex, age and his
five preferred hits according to priority. Write a program (considering the
results of the poll as the input) to compute the results described below. Your
program must use subprograms (subroutine or function) as many as need.

(a) A list of hits in order of their popularity. Each entry consists of the hit
number and the number of times it was mentioned in the poll. Hits that
were never mentioned are omitted from the list.
(b) A list of names of all the respondents who had mentioned in the first
place one of the three hits most popular in their category.

28. (a) Write a recursive function to compute the following:


f (0) = 0, f (1) = 1, f (2) = 2 and f (n) = 7 f (n −2) −6 f (n −3), for n ≥ 3.
How many subtractions and multiplications do your function perform for
a given n?
(b) Convert the function in (a) into a non-recursive function by explicitly
maintaining the recursion stack.
(c) Write an efficient code to compute the above function using atmost one
loop and a fixed number of variables (≤ 10). How many subtractions are
needed now?
(d) Is it possible to express f (n) as a closed form function of n? When can
f (n) be negative? Discuss.
Chapter 11
PROGRAMMING WITH WHOLE NUMBERS

Implement the following problems related to number theory using a conven-


tional programming language.

1. Write a program which will take 2 number as input and output the following:

(a) their sum (using +),


(b) product (using ∗),
(c) the first minus the second, and
(d) the first divided by the second.

2. Write a program which will take 2 numbers as input and print out
(a) the largest and (b) the smallest.
3. Write a program which will take 10 numbers as input and print out
(a) the largest and (b) the smallest.
4. Write a program to test a natural number whether it is even/odd and output
as ‘even’ or ‘odd’.
5. Write a program to print out all the even numbers from
(a) 10 to 20 and (b) 10 to 200.
6. Write a program to print out all the odd numbers from
(a) 5 to 11 and (b) 5 to 111.
7. Write a program to input a positive integer n and output all perfect squares
(less than n).
8. Implement the following.

193
194 CHAPTER 11. PROGRAMMING WITH WHOLE NUMBERS

(a) Sum of all odd numbers in the range between 1 and 1000 is divide by
the sum of all even numbers in the same range.
(b) Calculate and print out the first ten factorials.

9. Write a program to print out all the multiples of 3 less than 40.
10. Imagine that your ‘∗’ (for multiplication) and ‘/’ (for division) key is faulty.
Devise a method of multiplying (or dividing) two integers together by re-
peated addition (or subtraction).
11. Is 711 > 117 ? Write a program to test for integers A and B, which may be
input or increased methodically, whether AB > BA if A > B.
12. [Roots of Numbers]

(a) Find the square root of a number (N) by taking the average (A) of a
higher number (H) and a lower number (L). If the square of A is less than
N then the root lies between L and A to give a new average. Otherwise
the root lies between A and H. Sometime A will become the root of N.
(b) Use the same method to find the cube or any other root.

13. [HCF] Determine the Highest Common Factor (HCF) by Euclid’s method
Example:
HCF for 72 and 48.
72/48=1 remainder 24
|−−−−−−−−
48/24=2 exactly
Hence 24 is the HCF.
14. Write a generalized program for computing the Highest Common Factor
(HCF) for two or more integer numbers.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 195

15. Write a program for the computation of the Least Common Factor (LCM)
of two given integer numbers. Check your result by computation: Product
of the two numbers = LCM × HCF.
16. Write a generalized program for the computation of LCM of two or more
integer numbers.
17. Write a program to convert a number from base B to base 10, where B < 10.
18. Write a program to convert a hexadecimal number to decimal. [AC8D16 =
4417310 ]
19. Write a program to convert a number from base 10 to base B, where B < 10.
20. Write a program to convert a decimal number to hexadecimal.
21. [Reduced Numbers] A reduced number is found by repeated addition of
the digits of a number until only one digit is left. Write a program to find
the reduced number of a very large number of about 30 digits.
22. [Number Bases] (Character symbols are needed for bases greater than 10).

(a) Convert a number in base 2 to


(i) base 4, (ii) Octal (base 8), (iii) Hexadecimal (base 16).
(b) Convert a number in binary to decimal.
(c) Convert a number in decimal to any base up to 16.
(d) Convert a number in any base B to another base S.

23. [Persistence] The persistence of a number is defined as the number of steps


required to reduce it to a single digit by multiplying all its digits to obtain
another number and so on till a single digit is reached.
Example:
The persistence of 77 is 4 and the transformation is
77 −→ 49 −→ 36 −→ 18 −→ 8.
Draw a flow-chart and write a program which inputs a number N and outputs
the original number, its persistence and all the intermediate steps.
196 CHAPTER 11. PROGRAMMING WITH WHOLE NUMBERS

24. Read a 3 digit positive integer and print it out in words.


Example:
342 Three hundred forty two
456 Four hundred fifty six
29 Twenty nine
6 Six
25. Given a positive integer less than 400, it can be written as a Roman numeral
using the following symbols:
Symbol C L X V I
Value 100 50 10 5 1
There are two rules:

(a) If a symbol precedes one of equal or smaller value, then the value of
the former symbol gets added. This also happens when the symbol is the
last one, i.e., when it is not followed by any other symbol.
(b) If a symbol precedes one of larger value, then the value of the former
symbol gets subtracted.

Example:
CXLIV has the value 100 − 10 + 50 − 1 + 5 = 144.
It is customary to write a number in a simple way as possible using only X
and I.
Example:
194 is written as CXCIV, and 75 as LXXV.
A Roman numeral is supplied to you in the form of an array of symbols.
Obtain the corresponding decimal value.
26. Let f (x) = integer part of the square root of x and g(x) = sum of all f (m)
where m = 1 to x. Give n, determine g(n).
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 197

27. Write a program which inputs a number and output


(a) all its multiples less than 200 and (b) the first 12 multiples.
28. [Roman Number]

(a) Write a program to generate all the numbers from 1 to 100 using roman
numerals.
(b) Write subprograms that will add and multiply roman numbers produc-
ing a result in the same form. Start by using specific numbers and then
generalize.

29. [Friendly Number] Write a program in which inputs are two positive inte-
gers, and it returns TRUE if the numbers are friendly and FALSE otherwise.
A pair of number is said to be friendly if the sum of the divisors of each
of the numbers (excluding the number itself) is equal to the other number.
(e.g., 1184 and 1210 are friendly.)
30. [Friendly Number] Two numbers m and n are said to be friendly if the sum
of all factors of m is equal to n and the sum of all factors of n is equal to
m. Write a program in which inputs are m and n and determines if they are
friendly.
31. [Amicable Number] An amicable number is a pair of number whose sum
of all possible factors will be equal to each other.
Example:
(6, 6), (28, 28), (220, 284) . . . are the amicable numbers.
Write a program which takes a positive integer n as input to give first n pairs
of amicable numbers as output.
32. [Lucky Number] A positive integer is called lucky number if it is divisible
by 3, 5, or 7. Given a positive integer n, you are required to output all lucky
numbers less than or equal to n, and the total number of such lucky number.
198 CHAPTER 11. PROGRAMMING WITH WHOLE NUMBERS

33. Consider all positive integers which are multiples of exactly two of the three
numbers 3, 5 and 7. Let Pn denotes the nth such number in increasing order
of magnitude. Then P1 = 15, P2 = 21, P3 = 30, P4 = 35, P5 = 42 and so on.
Write a program to compute Pn for the input n.
34. Consider all positive integers which are multiples of 7 but are multiples
of neither 3 nor 5. Let Pn be the nth such number in increasing order of
magnitude. Then P1 = 7, P2 = 14, P3 = 28, P4 = 49 and so on. You are
supplied n as input and your program is required to print output Pn .
35. [Prime Number] A prime number is a natural number which is divisible by
1 and the number itself. Write a program to generate all the prime numbers
between the given numbers n and m.
Example:
11 is a prime number since it is divisible by 1 and 11 itself. Suppose n = 1
and m = 14, then the prime numbers between 1 and 14 are 1, 2, 3, 5, 7, 11,
13.
36. [Prime Number] A positive integer greater than 1 is called a prime number
if it is divisible by 1 and itself, but not divisible by any other positive integer.
Given a positive integer n, you are to decide whether n is prime or not. Give
a flow chart and write the program.
37. [Mersenne Primes] A mersenne prime is a prime number which is equal to
2 p − 1, where p is any integer greater than 1. Write a program to generate
the first ten mersenne primes.
38. [Prime Number]
(a) Test a number to see if it is a prime number.
(b) Give the factors of a number.
(c) Combine (a) and (b).
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 199

39. [Prime Number] If you have some method of timing your program, see
how many primes you can find in, say, one minute. Challenge others to do
better.
40. [Perfect Number] A perfect number is one which is equal to the sum of its
factors including 1 but excluding itself.
Example:
6 = 3 + 2 + 1.
Write a program to generate the first three perfect numbers greater than 1.
41. [Perfect Number] A number n is said to be perfect if the sum of all its
factors including 1 but excluding n is the number n itself.
Example:
6 and 28 are perfect numbers.
Write a program to find out all perfect numbers below 1000.
42. [Perfect Number] A perfect number is a natural number which is equal to
the sum of its prime factors. (a) Test a given integer is a perfect or not. (b)
Generate all the perfect numbers between n and m, where n and m are given
integers.
43. Goldbach’s conjecture is that, every even number greater than 2 can be ex-
pressed as the sum of 2 prime numbers. Write a program for every even
integer (i) from 4 to 400 attempts to find a pair of prime numbers (A, B)
such that i = A + B. If successful, the program should print i, A and B; oth-
erwise it should output a message indicating that the conjecture has been
disproved.
44. [Prime Pair] A pair of positive integers p and q are said to form a prime
pair if p and q are both primes (a number is said to be prime if it is greater
than 1 and divisible only by the number itself) and q = p + 2.
200 CHAPTER 11. PROGRAMMING WITH WHOLE NUMBERS

Example:
(3, 5) and (5, 7) are prime pairs. A positive integer n is given. Write a pro-
gram to output the first n prime pairs.
45. Write a program which inputs a positive integer n and output its prime fac-
torization.
Example:
If the integer number is 980 then the output should be
Prime 2 5 7
Power 2 1 2
46. Any number can be expressed as powers of prime (e.g. 360 = 23 ∗ 32 ∗ 5).
Write a program to express a given number as powers of prime.
[Note: the lowest factor is always a prime.]
47. The Fibonacci numbers F(0), F(1), F(2), . . . are defined as follow:
F(0) = 0, F(1) = 1, F(n + 2) = F(n + 1) + F (n), for all n ≥ 0.
Write a program which reads a positive integer m and determines whether
or not it is a Fibonacci number.
48. Write a program which accept two number as input, and output the Fi-
bonacci sequence based on them.
Example:
If 2 and 5 were input, the next 3 terms would be 7, 12, 19. It is normal to
input the lowest of the two numbers first.
49. What are the largest two starting numbers to give 10 members of a Fibonacci
sequence all less than
(a) 100, (b) 1000 and (c) any number?
Write a program to count the number in the sequence and to keep on in-
creasing the size of the initial numbers until the tenth member is too large.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 201

50. [Back to front] This question is for those who prefer to do mathematical
problems backwards! Input 2 large numbers in order (largest last) which
represent the last 2 members of a Fibonacci sequence. Output the complete
sequence in reverse order.
51. Generation of Fibonacci numbers and search for primes.
Generation of Fibonacci numbers: The Fibonacci numbers are members
of an interesting sequence in which each number is equals to the sum of the
previous 2 numbers. In other words: Fi = Fi−1 + Fi−2 where, Fi refers to the
Fibonacci number. The first 2 Fibonacci numbers are both equal to 1, i.e.,
F1 = 1, F2 = 1. Hence F3 = F2 + F1 = 1 + 1 = 2, F4 = F3 + F2 = 2 + 1 = 3,
F5 = F4 + F3 = 5, and so on.
Search for primes: All of the Fibonacci numbers are positive integral
quantities, and some of them will be primes. A positive prime number is
an integer, that is, divisible without a remainder, only by 1 or by itself.
Example:
5 is a prime number because the only quantities that can be divided evenly
into 5 are 1 and 5. On the other hand, 8 is not a prime because 8 is divisible
by 2 and 4 as well as by 1 and 8.
52. Write a program that will read a positive integer and determine the fol-
lowing: (a) the integer is prime number, and (b) the integer is a Fibonacci
number.
Modify the program in such a manner that it will execute in a loop, until a
zero value is detected for the input quantity.
53. [Numerical Center] Two positive integer m and n are given where m, n > 1
and n > m. The positive integer m is said to be the numerical center of
another positive integer n if it satisfies the following condition:
1 + 2 + 3 + · · · + (m − 1) = (m + 1) + (m + 2) + · · · + n.
202 CHAPTER 11. PROGRAMMING WITH WHOLE NUMBERS

Example:
1 + 2 + 3 + 4 + 5 = 7 + 8. Therefore 6 is the numerical center of 8.
Write a program to generate all numerical centers less than or equal to 1000.
54. [Editing Numbers] We are always in danger while reading numbers. Some
non-numerical character has been typed as the letter I instead of a 1 or the
letter O instead of a 0 (zero). Write a program to read in any character, check
that it is numeric and build up a value. If there is an error indicate its type
and position. [Note: Start with integers and then tackle decimals.]
55. [High Accuracy Calculations] Calculations involving the four mathemat-
ical operators may be achieved to 20 significant figures by inputting as a
string, converting to numbers bit by bit, calculating bits at a time, convert-
ing back to another string which is the final output form.
56. There are three ways of adding 4 odd numbers to obtain 10:
1 + 1 + 3 + 5 = 10; 1 + 1 + 1 + 7 = 10; 1 + 3 + 3 + 3 = 10.
It is assumed that changes in the order of the numbers are irreverent. Find
all distinct ways of adding 4 odd numbers to obtain a given positive even
integer n > 3.
Write the program.
57. [Large Numbers] Most computers can handle integers upto 8 digits and
simple decimal calculations with 8 or 10 digit accuracy. What do we do if
we wish to multiply two 20-digit numbers?

(a) Write a program to add numbers upto 100 digits long. Each digit must
be held and handled separately.
(b) Carry out addition, subtraction, multiplication and division with virtu-
ally unlimited digits.
(c) Produce a program to calculate X n where X and n are integers giving a
massive result, e.g. 12345678 .
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 203

58. [Large Factorials]

(a) Write a program to find all factorials up to 1000!.


(b) Count the number of digits in each factorial and print out those num-
bers which are an exact square. These numbers can be printed out as a
triangle with one digit at the apex, then 3 digits, then 5 and so on. This
arises because any partial sum of the series 1 + 3 + 5 + 7 + . . . gives an
exact square.
Example:
Here 12! gives 9 digits printed as

4
790
01600

(c) These factorials can be printed out in other shapes such as hexagon or
octagon.
Example:
35! has 41 digits equal to two consecutive squares 42 + 52 , this forms a
diamond.

59. In a cheap canteen each item costs less than twenty rupees and the price is
always a multiple of five paise. The counter-keeper has a supply of twenty
five paise, fifty paise, one rupee coin, two rupee coin and five rupee coin. In
view of the acute shortage of small change, he wants to be able to return the
change to a customer with the smallest possible number of coins. Giving the
price of an item in paise (or rupees), your algorithm should determine the
smallest total number of coins needed for returning the change, assuming
that the payment is made with a ten or twenty rupee note. Your program
204 CHAPTER 11. PROGRAMMING WITH WHOLE NUMBERS

should output the number of coins of each denomination as well as the total
number of coins.
Chapter 12
PROGRAMMING FOR TABLE PRINTING

Implement the following problems related to table printing using a conven-


tional programming language.

1. Write a program for tabulation of first 20 even numbers (in 3 columns) as


√ √
values of n, n, n2 (where n = n1/2 ) with proper columns heading.
2. Write a program for tabulation with proper columns heading of n numbers in
c (< n) columns where only the part of cth column may be empty. (Accept
n number as input).
3. Write a program for tabulation of first 20 even numbers as the radius and its
corresponding volume and total surface area of a sphere.
4. Input a number. Output its multiplication table up to 20 times. Write a pro-
gram.
5. Had a distant relative of yours, managed to invest Rs.10 with 10% per an-
num compound interest, one hundred years ago, how much would it be
worth now? Write a program for investment. Tabulate the calculations for
every 5 years using the following headings.
Year Interest Current Total
... ... ...
6. Write a program to using a loop to print first 20 factorials in the form of a
table with headings ‘n n!’.
7. Write a program to produce a neat headed table of squares and cubes.
8. Write a program which accepts the name of a country and a figure repre-
senting an amount of money in rupees as input. Output the equivalent value

205
206 CHAPTER 12. PROGRAMMING FOR TABLE PRINTING

in the currency of the country specified. Select 5 countries of interest and


find out the rates of exchange from a newspaper or a bank. Round figures
sensibly, and also to produce headed tables of rupees to foreign currency,
and foreign currency to rupees.
9. In a survey question, the answer is one of the n options numbered 1, 2, · · · , n
and this survey has been conducted in m different zones numbered 1, 2, · · · , m
attached with the questioner number, where the zone field of two characters
width. The structure of data file is given as:
Column Number Field
1-2 Zone
3-6 Serial number
7-8 question 1
9 - 10 question 2
... ...
Write a program which inputs n, m, first title of headings, second title of
heading of the table, and zone start column numbers and its width, and data
start column number and its width. Output the frequency table of data with
zone and with proper headings.
10. Intake of a management institute is n students of different casts ST, SC,
OBC and GE belong to different classes of income group. Administration of
management institute wants to know the number of students are belonging
to which income group. Group ranges are supplied by the administrator.
Student file must contain the number of students with their casts and parent’s
annual income. Output a frequency table of income with categories and with
total students.
11. A management institute offers ′ c′ courses in a particular term (or semester)
of which one student can select x + y courses except compulsory course,
where x is the number of optional credit courses and y that of non-credit
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 207

courses. The administrative officer wants to know the crossing and the non-
crossing (i.e., intersection) between the courses in a tabular form. Write a
program, that accept the above inputs and produces an output that the results
are in a tabular form. [Note: Output will be a symmetric matrix.]
12. Write a program to give the internal angle of a regular polygon with n sides.
Tabulate results using following headings:
Number of sides Interior angle
... ...
13. The values of sin x and cos x are given by the equations:
x3 x5 x7 x9
sin x = x − + − + − . . ., and
3! 5! 7! 9!
x2 x4 x6 x8
cos x = 1 − + − + − . . .
2! 4! 6! 8!
where x is the angle in radians. Remember that 180o = π radians.
There are two approaches - either to evaluate the series to say 15 terms or to
perhaps 6 decimal places. The latter is obtained by checking the size of the
last term evaluated. The tangent of an angle can be obtained by dividing the
sine by the cosine - remember that tan 90o is infinity.

(a) Print a table showing the Angle, Sine, Cosine and Tangent for angles
between 0o and 90o .
(b) If you have built-in Sine and Cosine functions, print a table comparing
these against your values.

14. The natural logarithm is given by the formula:


x2 x3 x4
ln(1 + x) = x − + − +... although this converges slowly.
2 3 4
Produce a table of six figure logarithms. The antilog tables can be produced
by y = loge x, Therefore, x = ey common logarithms (to the base 10) can
loge N
be converted by the formula log10 N = , where the denominator is a
loge 10
constant.
208 CHAPTER 12. PROGRAMMING FOR TABLE PRINTING

15. (a) Produce a table giving a number, its square root, cube root etc. This
table could also include the squares, cube and reciprocal.
(b) If you have built in sub-programs for finding roots, compare your val-
ues against those of the sub-program. Produce a table of differences.
1 1 1
16. The focal length for a convex lens is given by: + =
u v f
where u = the distance of the object from the lens, v = the distance of the
image from the lens, and f = the focal length of the lens.
Construct tables while giving f for various values of u and v, and v for
values of u and f .
17. Write a program to produce a series of tables converting the various standard
British weights and measures into their metric equivalent. The reverse set of
tables is also necessary.
18. The category of books are 1, 2, 3 and 4, for which we want to calculate a
discount of 15%, 10%, 5% and 0% respectively, on the selling price of the
book. In each case, deduct the discount from the selling price to obtain the
net price of the book. Further, let us assume we have an unknown number
of data (records) each containing the values of book number, category and
price. Write a program that will produce a table giving particulars of the
book; its number, category, price, discount and net price.
19. The 
acceleration due to gravity as a function of altitude is described below.
 2
4390
, if h ≥ 0

 32.17

g=  4390 + h 
h
 32.17 1 + , if h ≤ 0


4390
where h is the height above the sea level in statute miles and g is the acceler-
ation of gravity in f t/sec2 . Write a program to compute and print the values
of g for h = −5, 0, 5, 10, · · · , 150 in a tabular form.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 209

20. Write a program which will evaluate the following function for the set of
values of x : (0.5, 1.0, 1.5, 2.0, 2.5, 3.0) and tabulate the results
x2 x4
f = 1 + + −0.250 sin(2x) + (4 − x2 ).
2! 4!
21. The allowable stress, Fa , in a column is given by the formula
 2
L
1−
5 3(L/r) (L/r)3
 
r.c 22E
Fa = Fy , where F.S = + − and c = .
F.S 3 8c 8c Fy
L
Write a program that generates a table for Fa with the values of varying
r
from zero, in increments of one, to a maximum integer value not exceeding
the value of c. Input for Fy and E.
22. The scattering cross-section of an electron is given by the formula A =
0.666r4
, where r is the ratio of the radiation frequency to the bound nat-
(r2 − 1)2
ural frequency of an electron. Write a program to print the values of A for
different values of r = 10, 20, 30, · · · , 100 in a tabular form.
23. The Fermi-Dirac distribution for a normalized energy u is given by the for-
1
mula: FDD = u .
e −1
Write a program to print this function FDD for u, varying from 1.0 to 10.0
with step size 0.05 in a tabular form.
24. The ratio of relativistic to classical momentum as a function of the fraction
1
of the speed of light is given by the formula, ratio = .
1− f2
Write a program that will compute and print a table of the ratio for f = 0.1
to 0.9 in steps of 0.1, f = 0.91 to 0.99 in steps of 0.01, and f = 0.991 to
0.999 in steps of 0.001.
x2 + y2 + 2xy
25. Tabulate the function f (x, y) = 2 for the following set of values:
x + y2 + 8xy
x 0 2 4 6 8 10 12 14 16 18 20
.
y −10 −8 −6 −4 −2 0 2 4 6 8 10
210 CHAPTER 12. PROGRAMMING FOR TABLE PRINTING

26. Write a program that tabulate both simple and compound interests for all
combinations of the following deposits, interest rates and years of deposit
Deposit : 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000
Rate : 5%, 6%, 7%, 8%, 9%, 10%, 11%, 12%, 13%, 14%,
.
15%, 16%, 17%, 18%, 19%
Years : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

27. (a) Suppose you place a given sum of money, A, into a savings account at
the beginning of each year for n years. If the account earns interest at the
rate of i% annually, then the amount of money that will have accumulated
after n "years, F, is given by
   2  n #
i i i
F = A 1+ + 1+ +··· + 1+ .
100 100 100
Write a program to determine the following:
(1) How much money will accumulate after 30 years if Rs.1000.00 is
deposited at the beginning of each year and the interest rate is 6% per
year (compound)?
(2) How much money must be deposited at the beginning of each year
in order to accumulate Rs.1,00,000.00 after 30 years (again assuming
that the interest rate is 6% per year, compounded annually)?
In each case, first determine the unknown amount of money. Then create
a table showing the total amount of money that will have accumulated at
the end of each year.
(b) Modify the above program to calculate quarterly rather than annually
compounding of interest. Compare the calculated results with those ob-
tained "
in part (a). [Hints: the proper formula is
 m  2m  nm #
i i i
F = A 1+ + 1+ +··· + 1+ ,
100m 100m 100m
where m represents the number of interest periods per year.]
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 211

28. Politicians and bankers often quote ”the rule of 72” which says that if the
annual rate of inflation is r% then a fixed sum of money will decline in value
by half in a period of 72/r years. Write a program to test the accuracy of
this rule by tabulating, for each value of k from 1 to 36 for (1) k, (2) the
72
value of , and (3) the time at which the value of a sum is actually halved
k
when inflation is k%.
29. Write a program to generate a log table for a 4 decimal place and 7 decimal
place accuracy.
30. Write a program to generate a table for a given accuracy with the given
function of the form y = f (x), where x varies from 1 to 1000 with step 0.1.
The output table looks like
Function y = f (x), 1 ≤ x ≤ 100
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
1
2
.
Assumption: (1) The output of each page contains a table title and page
number. (2) Each page contains only 60 lines.
Modify the above program so that each table slot contains both y = f (x) and
y = g(x)
Function y = f (x) and y = g(x), 1 ≤ x ≤ 100
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
1 f(1.0) f(1.1)
g(1.0) g(1.1)
2
.
212 CHAPTER 12. PROGRAMMING FOR TABLE PRINTING

31. [Poisson Distribution Table] Write a program to generate a Poisson distri-


bution table for a given value of the mean of the distribution and range is
from 0 to upper limit. [Assume each page contains at most 60 lines].
32. [Normal Distribution Table] Write a program to generate a Normal distri-
bution table
Z t
with mean 0 and the standard deviation 1 as
1 1 2
f (t) = √ e− 2 x dx
0 2π
ranges from 0 to 99 with step 0.1. [Assume each page contains at most 60
lines]
33. In the highway code we are given various thinking and braking distances for
a car travelling at different speeds. Write a program to reproduce this table
for a wide range of speeds. Can you modify the program to allow for dry
and wet roads, and even for the braking efficiency of the car?
34. [League Tables] If you are a cricket or football fan, you may like to produce
your own league table. This should be updated regularly with recent results.
A log of all results should be kept and built up.
35. [Tide Tables] Produce a tide table showing the times of high and low tide at
every day of the year. You should only need to read in a single time of high
tide for 1st January, and the tidal delay.
36. An experiment has been conducted in such a way that a living cell or a living
body changes with time. Here we are going to measure different parameters
of a human body such as (1) height, (2) weights and (3) chest.
Write a program to represent the observed data in the following tabular
form.
Tables for the changes of Height, Weight and Chest with time
(Unit: Height & Chest in cms, Weight in Kg and Time in Yrs, Months)
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 213

Age in months
No. 0 1 2 3 4 5 6 7 8 9 10 11
Height ...
0 Weight ...
Chest ...
... ...
1 ... ...
... ...
Prepare another table for the standard height and weight from the above
observe data.
37. [Differentiation] Write a program to find out the first order differential of
a simple polynomial. Extend this to product and division equations, and
to logarithmic and trigonometric equations. Produce tables showing first,
second, third etc. order equations, and solutions with given values of x.
Chapter 13
PROGRAMMING GEOMETRICAL
PROBLEMS

Implement the following problems related to geometry, using conventional


programming languages.

1. Write a program whose input is an angle in degrees. Output the messages


(angle type) acute, right angle, obtuse, straight line, reflex as appropriate.
2. Find the area of a rectangle with a given perimeter p (e.g. the total length of
string or fencing from which the rectangle is made) depends on the ratio of
p 
its sides c and d. p = 2(c + d) therefore c = −d and Area A = c × d =
p 2
 p
d −d . Input p, increase d in small steps from 0 to , and output each
2 2
time through the loop the values of d and A.
3. Write a program to compute the area of a triangle whose sides are a, b and
p
c. Mathematically, Area = s(s − a)(s − b)(s − c), where s = 12 (a + b + c).

(a) Test the formula using known data (e.g., for a right angle triangle).
(b) Find, by making the computer do trial-and-error testing for you, the
values of a, b and c for maximum if s = 24.

4. Write a program whose input is a Cartesian co-ordinate of a point and output


is its polar co-ordinate.
5. Write a program to test, whether the given point is inside or outside the
given polygon (may be triangle).
6. The coordinates of vertices of a simple n−gon (convex or non-convex) is
given. Input n and its n co-ordinates of the vertices. Write a program to
compute the area of the n−gon (self-intersection is not allowed). [Hints:

215
216 CHAPTER 13. PROGRAMMING GEOMETRICAL PROBLEMS

(xi , yi ), i = 1, 2, · · · , n are n vertices of a n−gon, then


n−1
1
area = [(yn + y1 )(x1 − xn ) + ∑ (yi + yi+1 )(xi+1 − xi )].]
2 i=1
7. Write a program that will accepts 3 points in a plane, check whether they
are collinear or not.
8. Write a program that will accept 3 points in the space. Check whether they
are co-planner or not.
9. Write a program which will accept sides of a polygon (non-convex). Output
the sum of angles of the polygon.
10. A triangle can be defined precisely in one of three ways:

(a) The length of the three sides.


(b) The length of two sides and included angle.
(c) The length of one side and the angles at each end of the line.

The program requires that three values be read in relating to one of the cases
above and test whether they form a triangle, if so what types of triangle, i.e.,
acute, right angle, isosceles etc., calculate all its dimensions, including its
area and find the radius of its enclosed and circum-circle.
11. [Great circle distances] A great circle route is the shortest possible dis-
tance by sea or land between two points on the earth’s surface. The problem
is to read in pairs of locations (e.g., Calcutta and London) with their corre-
sponding latitudes and longitudes, and then write a program to calculate the
distance between them. The difficulty lies in the curvature of the earth.
12. Write a program to convert a rectangular Cartesian co-ordinate (x, y) to an
angular co-ordinate system. (Where the angle between two axis is ω ).
13. Write a program to convert a 3-D rectangular cartesian co-ordinate (x, y, z)
to a cylindrical and a spherical co-ordinate systems.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 217

14. Equation of a closed curve such as (1) circle, or (2) ellipse is given. Write
a program to check whether a given point is inside or outside of it.
15. [Convex hull] A set of points is given in a plane. Write a program to find
the sequence of points from the given set that includes all the points of the
given set. [Note: A convex hull is a smallest convex polygon which contains
all the given points.]
16. [Convex hull] Write a program which will return a set of ordered points
(V ) from the given set of planner points (S), so that the points of V form
a smallest convex polygon so that it includes all the points of S. Can you
improve your algorithm.
17. Write a program which will return a smallest diameter of a greatest circle
that includes the given set of planner points, where the circle is passing
through at least two points of the set.
18. Write a program which will return a smallest diameter of a greatest possible
sphere that includes the given set of non-planner points and the sphere is
passing through at least two points of the set.
19. Write a program which will identify the smallest distance neighboring
points from a given set of points with respect to a given point. Print the
point and its identification.
20. Write a program to compute an intermediate point C between the straight
line AB, such that AC : CB = m : n.
21. A straight line is indicated by two points A1 (x1, y1 ) and A2 (x2 , y2), similarly
another straight line is indicated by two points B1 (x3 , y3 ) and B2 (x4 , y4).
Write a program to compute the point of intersection between the straight
lines A1 A2 and B1 B2 . Report only internal point of intersection, otherwise
report lines are not intersecting.
218 CHAPTER 13. PROGRAMMING GEOMETRICAL PROBLEMS

22. Write a program to compute the intersecting polygon between two given
polygons.
23. [Voronoi diagram] Suppose a given set V = {v1 , v2, · · · , vn }, of n (≥ 3)
points in a plane are not all collinear, and that no four points are co-circle.
Assume d(vi , v j ) is the distance between points vi and v j . The bisector
B(vi , v j ) of vertices vi and v j is the locus of points equidistant from them;
that is,
B(vi , v j ) = {x ∈ E 2 |d(x, vi ) = d(x, v j )}.
The half-plane H(vi , v j ) is the locus of points closer to vi than to any v j ,
j 6= i, thus
H(vi , v j ) = {x ∈ E 2 |d(x, vi ) ≤ d(x, v j ); j 6= i}.
N
The polygonal region V D(vi ) = ∩ H(vi , v j ) is the locus of points closer
j=i
to the vertex vi than to any other vertex. Each vertex vi therefore defines
a region V D(vi ) called the Voronoi Polygon associated with the vertex. The
collection of these n Voronoi Polygons is referred to as the Voronoi Diagram
VD(V) of the set V of points.
Write a program to draw the voronoi diagram from the given set of co-
ordinates.
24. Write a program which will generate a random smooth polyline or a poly-
gon (like a map boundary or a river) using normally distributed random
number generator. [Hints: Choose two parameters l, the length of a line seg-
ment and θ , the angle with x−axis. Let (x0 , y0 ) be the starting point (may be
random) and perform the following operations: a normally distributed ran-
dom number generator generate l = N(lm , lσ ) and θ = N(θm , θσ ), where
the initial values of lm , lσ , θm and θσ are suitably chosen. Then compute
xi = xi−1 + l cos θ and yi = yi−1 + l sin θ , and for the next set, choose lm = l
and θm = θ for i = 1, 2, ...]
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 219

25. Write a program to compute the frequency distribution of the length of


x−monotone, y−monotone or xy−monotone chains generated from a nor-
mally distributed smooth polygons (or polylines).
26. Write a program to compute θ which denotes the number of degrees in each
angle of a regular polygon of n sides. [Hints: nθ + 360o = n.180o ]
27. (a) Write a program to generate a set of 3 numbers a, b, c for which
a2 + b2 = c2 . These numbers represent the sides of a right-angled triangle
(Pythagoras Theorem).
(b) Add to the program to print the set of numbers only if a < b.
(c) Add to the program again to avoid printing out larger versions of the
same shape. For example, a triangle with sides 6, 8, 10 units is the same
shape as a triangle with sides 3, 4, 5 units.
28. The perimeter of a triangle is l (integer). Divided l into 3 integral parts
so that it form a triangle. Write a program which will report all possible
combinations of segments and also the types of the triangle i.e., right angle,
equilateral, isosceles, acute, obtuse (if one triangle is more than one type
then also specify).
29. [Pedal or Simson’s line] Write a program to prove the following statement.
The feet of the perpendiculars drawn to the three sides of a triangle from any
point on its circum-circle are collinear which is known as pedal or Simon’s
line of the triangle for the point.
30. [Nine-points circle] Write a program to prove the following statement. In
any triangle the middle points of the sides, the feet of the perpendiculars
from the vertices to the opposite sides, and the middle points of the lines
joining the orthocenter to the vertices are concyclic.
220 CHAPTER 13. PROGRAMMING GEOMETRICAL PROBLEMS

31. In a rectangular paper, two closed polygons/curves A and B (say) are given.
Write a program to compute the ratio r of the area of A and the area of B.
Also this result can be verified by the following statistical method.

(1) Generate n (say, 1000) uniformly distributed random points in the


range of the rectangular paper.
(2) Counts the number of points (belongs to n generated points) inside or
on A and also count the number of points inside or on B as A.
(3) Compute the ratio α of the count of A and the count of B.
(4) Compare the ratio α with r if not desired then repeat this method for
large values of n.

32. [Convex hull of circles] A set of circles with different radius is given in
a plane. Write a program to find the sequence of points and arcs from the
given set that includes all the circles of the given set.
33. [Convex hull of ellipses] A set of ellipses with different size is given in
a plane. Write a program to find the sequence of points and arcs from the
given set that includes all the ellipses of the given set.
34. [Convex hull of mixture of points, circles and ellipses:] A set with a mix-
ture of points, circles with different sizes and ellipses with different sizes is
given in a plane. Write a program to find the sequence of points and arcs
from the given set that includes all the points, circles and ellipses of the
given set.
35. [Convex hull of 3D points A set of points is given in 3D space. Write a
program to find the sequence of points from the given set that includes all
the circles of the given set.
36. [Convex hull of spheres] A set of spheres with different radius is given in a
3D space. Write a program to find the sequence of points and surfaces from
the given set that includes all the spheres of the given set. Can you extend
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 221

this idea for a set of ellipsoids of different size. Also extend this idea for a
set of mixed items such as points, spheres and ellipsoids (same or different
size).
37. Bridge computation Compute a optimal bridge between two convex poly-
gons in a plane.
38. [Minimum spanning circle] A set of circles with different radius is given
in a plane. Write a program to find a circle with minimum radius from the
given set that includes all the circles of the given set.
39. [Minimum spanning sphere] A set of spheres with different radius is given
in 3D space. Write a program to find a sphere with minimum radius from
the given set that includes all the spheres of the given set. Extend this idea
for n-D.
Chapter 14
PROGRAMMING PROBLEMS WITH TIME
AND DATE

Implement the following problems which are related to time and date.

1. Write a program in which input is your date of birth in the form dd, mm,
yyyy and output your age as on today (or January 1, 2004). (3rd of March
1983 would be input as 03, 03, 1983 to be recognized as 3 integer numbers.)
2. Write a program in which inputs are two times of a day in hours and minutes
using the 24 hours clock and compute the time elapsed between them and
also work out wages of an individual worker who gets payment Rs.4 per
hour between the hours of 08:00 and 16:00, and Rs.5 for every extra hour
worked. Inputs are the clock on and clock off times for the 5 working days.
3. Write a program to compute the number of days between two days.
4. Write a program to check the validity of a given date. [Note: 18.12.1959 is
a valid date but 51.31.1991 is not a valid date.]
5. Write a program to read a date in the form 15.11.91 and print out that in the
following forms. (1) 15th November 1991, (2) November 15, 1991, and (3)
Fifteenth day of November nineteen hundred and ninety one.
6. Julien date is defined as the number of days that have passed since some
specified reference date. For example, if the date is 2nd March, 1990 and the
reference date is 1.1.90, then the corresponding Julien date will be 61 (31 +
28 + 2). Write a program whose inputs are two different dates of the year
1998 in the format dd/mm/yy and compute the number of days between
these two dates using Julien date.

223
224 CHAPTER 14. PROGRAMMING PROBLEMS WITH TIME AND DATE

7. Suppose the days in the year 1984 has been numbered from 1 to 366; with
January 1 as 1, January 2 as 2, and so on, finally December 31 as 366. Given
any positive integer i between 1 and 366 (both inclusive) as input, you have
to output the corresponding date in the following format : Month Day Year.
Example: if i = 62, your output is March 2, 1984. Write a flowchart and the
program in which input is i and print the date in appropriate format.
8. The problem is to read a date and find out the day of the week. We can
calculate the day of the week from the following equation:
 hyi hci 
[2.6m − 0.2] + d + y + + − 2c mod 7
4 4
where, d is the day of the month,
m is the month number taking March = 1
upto December = 10; January and February
months 11 and 12 of the previous year,
c is the century, and
y is the year.
Thus for 16th April 1961, d = 16, m = 2, c = 19, y = 61; and for 1st
January 1900, d = 1, m = 11, c = 18, y = 99. The square brackets indicate
that every thing after the decimal point is dropped (e.g., [2.7]=2).
The “mod 7” means that the result in round brackets is divided by 7 and
the remainder taken to find the day. If the remainder is 0 the day is Sunday,
whilst 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday
and 6 = Saturday. If the result is negative add 196 before dividing by 7.
Notes: (a) Start by printing the remainder only but ultimately print the date
and actual day. (b) Don’t forget to adjust the year for January and February,
sometimes the century also. (c) Incorporate a check that the date is mean-
ingful, i.e. not 44/0/4444.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 225

9. It is possible to compute the day of the week corresponding to any given


date of the Gregorian calendar. Let m be the month of the year, starting
with March as m = 1. January and February are months 11 and 12 of the
previous year. Let d be the day of the months, y the year of the century, and
c the century. Thus January 22, 1954 has m = 11, d = 22, y = 53, c = 19.
Now,
13m − 1
(1) a be the integer part of ,
5
y
(2) b the integer part of ,
4
c
(3) e be the integer part of , and
4
(4) Compute a + b + e + d + y − 2c, divide by 7 take the remainder; then
Sunday corresponds to 0, Monday to 1,· · ·, Saturday to 6.

For example, January 22, 1954 fall on Friday. You are supplied with three
positive integers i, j and k. The first is the month of the year with January as
the first month, the second is the day of the month, and the third is the year.
Write a program to determine the day of the week.
10. (a) Write a program to print the days of the week for the current month.
(b) Extend and alter the above program to give the day of the week for any
date in the current year which may be input.
(c) Extend your program further by predicting the day of the week for any
date in the next year. Your program should be able to detect a leap-year
and adjust accordingly.
(d) Predict the day of the week for any date since 1752.
(e) Select a year and print out the calendar for that year. This could be an
interest to historians.
226 CHAPTER 14. PROGRAMMING PROBLEMS WITH TIME AND DATE

11. (a) Input a list of 6 names each followed by age, in years only in your
program. Output all those (i) born after a given date, (ii) born in a given
year.
(b) Extend the program to include months.
(c) Extend the program to accept date of birth for each name, and to print
the same information, plus (iii) those born in a given month.
12. [Calendar] Write a program that print out the date and day of this year from
the first of January. The day for the first of January must be read in. Do not
forget to allow for leap-years.
Indicate special days such as Independence day, Republic day, Good Friday
and Christmas day. This seems a fairly trivial program but it is really quite
difficult.
A similar program could be written to find the number of days between two
dates read in. Check that the second date is greater than the first; Do you
forget that our present Gregorian calendar only started in 1582.
13. [Global time differences] Produce a table of differences in time between a
large number of capital cities of the world. The cities with their latitude and
longitude should be listed across and down the page with the differences at
the intersections.
14. [Calendars] Read an year, e.g. 1993, and some code to represent the day on
which the first of January falls for the year. Now print out the calendar for
that year. [Note: You may have difficulty with the blank days of the calendar
which will initially print as “o”. Eliminating this zero is a problem in itself
but well worth solving.]
15. An organization made a rule that the retirement age of an employee is 60
years. Write a program which will print the date of retirement from the date
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 227

of birth of the employee. [Note: The retirement date should be the last date
of the calculated month.]
16. Write a program to compute the times when the angle between the two
hands (hour-hand and minute-hand) is 180o for a 12 hour clock.
17. Write a program to compute the time when the angle between the two hands
is θ o for a 12-hour indicated clock.
18. Write a program to compute the time when the angle between the two hands
is θ o for a 24-hour indicated clock.
19. Write a generalized program to compute time when the angle between the
two hands is θ o for a h−hour indicated clock. [Note: Standard time prob-
lems]
20. The standard direct labor cost in standard costing of cost accountancy de-
pends on (1) standard time and (2) standard rate.
Standard time should be fixed for each grade of labor and for each oper-
ation involved. This is generally done in conjunction with the work-study
engineers.
Standard rate of pay for each grade of workers are then to be determined.
Any expected increase in the rates should be considered in the assessment.
The personnel manager will help to the accountant while determining the
standard rates. If overtime work is essential, extra payment for overtime
may be included in the wage rates.
Write a program to calculate the standard labor rate for a workman of a
particular grade from the following inputs:

(1) Basic pay in Rs. per month.


(2) D.A. in Rs. per month.
(3) Fringe in Rs. per month.
(4) Number of working days per year.
228 CHAPTER 14. PROGRAMMING PROBLEMS WITH TIME AND DATE

(5) Number of days PL with full pay per year in the leave rule of the
organization.
(6) Number of days SL (sick leave) with half pay per year in the leave rule
of the organization.

Your program should consider (1) with sick leave and (2) without sick leave
for the computation.
21. Write a program to compute the following:

(a) Standard time for actual production = Actual production × Standard


time required per unit.
Actual hrs excluding abnormal time
(b) Std. Production =
Standard time per unit
(c) Efficiency variance computed as:
Efficiency variance = [(Standard time for actual production) − (Actual
hours excluding abnormal ideal time)] × (Standard hourly rate)
[Note: Actual time < Standard time; Production > Standard Production
then variance is favorable]
(d) Ideal time variance is that portion of wage variance which is due to
specified idle time of the workers.
Ideal time variance = Abnormal idle hours × standard hourly rate.

with the following inputs: (1) Standard time per unit, (2) actual hours ex-
cluding abnormal time, and (3) actual production.
22. [Time study] Time study is the appraisal, in terms of time, of the value
of work involving human effort. It produces a time standard for the perfor-
mance of a series of acts by a man or group of men. The time taken by an
actual worker is determined by one of the following methods.

(1) Continuous timing,


(2) Repetitive (or snap-back) timing,
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 229

(3) Continuous accumulative timing,


(4) Repetitive accumulative timing,
(5) Motion-picture camera timing, and
(6) Time study machines and sound recorders.

The computation of standard time and


r rate by the well-known standard sta-
∑ d2
tistical methods as given as: SD =
N
where, SD = Standard Deviation,
d = X − X computed for each reading of the element separately be-
fore squaring and then summing,
X = Individual readings of an element,
X = Mean or average of all readings of an element, and
N = Number of readings of an element
SD
So, standard error of the mean is SDx = √ .
N
The property of this last measure is such that 95% of the probable values
of X (average for the element) will lie within +2SDx of the true average.
Thereforeq
1
N ∑X2 − ∑X
2
SDx = N √ .
N′ !2
40 N ∑ X − (∑ X)
p
2 2
Set 0.05X = 2SDx ⇒ N ′ =
∑X
where, N ′ = required number of readings.
Write a program to compute the number of observation N ′ for p% of the
 p 
probable values. [Hints: 1 − X = 2SDx ].
100
Chapter 15
PROGRAMMING FOR COMPUTER GAMES

Computer games and graphics is an important and interesting area of study.


We can play with a computer as an opponent player for the game. The com-
puter game will be more attractive if we use computer graphics for the imple-
mentation. In this chapter a set of problems have considered as a programming
assignment to practice one of the conventional programming languages. Here
our objective is to design the programming logic from the description of these
problems.

1. [Fun] Write the following program for a fun.

(a) Think of a number, add 5 with this, double your obtained result, and
then subtract 7. What is the result: 15 (say). You thought of 6. Now write
the program!
(b) Invent your own sequence of simple mathematical operations to pro-
vide some fun for your friends.

2. [NIM] Write a program for a game, known as NIM game.

(a) There are 17 matches from which 1, 2 or 3 may be removed by each


player in turn. The objective of the game is to make your opponent take
the last match. Write a program to beat your friend, who always has first
go by removing m matches, if it removes (4 − m) matches, where m < 4.
(b) Extend the idea to work with different numbers, e.g., starting with 31
matches where up to (i) 4, (ii) 5 may be removed at any single turn.
(c) Extend the idea for two players, and

231
232 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

(d) Any starting number

3. [High-low game] The High-Low game could be made more attractive by (a)
inviting the user to input a lucky number before trying to guess the number
generated by random number generator, and (b) inviting the user to ask for
another go.
4. [Snakes and ladders game] The snakes and ladders game in ludo has no
board and the player has no opponent but tries to beat a record. Use random
number generator for a die to land on a number n. Let the number of tens in
n be t and the number of units be u, such that n = 10 ∗ t + u. If u = 4, then
you have found a ladder and n is increased by (10 −t) ∗ 3. If u = 6, then you
have been swallowed by a snake and n is decreased by 5 ∗t. Write a program
to print the value of n after each throw, followed by an appropriate message
about ladder-climbing or snake-swallowing.
Example:
(a) Landing on 64 (which is the bottom of a ladder), you would move up by
(10 − 6) ∗ 3 = 12 to 64 + 12 = 76.
(b) Landing on 76, the snake would take you down by 5∗7 = 35 to 76−35 =
41.
Press a key for the next go. How many goes did you take? what is your
record?
5. [Word hunt secretly game] Write a program in which input 7 names of
your class, in alphabetical order. Ask a friend to try to find them all in less
than (say) 15 attempts. The output will be either the number of the person
(1, 2, 3, 4, 5, 6 or 7 - thus giving some clues for further guesses) or give the
response “not on the list”. This game could be adapted for any words such
as (a) Cities, (b) Bones in the body, (c) Scientist, (d) Poets, (e) name of ani-
mals. The possibilities are very wide and could include foreign languages.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 233

6. [CAT into DOG] A program prints out a starting word and a finishing word
selected randomly from a fairly long list of data set. You have to input one
word at a time through keyboard, differing by only one letter in each case,
so as to end up with the second word using as few words as possible. The
program counts the number of words input and recognizes the second word,
you are aiming for. It is possible to get the computer to check that you do
not cheat by changing more than one letter at a time.
7. [Magic squares] Use your imagination to change the numerical data for
numbers so that they form a magic square. Each row, each column and both
diagonal always add up to the same number in a Magic Square.

Example:
Try for the data set 6, 7, 2, 1, 5, 9, 8, 3, 4. Many other are possible with 9 or
(32 ) numbers, but you could extend to 16 or (42 )numbers (52 or 62 or 72 or
82 etc.). Write a magic square program.
8. [Word game] A program generates 10 letters at random, from which you
have to make up words, input under the control of a loop which counts how
many entries have been made. The program will check that the correct letters
are used and that no letter is used more than once, unless it is given more
than once, but cannot check that a word is genuine (for which a dictionary
might be used - afterwards!). Words must be at least 3 letters long and points
are scored as follows:
Word size 3 4 5 6 7 8 9 10
Score 3 5 8 12 20 35 60 100
9. [Word game]

(a) A program generates a 3 × 3 array of 9 random letters. Words can only


be made using letters adjacent in row, column or diagonal in a table. For
234 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

example, any letter in position x could be used before or after that in po-
sition A. Three-letter words areallowable. Timing and scoring as
100
Score = (2l−2 + l) × n−2 , where l = 3, 4, · · · , n and the table is
2 +l
xx
Ax
xx

(b) Letter weighing could be used such that letters E and T are more likely
to appear than Z or Q, etc. Both of these word games could be played in
other languages.

10. [Word squares] The idea is to produce a grid of letters as given below:
S I NG
I DE A
NE AT
GAT E
which make up genuine words in all rows and all columns. The text cursor
may be made to move to the beginning of the first row and then the letters
may be changed by overwriting using key control. This method of working
saves writing grids of words all over pieces of paper in an attempt to solve
the puzzle. Write this program.
11. [Hangman] A game to play when no friend is available. Hangman is that
kind of game. Write this program using the following steps.

(1) Give an introduction and instructions to the user.


(2) Selection of a word from data using random number generator and a
character variable.
(3) Count the number of letters and print the same number of dashes.
(4) Input a letter, initiate a count of guesses.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 235

(5) Test the letter for match, replacing dashes for the letter wherever it
matches.
(6) Repeat the process from (4), adding one to count and check the counter
for its limit.
(7) At any stage, a word may be typed instead of a single letter. If the word
does not match exactly then print ‘Bad luck’ and give no further informa-
tion regarding the letters. Add one to count and invite another guess. If the
word does match, then the program should print a message such as ‘Well
done. You took guesses.’, where the number of guesses should be inserted
in the space.
(8) Invite the user to have another go (recognized by Y or YES) in which
case the program loops back to stage (2).

12. Write a program to distribute a randomly suffeled deck of 52 playing cards


into four players. Also display each hand.
13. In a well-known card trick

(1) Player A displays 21 different playing cards in columns of 7 cards each.


(2) Player B secretly chooses one of the cards and tells player A the num-
ber of the column it is in.
(3) Player A gathers up the cards, displays them in columns again and one
more player B identifies the column containing the selected card.
(4) & (5) same as step (3).

By gathering in the cards column by column with the selected one second
of the three and by subsequently displaying the cards row by row, player A
ensures after step (5), the chosen card will be the 4th in column 2 and can
thus be identified to a suitably astonished player B. Write a program which
takes the role of player A.
236 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

14. The organizers of the Calcutta senior division football league have ap-
proached you to help tabulate their results. All data will be available in a
file in the following format (team; matches played; won; drawn; goal for;
goals against; points). Your program must

(a) update the file whenever a match is played (e.g. input - Mohan Bagan,
Aryan, 3, 1 means Mohan Bagan beat Aryan by 3 goals to 1) points are
collected as 3 for a win, 1 for a draw and 0 for losing.
(b) If a point is requested then your program should print the table in in-
creasing order of rank. Rank is calculated as per the following rules.
(1) In decreasing order of points.
(2) If two or more teams have the same number of points then the team
with higher goal difference ranks before the other teams.
(3) If the goal difference is also the same then the team with greater
goals for ranks before the other teams.
(4) In case none of the above rules work, ties should be resolved arbi-
trarily.

15. [Music] Write a program which plays an accurately recognizable tune. On


some computers this could be done on 5 lines or fewer but refinements of
harmony and dynamics (i.e., loud and soft, etc.), vibrato, etc. (if available),
would make it more interesting.
16. Print a histogram (on its side) to represent input data.
17. [Rectangle numbers] Write a program to generate a rectangular numbers.

(a) How many ways, the number n can be represented by a rectangle of


dots or ‘∗’? Also write a program to find the factors of n. [i.e., n = n1 ×n2 ,
where n1 and n2 are the factors of n].
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 237

(b) Extend the program to find the factors for any number. Count the num-
ber of factors.
(c) Display your results by rows of dots or of ‘∗’. Use clear screen routine
and expect an input within a loop to give the signal to clear the screen so
the next pattern may be displayed.

18. Write a program for overlapping graph plot if y1 = x and y2 = (32 − 2 ∗


x), use suitable function/procedure to plot y1 , y2 and (y1 + y2) using three
different symbols, with respect to x.
19. [Polynomial solution] In a program, input two limits (upper and lower) of
x, and tabulate x and y (where y is the function of x) between the limits.
Increase x in fairly small steps s, where s is also input. Make a note of the
values of x for which y is nearly zero and then repeat the program using
the new limits and a much smaller step. The maximum number of roots of
the polynomial is equal to its order and so you could have 3 sections of the
graph to examine in finer detail if the order of your polynomial is 3.
20. [House] Write a program to draw a picture of a house using lines or charac-
ter blocks. Use colored lines and shading.
21. [Color] Write a program to arrange for the screen to turn red when RED is
input, green when GREEN is input, etc.
22. [Tessellations] Write a program for the following

(a)
(1) Draw a small 25 triangle with its long side horizontal.
(2) Repeat this to produce a row of 25 triangles, all touching.
(3) Fill the screen with these triangles, all row touching.
(4) Produce other tessellations of the same shape (25 triangle).
(b)
(1) Draw a small rectangle with one side twice the other.
238 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

(2) Produce a basic pattern unit using this rectangle.


(3) Fill the screen with your pattern.
(c) Produce a chess board, shaded appropriately.
(d)
(1) Draw a small regular hexagon (i.e., all sides and all angles are equal).
(2) Produce a tessellation of these regular hexagons to fill the screen-like
cell structure within a beehive.

23. [Random jump] Write a program which causes a line to be drawn from
one point to another and then to another, etc. All points are found using a
random number generator (uniformly). Random color selection and short
time delays make this an easy but attractive start to the use of graphics and
color.
24. [Random walk] The random walk differs from the random jump in that the
distance between one position and the next has a definite maximum size;
1
20 th of the width of the screen could be suitable. If your first point is in the
center of the screen, how long does the trace take to disappear? What is your
record for the longest time (or the most number of moves) before the trace
disappears? Write a program for this random walk.
25. [Chunky wall paper] Use the character graphics idea but scale it up to, say,
a 4 × 4 grid of characters. Arrange for the basic pattern to be defined by 16
numbers chosen randomly and place it at regular intervals to fill the screen.
Give full color but choose selectively for best results.
26. [Circles] Plot a circle using x2 + y2 = r2 . Measure the diameter (2r) hor-
izontally and vertically on the screen, and use a scaling constant k (also
called aspect ratio) to give a perfect circle i.e., x2 + ky2 = r2 Modify your
program to produce a set of concentric circles.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 239

27. [Parabola] For example, if y2 = ax, input a value for a and draw a graph of
y plotted with x, where x is stepped from some suitable negative value to a
suitable positive value. Small steps take longer but should give a smoother
curve. Write a program to test the above statements.
28. [Stretch and squash] Write a program for the following:

(a) Using line graphics, draw a simple shape such as a square.


(b) Control the movement of the shape about the screen using x, y control.
(c) Input a scaling factor. Scale, by which the figure is to be enlarged.
For example, 1 would produce normal size, 2 would produce an identical
shape but twice as high and twice as wide, and 0.5 would produce a figure
of half height and width.
(d) Distort the shape by multiplying the y movements by one scaling factor
and the x movements by another.

29. [Rotation] Write a program to draw a simple shape such as a square and ro-
tate it by 300o in a clockwise direction about the origin. Extend this program
to the general case of angle θ o .
30. [Spirals] Write a program to draw a spiral. A spiral of Archimedes is rep-
resented by the following relation: r = a ∗ t, where r is the radius, t is the
rotation from a given direction and a is a constant. [Note: Convert from polar
to Cartesian coordinates and also decide the step size.]
31. [Bar chart] Write a program such that a set of data may be represented
on the screen by a bar chart, together with suitable headings. This can be
achieved using ‘∗’ but may be more detailed and certainly more attractive if
colored fine graphics are used.
32. [Pie chart] Write a program which represents data in the form of a pie
chart, where the area of the sector is proportional to the relative size of the
240 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

quantity. Each sector should be shaded a different color if possible and must
have label of identity.
33. [Large letters]

(a) Write a program for printing a large t on the screen by using graphics,
7 lines high.
(b) Move the shape around the screen by a simple (x, y) control.
(c) Write subroutines for other letters and print a word on the screen.
(d) Alternatively, plan out a grid, as shown for character graphics, and use
7 numbers to define each large character and two more to fix its position
on the screen.

34. [Picto-gram] Write a program for the following:

(a) Draw a simple shape and then cause it to be made bigger.


(b) Draw a simple pie chart and cause its radius to be doubled (i.e., its area
to be increased fourfold). Pie charts may be used to indicate total numbers
as well as proportions in this way.

35. [Waves] Write a program for the following:

(a) Display a sine curve/wave.


(b) Combine two waves to show harmonics or beats.
(c) Use (colored) graphics to give improved definitions.
(d) Combine many waves of related frequency and specified amplitude to
give Fourier series to simulate any waveform. For example, a square wave
1
is made up of only odd harmonics with amplitude of , where n is the
n
number of harmonic. (The first 10 odd harmonics will give quite a good
impression of a square wave.)

36. [Moire patterns] Write a program for the following:


COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 241

(a) Print a set of vertical lines of spacing s unit (pixel) right across the
screen. Print a second set of vertical lines of spacing t (s < t < 2s) to
fill the screen. The resulting Moire pattern indicates the size of (t − s)
compared to s. This pattern is produced by the railings on many road
bridges over motor-ways - as seen from the motor-way. The pattern is a
helpful model to explain the formation of “beats” in Physics.
(b) Print a set of equally spaced horizontal lines on the screen. Then, in
the same color, print a second set of equally spaced parallel lines at a
shallow angle to the horizontal. The lines cross at regular intervals to form
a distinctive pattern.
Vary the angle between the two lines. The pattern spacing should increase
when this angle is made smaller (a useful technique for detecting small
changes in angle).
(c) Plot two sets of concentric circles, all equally spaced but with slightly
different center positions. The resulting Moire pattern is the same as the
interference pattern of waves from two point sources.
(d) Try devising your own patterns using the Moire technique. Are any of
them useful?

37. [Graphics designer] Planning out user-defined graphic shapes on paper can
be tedious because if any mistake is made either it has to be rubbed out
or another diagram has to be drawn. A simple graphics program can be
written to modify shapes on the screen by the rubbing-out method. A yellow
character square may be moved up, down, left or right and then printed as
either a black square or a white square within an 8 × 8 character grid.
38. [Pixel patterns] Due to a finite pixel size, perfectly smooth lines can rarely
be drawn on the screen. Use of this imperfection can be made to produce
patterns.
242 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

(1) Write a program to draw a set of overlapping lines.


(b) Arrange for (i) color, (ii) maximum width, (iii) maximum height, (iv)
step size to be input.
(c) Arrange for patterns to be printed on top of one another in different
step sizes and colors.
(d) Arrange for the repeats to have different outline size or shape but to be
placed symmetrically with respect to the first pattern.

Make a note of the values needed for your favorite patterns.


39. [Horse race] Write a program for the following:

(a) Create a racing horse with rider in two character spaces.


(b) Make your horse race across the screen.
(c) Create a race track with 4 horses, of different colors, racing at rates
controlled by random numbers.
(d) Stop the race when the first horse crosses the line.
(e) Create sounds to make the race more exciting.

40. [Knight tour] For the chess enthusiast - write a program in which a single
Knight visits every square on the board once only.
41. [Magic squares] A magic square is divided up into a number of small
squares, either 3 × 3, 4 × 4, etc. with a 3 × 3 square the numbers 1 − 9 are
placed in the squares so that the addition of any three numbers in any one
direction is the same. For the 3 × 3 this total is 15. For n × n the total is
1 2
2 n(n + 1). Write a program to find all the magic squares of order 3 × 3.
Then try 4 × 4. [Note: This problem will take a lot of computer time and is
not as easy as it seems at first sight.]
42. [Fortune telling] A computer is an ideal medium for fortune telling since
it has an inherent mysticism. A program could deal with normal astrology,
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 243

giving birth signs, temperament, most suitable partner, lucky day, etc. Al-
ternatively it could use numerology, which takes regard of date of birth,
favorite number, name, with some other factors. These are used in calcula-
tions to give information about the person or the future.
43. [Minimum and maximum attack problem] This program is strictly for
the chess enthusiast

(a) Take the eight major chess pieces of either color, i.e. King, Queen, two
Bishops, two Knights and two Rooks, and place them on a chess board so
that the minimum number of squares are under attack by the pieces.
(b) Do the same, so that the maximum number of squares are attacked.
[Notes: The minimum is considered to be 16 squares including those con-
taining pieces.]

The maximum number of attacked is considered to be 63 although several


solutions for all 64 are possible if the Bishops are on the same color. Write
a program to find a solution to one of these problems or at least print out the
best to date after a limited computer run.
44. [Chess] It is unlikely that you would have enough time or computer access
to write a program that plays even a basic form of chess. Instead try and
write a two-move chess problem solving program.
Input the positions of the pieces on a board using a simple code, e.g. 11
for white Pawns, 12 for white rooks, 13 for white Knights etc., with 21 for
black Pawns and 22 for black Rooks etc.
Assume white moves first, print out all combinations of white and black
moves. Examine the result after each move for checkmate.
This is not an easy problem, so approach it slowly and carefully. At some-
time incorporate a routine to actually print out the chess board with the
pieces.
244 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

45. [Life] Life is a modern technical game very popular in recent years. Basi-
cally we must imagine a very large chess board of thousands of squares. We
place a pattern of live cells on certain squares. Any one cell is surrounded
by eight squares. If only one of these eight squares contains a live cell then
the center cell will die. If the eight squares contain two or three live cells
then the center cell will continue to live. If the surrounding squares contains
four or more live cells then the center one will die, from over population.
On the other hand, if the center square is empty, then if it is surrounded by
exactly three live cells a new cell will be born in the center square.
All these deaths and births take place at the same instant to produce a com-
pletely new pattern of cells. The whole series of cell pattern of cells. The
whole series of cell patterns arises from the original pattern input. Some
series will die out, others will move around the chess board.
Beware of the constant loops that flip from three horizontal squares to three
vertical squares and back again.
Write a program to accept any pattern input and show the patterns of each
step.
46. Write a program to play simple games and learn as it plays. The approach
is simple - code and store all the possible positions and moves for the com-
puter. Initially give all moves an equal weighing factor. Play a game with the
computer choosing its move at random. When it loses penalize its last move
by reducing the weighting factor and thereby the likelihood of that move in
future.
A simple game to play in Hexapawn, which consists of a 3 × 3 chess board
with 3 white and 3 black Pawns opposite each other. Pawns move one square
at a time towards each other and capture diagonally as in chess. There are
three winning positions:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 245

(a) By advancing a Pawn to the third row.


(b) By capturing all enemy Pawns.
(c) By achieving a position in which the enemy cannot move.

To simplify the program the computer should always move first or always
move second. Once you have mastered this program expand it to a 4 × 4
board and so on. You might then try simplified draughts with just two black
and two white pieces on a 4 × 4 board. Theoretically there is no limitation
to the technique, but on no account try chess unless you have twenty years
and unlimited computer time to spare!
47. [Board splitting game] Consider the following game. An n × n square
board is given, where n is a power of 2. Each cell of the board contains
an integer. There are two players Max and Min. Max starts the game by
splitting the given n × n board vertically down the middle; he retains either
the left or the right half for Min and gets rid of the other half. Then Min
splits the retained portion of the board horizontally at the middle and keeps
either the top or the bottom half for Max, who again splits the remaining part
of the board vertically and retains one of the halves for Min and so on. After
log2 n pairs of moves a single cell remains that can no longer be split. The
context p of this cell determines the outcome of the game. If p is positive
then Max gets p rupees from Min; if p is negative then Min gets p rupees
from Max; when p is zero then game ends in a draw.
Example:
Board 1 : n = 4
-2 3 0 5 Max -2 3 Min
9 2 -6 8 Keeps 9 2 Keeps -2 3
1 -4 7 -9 left 1 -4 top 92
-3 6 0 4 half -3 6 half
246 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

Max Min
Keeps 3 Keeps
right 2 bottom 2
half half
For the sequence of moves shown in the example, Max gets two rupees from
Min in the end.

(a) For the board configuration shown in Board 2, with Max to move first,
construct the entire game tree t.
Board 2: n = 4
1 -5 6 3
5 2 -2 -8
6 -9 4 7
-1 4 7 -3

(b) What is the MINIMAX value of the game tree T (say)?


(c) Suppose the content of none of the cells is known to Max initially.
What is the minimum number of cells whose contents must be known to
Max if his best starting move in the game tree T is to be determined using
(1) Alpha-Beta Strategy: To modify the search procedure slightly to han-
dle both maximizing and minimizing players, it is necessary to modify
the branch-and-bound strategy to include two bounds, one for each of
the players. It requires two threshold – one for a lower bound that a
maximizing node may ultimately be assigned (i.e. alpha) and other for
an upper bound on the value that a minimizing node may be assigned
(i.e. beta).
(2) SSS∗ strategy: Attempt to avoid exploring bound positions that can
be guaranteed to be irrelevant. Alpha-beta is quite different, being a
depth-first search rather than one that uses the values of partial solutions
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 247

to guide the search. However, it does calculate MINIMAX values, and


uses them to prune the game tree.
(d) In T, reorder successors of internal nodes from left to right so that the
MINIMAX value of T remains the same but the number of cells whose
contents must be known to Max in order to determine his best starting
move using Alpha-Beta is minimized. Determine the corresponding board
configuration.
(e) In T, reorder successors of initial nodes from left to right such that the
MINIMAX value of T remains the same but the number of cells whose
contents must be known to Max in order to determine his best starting
move using SSS∗ is maximized. Determine the corresponding initial board
configuration.

48. SQR is an 8 × 8 integer array. We interpret SQR as a chess board. There is a


White King (WK) and a Black Queen (BQ) on the chess board, and nothing
else. The position of the WK is indicated by a 1 while the position of a BQ
by a 2, other entries in SQR are 0. The WK is in check by the BQ if the BQ
is in the same row, column and diagonal as the WK; otherwise the WK is
out of check. If the WK is in check, it can try to get out of check by moving
one square vertically, horizontally or diagonally in an appropriate direction.
However it may not always be possible for it to get out of check, by moving
one square.
You are supplied with SQR as input. First determine whether the WK is
in check by the BQ, and output an appropriate message. If the WK is in
check, then determine whether it is possible for it to get out of check by
moving a square in an appropriate direction and output a message; if it is
indeed possible for the WK to get out of check, suggest a move that will
accomplish this.
248 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES

49. John Conway’s Life game involves a colony of organism on an n × n rectan-


gular array of cells. Each cell is either unoccupied or occupied by a single
organism. Each cell has eight neighboring cells, those with index 0 or n + 1
are permanently unoccupied.
In one generations organisms may die or be created or survive according to
the following rules.

(a) An organism with fewer than 2 or more than 4 neighbors die (is re-
moved from the array) otherwise it survives.
(b) An unoccupied cell with exactly three neighbors has an organism
placed in it in the next generation.
All births and deaths occurs simultaneously and together constitute a sin-
gle generation.
(1) Write a program which simulates the colony for ten generations.
Data is n followed by n × n values representing the initial configuration.
Print out the state of the colony after each generation. Try the following
initial cell patterns
000000000000000
0∗∗∗000∗000∗∗∗0
00∗00000∗00∗0∗0
000000∗∗∗00∗0∗0
000000000000000
(2) Modify your program so that it will halt as soon as there are no or-
ganisms alive.
(3) Modify your program so that it halts if 2 successive generations are
identical.

50. There are n teams participate in a football league. The teams are numbered
1 through n. The teams play the same number of games. Their records are
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 249

summarized in an n × 5 array GAME. The ith row of GAME corresponds to


team i. The column gives the following information.
Columns Contains
1 No. of games won,
2 No. of games drawn,
3 No. of games lost,
4 No. of goals for (i.e., scored by the team), and
5 No. of goals against (i.e., scored against the team).
Two points are awarded for a win, one point for a draw and no points for a
loss. The team with most points wins the championship. In case of a tie in
points for first place, that team wins for which goals for minus goals against
is larger. If the tie remains, there is a play-off. (It is assumed that such tie,
if any, occurs for no more than two teams). Given n and GAME, write a
program to determine which team is the champion or whether a play-off is
needed. In the later case, output the teams for the play-off.
Chapter 16
MISCELLANEOUS PROGRAMMING
PROBLEMS

Implement the following problems.

1. Write a program which will accept the radius and height of a regular cylinder
as input. Output (a) the volume, (b) the total surface area.
2. Write a program whose input is the radius r of a sphere and Output (a) its
volume V , (b) its surface area A.
3. Write a program which accepts a number, n as input. Output the sum of first
n odd numbers. What do you find? Is it true for all values of n?
4. Write a program in which accepts a number as input and output its conver-
sion from miles to kilometers (given that 5miles = 8km). Produce an output
which is understandable to others.
Example:
If 10 were input, then output should be given as: 10 miles = 16 kilometers.
5. Write a program which takes an integer number, n, as input and print them
in reverse order.
6. Write a program whose input is the year of a date and prints out whether the
year is “a leap-year” or “not a leap-year”.
7. Simulate the experiment in which paper is repeated folded in half. How
many times would you need to double its thickness in this way to give a
thickness of (a) 1 cm, (b) 1m, (c) 1km, (d) the distance between the Earth
and the Sun 1.5 × 1011 m, (e) 1 light year. (Assume that you start with a
thickness of 0.10mm initially.)

251
252 CHAPTER 16. MISCELLANEOUS PROGRAMMING PROBLEMS

8. (a) Input two numbers, A and B, to a computer to print ‘A∗B= ’ and


awaiting for an input of C. The computer should indicate whether your
answer is correct or not.
(b) Try the same idea for testing the other methodical functions.
(c) For division, test the answer for correctness upto 3 decimal places.
9. [Password] Clear the screen and make the computer ready to accept a pass-
word from your friends. Print suitable messages in reply to their attempts.
(Passwords are used to provide computer security but they are input without
the word showing on the screen!)
10. [Arithmetic test] Write a program for the following:

(a) The computer prints out a sum (using 2 numbers, generated by random
number generator, up to a certain level of difficulty, e.g. neither number
should be greater than 10 for an easy grade), checks the answer offered
by the user, and print out an appropriate short message. 10 sums are set
and marked in this way after which a score out of 10 is given.
(b) Modify the program to allow the user to input the level of difficulty.
(c) Modify the program to test (1) subtraction (always quoting the larger
number first), (2) multiplication, (3) division (where the first number is
the product of the two random numbers - thus ensuring that the answer is
always integer).
(d) Combine all features to give (1) Choice of operator to be tested, (2)
Choice of level of difficulty, (3) Possibility of mixtures of all 4 operators
(bearing in mind that.
Example:
97 − 43 is easier than 97 ∗ 43!).

11. [Telephone index] In your program, input a list of names of your friends
in an alphabetical order, and a second list of their telephone numbers using
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 253

matched subscripts. Terminate your list by −999. Now the files are ready
for use.
[Note: Files are normally created on a disk rather than using RAM.] Input
a name. Your program should output the name followed by the correct tele-
phone number.
12. [Examination results] Input an alphabetical list of names, each one fol-
lowed by an “exam” mark. If distinction is given for marks greater than
80%, merit is given for marks greater than 65%, pass is given for marks
greater than 50% and otherwise fail. Output lists of names under the head-
ings of (a) distinction, (b) merit, (c) pass and (d) fail. The same variable
must be used for both name and mark arrays and the list should be termi-
nated by some distinct signal such as −999. After each list is printed, output
the percentage of candidates in that group and a cumulative percentage.
Example:
If 15% have a distinction, 20% merit and 35% pass, then 35% have a merit
or better and 70% have a pass or better.
13. [Pascal’s triangle] Write a program for the following:

(a) Generate each row of Pascal’s triangle. Each number is equal to the
sum of the two numbers immediately above it (see the diagram below).
(b) Print out the first 10 rows of the triangle in the pattern shown.

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
254 CHAPTER 16. MISCELLANEOUS PROGRAMMING PROBLEMS

14. [Odd one out] Write a program which can find one number out of a set
of 6 which does not fit in with the rest, and state why. For example, if the
numbers were 3, 6, 8, 9, 12, 15 then 8 would be the odd one out because . . .
15. Prime numbers by the Sieve of Eratosthenes use an array (of 1000 members
if possible) and set all members to unity. Starting with 2 and taking each
integer in turn up to 34, set all members of the array with subscripts equal
to multiples of that integer to zero, unless that multiple is unity.
Example:
When dividing by 3, a(6) = 0, a(9) = 0, a(12) = 0, etc., but a(3) = 1 (not
changed). Output the subscripts for which a( j) = 1, where j is the subscript.
16. [Consequences (trivial but quite amusing)] Use a two-variable array to
store n possible first words, n second words, n third words, etc. Use a ran-
dom number generator to print out a muddled statement.
17. [Distance chart] Using character recognition and two-variable array, devise
a program to give the distance between any two places chosen from a given
list. Start with 3 or 4 places and work up to a more useful list if you consider
it worthwhile.
Many motoring atlases contain a chart with the information you need and in
the form you need it.
18. [Vocabulary testing] Write a program for the following:

(a) Type in pairs of words (e.g. English word, French/German equivalent).


The last entry should be ZZZ which terminates the list. The computer
counts the number of English words on the list and prints out a word
at random from the foreign word list and you have to match it with the
English equivalent. The computer gives you 20 words (say) to translate
and gives you a mark out of 20 at the end. If you get any wrong, the
computer will print out the correct answer. [Hints: Use a 2-dimensional
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 255

character array of size 2 × 500, if your program can cope with the size to
give 500 pairs of words.]
(b) Alter the program to test your ability to translate into a foreign lan-
guage.
(c) Two foreign languages could be tested using, a 2-dimensional character
array of size 3 × 500. The data could be built up over weeks/months if the
program is re-saved each time after modification. The size of the RAM
will be your limit – but files could be used if you have a hard disk, i.e. a
random access memory.

19. Write a program to print out a message in code. For example, arrange for
one key to print out the letter with a code greater than it by

(a) Unity - such that when you think you are typing in CAT the letters
DBU appear on the screen!
(b) Any integer, but take care that all letters are available and used - you
have to decide how Z is to be represented.
(c) An integer determined by some formula of your invention.

You will also need to decode the message by using the computer. If you
have a printer, you could write secret messages quickly and send them to a
friend to decode on his or her computer.
20. Input an alphabetical list into a one-variable array. Input another word and
merge it alphabetically with the others and place the new list in a second
array. Write the program.
21. [Selection sort] This is a method (often used by hand with small quantities
of data) in which the lowest number is found from an unsorted list and
merged into a sorted list. The process is repeated until the unsorted list is
empty.
256 CHAPTER 16. MISCELLANEOUS PROGRAMMING PROBLEMS

22. [Searching] Input 20 names in alphabetical order in an array. Search to see


if a particular name is in the array using the High-Low technique (as you
would use a dictionary) rather than start at the beginning and work stolidly
through. This is merely an exercise - the program will sort very rapidly
through millions of individual files in a fraction of a second in this way:
very useful to the police, banks, etc.
23. [Merge sort] Merge sorting of two roughly equal-length lists is the most
efficient but needs plenty of RAM. The process is shown by an example.
Example:
Let array A hold numbers 8, 3, 4, 1 and array B hold numbers 2, 7, 6, 5.
The numbers are paired from the left (one number from A and one number
from B) compared and placed alternately in pairs (lowest number first) in
arrays C and D. Thus C will hold 2, 8, 4, 6 and D will hold 3, 7, 1, 5 after 4
comparisons The first two numbers from each new list are now compared,
two at a time, and placed in order as a group of four being placed alternately
in A and B. Thus A will now hold 2, 3, 7, 8; and B will hold 1, 4, 5, 6. The
process is repeated for the 3rd sweep to place 1, 2, 3, 4, 5, 6, 7, 8 in C. 8
items of data in 2 equal lists requires 3 sweeps (8 = 23 ). 1024 items of data
in 2 equal lists requires 10 sweeps (1024 = 210 ).

(a) Write a program to generate 32 random integers up to 100 and place


them in 2 equal arrays. Also program your computer to sort these num-
bers, displaying the contents of the relevant arrays after each sweep.
(b) Adapt your program so that it may be used as a subroutine for sorting
words.

24. Write a program for the following:

(a) Countdown in 1 second intervals from 10, 9, 8, 7, . . . to zero.


COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 257

(b) Modify your program to stop the countdown by typing in a password


(which is not printed on the screen). Provide a suitable display including
sound if you can.

25. [Pelmanism] Write a program which prints out a random selection of words
(say, 6 out of a much larger array read from data) for 5 seconds and then
allows one minute for you to type the words onto a blank screen. Each word
must be spell correctly if the computer is to recognize it. This is a funny
way of learning to spell words you find difficult to remember. Foreign words
could also be tested in this program.
26. [Word search within a string variable]. This is most useful for programs
involving teaching by computer. For example, can you test to see if the word
RED appears in GLOWING RED LIGHTS?
27. Write a program in which input letters one at a time using key control func-
tion when the screen is blank. As soon as a password is received in this way
(which is not printed on the screen), provide a suitable reward.
28. A coded message uses (i) the first letters, (ii) the second letters, (iii) the last
letters, (iv) the first, then second, then third, etc. letters of each word input.
Write a program to decode a message by (a) inputting one word at a time,
(b) inputting a whole sentence (such that gaps have to be detected).
29. [Vowel search in a string of words]. Write a program whose input is a
string of words. Output the number of each vowel found, and the total num-
ber of letters used.
Use the same program to search (a) several long sentences, (b) sentences
from a foreign language. Why might a printer be interested in the results of
experiments like these (by using much more data)?
30. A palindrome is a word which reads the same whether the letters are read
from right to left or left to right. Write a program
258 CHAPTER 16. MISCELLANEOUS PROGRAMMING PROBLEMS

(a) To test for palindromic form by comparing first and last letters, etc.
(b) To use the computer to find all the 4-letter palindromes by trial and
error (i.e., printing out 26 possible words beginning with A, 26 beginning
with B, etc.). When the screen is full, you will have to spot the genuine
words (or possible likely words), write them down on a piece of paper,
and press a key for the next screen full! The computer will print out a
total of 676 possible words for you to check – much quicker than hunting
through a dictionary.
(c) To find all the 5-letter and 6-letter palindromes.
(d) Write a generalized program for palindrome checking.

31. [Message revealed] The computer is programmed to give a cross-word type


clue including length and then pauses for 10 seconds (say). The word is then
printed out slowly, one letter at a time. The user may interrupt at any stage
to type in the rest of the word and the computer allows a few seconds for
this, once started.
The aim is to try, to type out the word correctly with as few clues as possible.
The computer can store words and their clues in a 2-variable array, and count
the number of clues needed.
This is obviously a game to set up for a friend to play.
32. Write a program for reversing a number using the following rules:
(a) Use string labels throughout and reverse.
(b) Split up by dividing by 10 and fit together.
33. Abbreviations are very useful for increased speed of working.

(a) Train your computer to recognize abbreviations for days of the week
and to print out in full.
(b) Modify the program, using key input, to recognize when a full stop is
placed and to continue the word rather than print the full stop.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 259

Example:
Typing ‘SAT’ would appear as ‘SAT’ but ‘SAT.’ would appear as SAT-
URDAY
(c) Use your imagination to extend this idea to other useful words and
phrases.

34. How good is your typing speed? (Simple timing facilities are needed.)

(a) Arrange for the computer to print out at random any upper case letter
and give 2 seconds for the correct key to be typed. After a 2 second rest
time, repeat the sequence to give 10 letters altogether – the computer will
tell you how many letters you typed correctly.
(b) Modify the time scales as you become more expert.
(c) Include a stopwatch timing to give the time you needed to find 10 let-
ters.
(d) Cancel the rest time and print out the new letter to be typed as soon
as the correct key is pressed. Add one second to the total time for each
wrong key pressed. Test (i) 10 letters, (ii) 25 letters. What is your record?
(e) Include numbers, punctuation marks and lower case letters.
(f) Arrange for the computer to test you on 6-letter words instead of iso-
lated letters – this uses common letter combinations. All words should be
sorted in a file.
(g) Extend the idea to whole phrases (i) in English, (ii) in a foreign lan-
guage.

35. [Economical readable output] All computers have set print fields for con-
venience but they are not compact or easy to read when numbers vary con-
siderably in size. Write a program which will give a space of 2 characters
between numbers and keep on printing on the same line until there is not
260 CHAPTER 16. MISCELLANEOUS PROGRAMMING PROBLEMS

enough room for the complete number. Test your program by printing the
first 58 square numbers.
36. [Enlarging] Input any set of 3 or 4 characters. Output a large display of
these characters, using ′∗′ . A decade or more ago, a similar challenge would
have been to punch out messages on paper tape (with 5 or 8 holes across the
width).
37. [Shapes] Combine shaped characters, if easily available, to produce attrac-
tive patterns. Define the basic pattern and command the computer to repro-
duce large number of them!
38. Given a matrix MAP(m, n) which indicates 0 and 1 if the corresponding
plot within a square-area belongs to an estate or not find the cost of fencing.
Assume each plot is 100m × 100m and cost of fencing of 1m is Rs.5/-.
39. Write a program which sorts the contents of a two-dimensional (2-D) array
so that they are in ascending order when the array is scanned row by row,
left to right. Your program should not use any storage for additional arrays.
40. Input a list of arbitrary order with each name in the form of first name,
second name and third name. Output the list sorted over third name with
each name in the form of third name, first name and second name. If third
name is same for some names, output them sorted over first name. Note that
some names in the list may not have second names.
41. There are two input files A and B, both sequential files on disk and sorted
in ascending order of their pay values. These two files are to be merged into
a third file, C, also sequential on disk, so that records in C are sorted in the
ascending order of key values. The three files have the same record format:
Key field : 5 digits.
Non-key fields : 95 characters.
Write a program whose inputs files A, B and output C.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 261

42. A file OLDMST contains details of current bank account balances. Each
record is of the form: account number, current balance and records are in
ascending order of account number. There is at most 1 record for an account
number. A file amendments contains details of recent transactions against
current accounts.
Each record is as: account number, change records are in ascending order
of account numbers. But there may be many records for an account number.
Write a program to update OLDMST using amendments.
43. Draw the flow-chart and write a program which inputs two complex num-
bers in the form of character strings and outputs the product of these two
numbers also as character strings (e.g. Input : 2 + 3i, 4 + 2i and output :
2 + 16i).
44. In pigLatin a word such as KING is replaced by INGKAY, while TROUBLE
becomes OUBLETRAY. The first vowel of the original word becomes the
starting point of the pigLatin word and all preceding letters are shifted to
the end and an AY is added. If a word starts with a vowel then translation
into pigLatin is done by adding a WAY at the end e.g. APPLE becomes
APPLEWAY. Write a program which converts English words into pigLatin.
45. Two given alphanumeric strings are A and B (say). The first one is a string
of nonblank characters of length at most 64 starting from the first position.
There can be blanks only at the rightmost end of the string A. No blanks
are interspersed among the nonblank characters. The second string B is a
similar string of nonblank characters starting from the first position, but of
length atmost 5. If the string B occurs as a substring anywhere in the first
string A, then you are required to delete such an occurrence from the first
string A and pack the remaining nonblank characters i.e., move them to the
left so that nonblanks remain embedded among the nonblank characters.
262 CHAPTER 16. MISCELLANEOUS PROGRAMMING PROBLEMS

Example:
If A and B are as follows:
A = ‘COBCABABCCDDEABCHAB’ and B = ‘ABC’
with the rest of the positions blank, then after modification the first string
would look like ‘COBCABCDDEHAB’.
46. The responses of an individual to a market survey questionnaire is supplied
in a form of a character string A. Each response to a question has been
encoded as a single digit. To ensure reliability, it has been decided to check
the consistency of data in A in the following manner. A positive integer n
gives the number of consistency checks to be performed on A. Two other
numeric arrays B and C are given, each containing n entries. The check to
be made on A is as follows: for each I lying between 1 and n, the C(I)th
character in A must be 0; again, whenever the B(I)th character in A is not 1,
the C(I)th character in A must be nonzero.
You are supplied with A, n and C as input. You have to determine whether
the data in A is consistent. If not, you have to output the number of incon-
sistent pairs of entries in A, and the positions in A of each such pair. Write
the program.
47. An alphabetic array NAMES having n elements is supplied as input. Each
element is a character string of length atmost m characters and is to be in-
terpreted as the surname of an individual. You are required to print out the
surnames in alphabetical (i.e. dictionary) order, with consecutive surnames
on the same line separated by at least two blanks. You will be supplied n, m
and NAMES as input. Draw the flow-chart and write the program.
48. A college maintains an alphabetically ordered file of its staff. At the be-
ginning of each academic year, an updated file is produced by a program
which reads the old file and an amendments file containing the names of
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 263

staff together with a code N indicating new or D for departing staff. Write a
program to implement it.
49. Set up files of driver and vehicle records. Write a program which inputs a
file of driver names and outputs for each, details of all vehicles owned.
50. Write a complete program that will create and utilize a sequential data file
containing names, addresses and telephone numbers. Include a provision for
the following features:

(a) Add a new record (i.e. a new name, address, telephone number) to the
file.
(b) Find and display a particular record, based on identifying information
entered from the console (e.g. a name).
(c) Delete a particular record, based on name or address or telephone num-
ber.
(d) Alphabetize the records, based on the last name in each record.
(e) List the entire file.
(f) Terminate the computation.
(g) Print the names starting with “A”, along with addresses, with proper
headings and sub-headings and the total number of such students at the
bottom of the list.

51. [π computation] Write a program to compute of the value of π using the


following relations:
1 1 1 1
(a) π = − + − + . . .
1 3 5 7
this converges slowly and can be speeded up by combining the items in
pairs as:
2 2 2
π= + + +...
1.3 5.7 9.11
264 CHAPTER 16. MISCELLANEOUS PROGRAMMING PROBLEMS

π2 1 1 1
(b) = 2 + 2 + 2 + . . .,
6 1 2 3
π4 1 1 1
or = 4 + 4 + 4 +...
90 1 2 3
A much faster method is Machin’s formula:
π −1 1 −1 1 −1 x3 x5 x7
= 4 tan − tan , where tan x = x − + − + . . .
4 5 239 3 5 7
x 2 x 3
52. The value ex = 1 + x + + + . . .
2! 3!
(a) Write a program to compute exp(x) or ex for any x.
1 1 1
(b) If x = 1, e = 1 + 1 + + + + . . .
2! 3! 4!
Thus calculate e to 10 terms of the series or to the greatest accuracy of the
computer, i.e. when the calculation of the next term makes no difference.

53. [Type setting] When setting up the type for a book or newspaper we are
concerned with three things: (a) size of print, (b) length of line, and (c)
design of each line.
If letters and spaces were of a fixed size then we would get lines of unequal
length, assuming we did not split words at the end of a line. An average
width of character and the precise length of the line are given then we can
adjust the overall character width to fit the line exactly.
Thus read the average width of a character and length of line as an input.
Now read in and print out a lengthy passage line by line, so that each line
ends on a word. Give the adjusted character width for each line. Try to avoid
leaving single words on a line by themselves when starting a new paragraph.
With a little thought this problem can be built up into a complete project in
itself.
54. An array A of n positive integers is given. We want to sort the array A in
ascending order of magnitude. One possible way is to find the minimum of
the set of numbers and output. Then replace that minimum element by a
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 265

very large number (which can not be the value of any element in the array
A) and repeat the process until all numbers are exhausted. Write a flow-chart
and the program.
55. Let A be an array of n sorted (in ascending order) positive integers. Let k be
a positive integer, which we want to search in array A by (i) linear search
and (ii) binary search. Write flow-charts for both the methods and write the
program.
56. Write a program to find a value of x satisfying the equation: 3x − cos x − 1 =
0 assuming x to be real, correct upto 3 decimal places, using any of the
numerical methods (bisection, regula falsi).
57. Write a program to find the value of integration of the function f (x) =
1/ log x, for x = 2 to x = 3 using Simpson’s 13 -rule correct upto 3 decimal
place.
58. Write a program to find the square root of a number n by iteration (i.e.
repeated trials and adjustments) using the following idea in the following
example.
Example:
Let a ∗ b = n.
Let the first guess be a = 10.
n n
Then a = = .
a 10
n
For the second guess, put new value of a = old value of a + to give
a
 n
10 + .
10
(a) The computer can continue this trial-and-adjust loop until you instruct
it to stop when a and b are the same (within limits you can specify).
(b) 4 significant figure is accurate enough for graphics. Is this method

quicker than using library function for n? Test by timing 100 calcu-
lations, for which n is increased from 2 to 101 for example.
266 CHAPTER 16. MISCELLANEOUS PROGRAMMING PROBLEMS

59. Write a program to explore continued fractions.


Example:
1 1 1
, , .
1+1 1 1
1+ 1+
1+1 1
1+
1+1
60. Write a program to solve simple polynomials of order 3 by iteration.
Example:
A simple polynomials of order 3 is x3 − 3x − 17 = 0
17
then x2 = (3 + ).
r x
17
Define y = (3 + ).
x r r
17 26
First guess: x1 = 3, y1 = (3 + ) = ;
3 3
x1 + y1
Second guess: x2 = , y2 = ...
2
This is a very tedious process by hand but very easy for your computer! Can
you extend this technique to higher-order polynomials?
61. Write a program to perform numerical integration of any function between
given limits (equal to area under the curve). Your limits may be input in run
mode in the usual way, as should the step size from one limit to the other.
The smaller the step size, the more accurate the integration, but the longer
it will take to do. Decide on the best compromise.
62. Write a program to print out (a) the first, and (b) the second differentiation
of a polynomial function.
63. Write a program for the following:

(a) Input a vertical velocity (and time interval steps) of a projectile. Output
the height above the ground and the velocity after each time step until the
projectile hits the ground. Output the total time for which the projectile is
in the air.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 267

(b) Modify the program to include the angle of projection θ and initial
velocity v0 to be an input. Output the total horizontal distance travelled as
well as the time of flight.
(c) Find the angle for largest range.
(d) Tabulate horizontal range against angle θ . How critical is the angle for
maximum range?
(e) Modify the program to include an air resistance term.
(f) Plot the motion using high resolution graphics.

64. Write a program to find the minimal spanning tree (MST) from the given
weighted, undirected, connected graph G.
65. Write a program for a cashier whose inputs are the cost of an item and the
note(s) and/or coin(s) offered in payment. Output the value of the change to
be given and how the change should be given, using the smallest number of
coins and/or notes.
Chapter 17
PROBLEM SET FOR FORTRAN

Program the following problems using FORTRAN.

1. Are the following valid fixed point variables in FORTRAN?


J, I, JAIL, Nbb4A, N + M, BETA, 2SUM, SUM SQUARE.
2. Are the following valid floating point variables in FORTRAN?
ALPHA, DELTA, GAMMA, XI, IY, INTEREST, ROOT(2)T, SUMDb45,
Cb47, YBAR, IBAR, Uhat.
3. Is this statement valid in FORTRAN?
y − 545.232 = 127.0 + 77.321 and X − 50.0 = 30 + 20.0.
4. What is the difference between (1) (L − M) + N and L − (M + N)? (2)
(L/M) ∗ N and L ∗ (M/N)?
5. Correct the errors in the following FORTRAN statements:
(1) S = A ∗ X2 + B ∗ X +C
(2) A = (X + 3) ∗ ∗N − R/Y
(3) B = X + 3N − R
(4) M ∗ M + 3.5 ∗ N + 2 = 0
(5) SQRT (IX) = X ∗ ∗0.5
(6) FUN = SUN(X +Y )
(7) VALUE = 1.0/ − 2 ∗ A ∗ ∗7/2
(8) RESULT = N ∗ ∗X ∗ (N − 2)
(9) RES = RAT ∗ IT EM1 + IT EM2
(10) A = 3.14/4 ∗ D ∗ ∗2
(11) X = A ∗ ∗2 + B ∗ ∗2 +C ∗ ∗2 − 3A ∗ B ∗C + D

269
270 CHAPTER 17. PROBLEM SET FOR FORTRAN

6. Determine the value of A, obtained from the following FORTRAN state-


ments and state whether the result is in fixed or floating point (a) A = 1/2
(b) A = 2 ∗ 4 + 5
7. Output the values of the following FORTRAN arithmetic expressions, and
verify the result with hand computed results.

(1) 25 ∗ ∗(1./2.)
(2) (2. + 3 ∗ ∗2)/(8 − 2 + 1)
(3) {(2 + 3) ∗ ∗2/(8 − 2 + 1)}
(4) 3 ∗ ∗2 ∗ ∗3
(5) (3 ∗ ∗2) ∗ ∗3
(6) SQRT (6.0 ∗ ∗2 + 6.0 ∗ 2.0 + 1)
(7) ABS(6.0 ∗ 2.0 − 3 ∗ ∗3)
(8) SQRT (6.0 ∗ ∗4) + ABS(4.0 − 6.0) + (4.0 − 6.0)

8. Are the following valid subscripts?


COUNT (NUM + 1), B(5 ∗ I), A(−1), A(X + 2), A(M + 2), A(−2 ∗ M),
A(K(5)), A(K ∗2), A(KOUNT ∗3+2), A(2−K), A(2K), IALPH(6∗II −3).
9. Write a flow-chart to calculate the sum of the following series:
1 2 3 99
+ + +··· + .
2 3 4 100
10. Give the algorithm and the flow-chart to find the sum of the following series:
x2 x3 x4 x5 x13
−x + − + − + · · · − .
2! 3! 4! 5! 13!
11. Write a FORTRAN program to find the sum:
x2 x3 x4 x5 x13
SUM = −x + − + − + · · · − .
2! 3! 4! 5! 13!
12. For a group of 100 students having roll numbers, scores in three tests, obtain
a flow-chart to find out the average of the three tests for each students.
13. Write FORTRAN program for the following algorithms

(1) (a) Read temperature in oC.


COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 271

(b) Calculate the corresponding o F and o K.


(c) Print oC, o F and o K.
(2) (a) Read 10 numbers one by one.
(b) Calculate the average.
(c) Print the average.
[Hints: Use a logical if statement and unsubscripted variables]
(3) (a) Read 10 numbers in an implied DO statement.
(b) Calculate the sum of these numbers using a DO statement.
(c) Calculate the average.
(d) Print the 10 numbers in implied DO.
(e) Print the average.
(4) (a) Read the values of A, B and C of the quadratic equation:
Ax2 + BX +C = 0.
(b) Calculate the real and imaginary part of the roots.
(c) Print A, B, C, the real part of root1 , the imaginary part of root1 , the
real part of root2 and the imaginary part of root2 . [Hints: Use arithmetic
IF]
(5) (a) Read 10 numbers in an implied DO.
(b Arrange the numbers in the ascending order.
(c) Print the rearranged numbers in implied DO.
(6) (a) Read the value of x.
(b) Find
 the value of y as given below:


 −19, −3 ≤ x < −2


 −11, −2 ≤ x < −1



y= 0, −1 ≤ x < 1


10, 1 ≤ x < 2






 20, 2 ≤ x < 3.
(c) Print the values of x and y. [Hints: use logical IF.]
272 CHAPTER 17. PROBLEM SET FOR FORTRAN

(7) (a) Read principal, annual percentage rate of interest and number of
years.
(b) Calculate the simple interest,
(c) Calculate the compound interest,
(d) Print simple interest and compound interest.

14. Suppose an amount of Rs.1000.00 is deposited in a savings account at 7%


interest compounded annually.

(a) Write a FORTRAN program which prints the amount of the account
each year for 15 years.
(b) Write a FORTRAN program to determine the number of years it takes
for the account to exceed Rs.5000.00.

15. The commission on a clerk’s sales is as follows:

(a) If sales < Rs.100, then there is no commission.


(b) If Rs.100 ≤ sales ≤ Rs.1000, then commission is equal to 10% of sales.
(c) If sales > Rs.1000, then commission is equal to Rs.100 + 8% of sales
above Rs.1000/-.

Write a FORTRAN program which reads total sales and calculate commis-
sion.
16. The commission on a salesman’s total sales is as follows:
(1) If sales is less than Rs.50, there is no commission,
(2) If Rs.50 < sales ≤ Rs.500, the commission is 10% of sales,
(3) If sales > Rs.500 the commission is Rs.50 + 8% of sales above Rs.500.
Write a FORTRAN program that read sales and print commission.
17. Write a FORTRAN program to compute the integration from 0.2 to 1.4
for the function sin x − ln x + exp(x) [Hints: use the following formula:
3h
I = [y0 + 5y1 + y2 + 6y3 + y4 + 5y5 + 2y6 + 5y7 + y8 + 6y9 + y10 + 5y11 +
10
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 273

2y12 + · · · + 2yn−6 + 5yn−5 + yn−4 + 6yn−3 + yn−2 + 5yn−1 + yn ], n is a mul-


tiple of six.]
18. Write a FORTRAN program to find the real root of: 3x − cos x − 1 = 0.
19. Write FORTRAN expressions for the following:
ab a
(a) , (b) 1 + .
c − d2 1
b+
c
20. Determine the output for the following FORTRAN programs:
(a) J = 3
(b) K = 2
K=5
10 DO 20 I = 3,8,2
IF (2*J-K) 10, 10, 20
IF (I .EQ. 5) GO TO 20
10 J = K
K = K+1
J = J+2
20 CONTINUE
20 PRINT 1,J
PRINT 1,K
1 FORMAT(I4)
1 FORMAT(I4)
END
END

21. Write a FORTRAN program to read values of y1 , y2 , · · · , y50 and compute


square roots except when y ≤ 0. Print the square roots when y > 0 and the
values of y when y ≤ 0.
22. Given a set of 100 numbers, write a FORTRAN program to arrange them in
ascending order. [Hints: use bubble sort algorithm.]
23. The mean, variance and standard deviation of x1 , x2 , · · · , xn are defined as:
1 1
m = mean = (x1 +x2 +· · ·+xn ), σ = variance = (x21 +x22 +· · ·+x2n )−m2,
n √ n
and s.d.=Standard deviation = Variance.
Write a FORTRAN program to calculate m, σ and s. d. of the data.
24. Answer the following questions.
274 CHAPTER 17. PROBLEM SET FOR FORTRAN

(1) Consider the following input patterns. Check what will be the stored
values of the variables whose input formats are shown in the format col-
umn of the table. Use proper variables and output formats to display the
result.

Input pattern format


Column No.--> 1 2 3 4 5 6 7 8 9 10
(1) 1 2 3 I6
(2) 1 2 3 I10
(3) 4 4 4 I10
(4) 4 8 9 5 6 7 I3,I2

(2) Use different output field width I1-10 to check what is being outputted?
What will happen if I0 is used as output format?
(3) Provide input/output formats I (fraction) (say, I3.2) and see what hap-
pens.
(4) Use different data types of variables other than integer and try to use I
format for input/output along with some values as shown.

25. Write programs in FORTRAN for the following:

(a) To find the sum of the digits of a given unsigned integer.


(b) To write a given unsigned integer less than 100 in words.
(c) To merge two sorted sequences of unequal length.
(d) To find the HCF of n given unsigned integers.
Z b
(e) To evaluate f (x)dx by using composite Simpson’s 31 rd rule.
a
(f) To solve an equation: f (x) = 0 by using method of bisection.
(g) To fit a polynomial y = a0 + a1 x + a2 x2 + · · · + an xn to the observed
value (xi, yi ), i = 1, 2, · · · , m, m ≥ n.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 275

26. Consider the following input data, input format and output format.
Input Data Input Format Output Format
12345E-2 E9.2 E9.3
What will be the content of the variable and what will be the output?
27. The following 3 lines of data are given for a FORTRAN program.
1234567890 1234567890 12345 ← Col. No.
11111 22.2 3333333
44444 55.5 6666666
77777 88.8 9999999
Find the values assigned to the variables in each of the following cases:
using the same format for output also (include carriage control character
‘1x’) at the beginning of each format spaces for output.
28. The most fundamental operation on an array is reading and writing the ele-
ments. You can do this by using the FORTRAN DO statement or the imple-
mented DO statement i.e., using parenthesized read, write.
Example
READ(*, A(I), (I = 1, 3)).
Write a FORTRAN program that will read an one dimensional array and
print it in the reverse order.
Example:
The array [1 5 2 3] should be printed as [3 2 5 1].
29. Write a FORTRAN program to read the name of students in a class and print
them according to a given format. Assume no name exceeds 24 characters
and a variable can refer to character string having at most 4 characters.
Chapter 18
PROBLEM SET FOR C

Implement the following program using C.

1. Implement the following C programs

(1) Write a smallest valid C program.


(2) Write a C program which will add two integer literal and the output
stored in a variable.
(3) Write a C program which will print the results of an addition of two
integers. Also print the input numbers with proper messages.
(4) Write a C program which will accept n real/integer numbers through
terminal with the proper messages and add those numbers and print the
sum with proper message (assume n is defined in the program, don’t have
to read this n).
(5) Write all possible C programs which will accept n numbers through
terminal and stored in an 1-D array. Sum those numbers in a variable and
print the output with proper messages.
[Note: Use different kinds of loop, increments/decrements, etc.]
(6) Repeat the above problem (5) where inputs are stored in a file and also
print the input sequence and results in an output file.
(7) A school/college administrator decided that the computerization of stu-
dents information well be easier to store and retrieve information from the
application form. The administrator wants to store, the following informa-
tion for a student such as (1) roll number, (2) name, (3) father’s name (4)

277
278 CHAPTER 18. PROBLEM SET FOR C

address, (5) date of birth, (6) Marks of paper1, (7) Marks of paper2, (8)
Marks of paper3, ... ,etc.
You are required to create a data structure and insertion program. Also
take care that a student may join in the class at any day in the session.
(8) Read 10 numbers and form a singly and doubly link list.

2. Write a program in C which will read a piece of text and perform the fol-
lowing actions for beautifying it.

(1) It will insert fixed left and right margins through the text, breaking a
word into two parts, if necessary, with a hyphen after the first half of the
word.
Example:
If the word ′ necessary′ is broken as ′nec′ and ′ essary′, then on line will
contain ′ nec−′ and the succeeding line will contain ′ essary′ .
(2) Assuming the original text to contain a preceding blank at the begin-
ning of each paragraph, the program should replace the blank with a tab.
(3) Assuming the text to contain no heading, the program should insert an
arbitrary heading on top.
(4) The program should be able to sense the end of a page of text (assuming
66 lines per page) and should accordingly insert a page number at the end
of a page which should in turn be centered.
(5) The program should insert sufficient blank lines at the beginning of a
page.

3. In the word of propositions, any statement in English about something is


a proposition, e.g. “The flower is beautiful”. This proposition may be true
or false, depending on the appearance of the flower. In propositional logic,
these propositions are replaced by simple symbols such as p or q. Proposi-
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 279

tional logic also contains certain logical operators such as ∨ (or), ∧ (and)
and ’!’ (not). The significance of these operators are as described below:
Assuming two propositions p and q,
If p and q both are true, then p ∧ q is true, otherwise p ∧ q is f alse.
If p and q both are f alse, then p ∨ q is f alse, otherwise p ∨ q is true.
If p is true, then !p is f alse.
This can be extended to complex propositions too, e.g. if p is true and q
is f alse, then the complex proposition (p ∧ q)∨!q is true. Such a complex
propositions and logical operators is often called a propositional formula.
Write a program in C which will read in a propositional formula, say (p ∧
q) ∨ (!p ∧ q) and determine whether it is true or f alse.
4. Write a utility tail −n in C which accepts input from a text file (by default
stdin), selects the last n lines and displays them on stdout, by default.
5. A limited over cricket-match was held between two teams A and B in which
one of the two teams had won. The complete score-card of the two teams
id given. A detailed statistics of the individual batting performances of each
player of the two teams, who had batted in the match, is also given.
For each batsman, the statistics include: (1) individual score; (2) number of
singles, twos, fours and sixes taken; and (3) number of deliveries faced.
The best batsman is detected based on the following technique: Each bats-
man has a performance value associated with him, which is calculated as
follows. The following [(a) to (e)] are added up: (a) individual score mod
10; (b) number of ones ∗ 0.5; (c) number of twos ∗ 1.0; (d) number of fours
∗ 2.0; and (e) number of sixes ∗ 3.0.
This sum is then divided by the number of deliveries faced. The quotient
thus obtained (taken upto two places after decimal point) gives the perfor-
280 CHAPTER 18. PROBLEM SET FOR C

mance value. The batsman with highest performance value is the best one.
Tie cases need not be considered.
The organizers of the cricket match have requested us to find the best bats-
man and his team through computer processing using the above selection
criteria. Could you help us out by writing a program in C which will do the
job?
6. A common encryption algorithm works in the following manner:
The given set of n characters in a word is converted to lowercase and any
special character (any character other than the ordinary alphabets and digits)
in the word is removed to get the encrypted form. The word is then scram-
bled by exchanging the ith character with the (word length − i)th character.
Implement a password check program in C using such encryption.
7. Write a program in C which reads a C program from a file, removes the
commented lines and extra white spaces and writes on a new file.
8. One way to model the managerial decision making process is with the help
of a binary trees which we call a decision tree. Suppose T is a decision tree.
Then each internal node X in T corresponds to a decision with a yes/no
option. If the decision taken is yes, then the left link of X is to be followed,
while if the decision taken to no, the right link of X is to be followed. The
external or terminal nodes of T correspond to actions. Each decision has an
associated cost, and each action also has an associated cost. Let X be an
external node of T. Then the weight Wx of X is given by AIx + BEx where A
and B are positive parameters (real numbers), Ix is the sum of the decision
costs of all internal nodes from the root to the father of X, while Ex is the
action cost of X. You are supplied A and B, and a pointer to the root of the
decision tree and you are required to list out all actions (i.e., external nodes)
and their weights.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 281

9. Let S be the following sequence of positive integers (not necessarily all


distinct) 12, 16, 5, 13, 12, 4, 17, 8, 14, 6 and T be the following sequence
16, 13, 12, 8, 6. Then T forms a subsequence of S, i.e., items in T are given
as same left to right order as in S, but they are not necessary consecutive
items in S. Also each item in T (except the file is strictly smaller than the
one immediately to the left of it in T, and T is the longest such subsequence
we can get from S. We say that T is the longest decreasing subsequence
in S. Note that S may have more than one longest decreasing subsequence.
You are supplied a positive integer n and a sequence of n positive integers.
Find all the largest decreasing subsequences of the given sequence.
10. Write the following program that includes a recursive function.

(a) The Legendere polynomial can be defined as


P0 = 1, P1 = x, Pn = [(2n − 1)/n]Pn−1 − [(n − 1)/n]Pn−2
where, n = 2, 3, 4, · · · and x is any floating point number between −1 and
1. Generate the first n Legendere Polynomials. Let the values on n and x
be input parameters.
(b) Determine the cumulative sum (or product) of n floating point num-
bers. Input a new number during each call to the recursive function.

11. Write a program in C to merge two linked lists such that elements of the two
lists alternate in the new list. Do not create a new list but implement using
pointer changes in the old lists.
12. Write a function that will scan a character string passed as an argument and
convert all lower case characters into their upper case equivalents. [Note:
upper case letters in the input string does not convert into lower case letters.]
13. Write a program that will encode a line of text.
Algorithm for encoding
282 CHAPTER 18. PROBLEM SET FOR C

(1) Convert each character (including blank space) to its ASCII value (say,
a).
(2) Generate a positive random integer (say, r). Add this integer to the
ASCII equivalent of each character (i.e. s = a + r). The same random
integer (r) will be used for the entire line of text.
(3) Let n1 = Minimum {ASCII codes} and n2 = Maximum {ASCII codes}.
If the number obtained in step 2 (i.e. s > n2 ) then the remainder, rem =
s − k × n2 , where k = largest possible multiplier such that rem > 0, new =
rem+n1 and n1 ≤ new ≤ n2 . So, new will be always represent some ASCII
character.
(4) Print the characters that corresponds to the encoded ASCII values.

Write another program which is reversed when decoding a line of text,


where the same random number is used in decoding as was used in en-
coding.
14. Write a function using pointers to add two matrices where the elements are
real or complex number and to return the resultant matrix to the calling
function.
15. Write a function (using pointers) with two arguments one is a character
string and another is a character so that it deletes all occurrences of this
character in the string. The function should return the corrected string with
no holes.
16. Write a program to read characters from a file and type them on the terminal
screen.
17. Write a program which will do the following:
(a) To create a file,
(b) Read a string from the terminal, and
(c) Store the string in the file.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 283

Write another program to open this file and read that stored string for dis-
play.
18. Write a program and test the following: Try to set the read-only protection
mode on a file, then opening the file with an access mode of read or write.
19. Write a program to implement the UNIX command tail − n, where n is the
number of lines from the end of the file to be copied to stdout.
20. Write a program to read a list of names (each name in one line) from stan-
dard input, and write these names spelled in reverse order to standard output.
Use I/O redirection and pipes to do the following:

(a) Input a list of names that are typed from the keyboard and write them
out, reversed, to a file called fileI.
(b) Read names from fileI; then print out in reversed order to another file
fileO.
(c) Read names from fileO, reverse them and sort the resulting list using
sort.

21. Write a program to create name and address file (as given below) that is
strictly a stream of bytes (no delimiters, counts, or other information to dis-
tinguish fields and records).
Algorithm

begin
get output file name and open it with the name OUTPUT
get LAST name as input
while (LAST name has a length > 0)
get FIRSTname, ADDRESS, CITY, STATE and PIN as input
write LAST to the file OUTPUT
write FIRST to the file OUTPUT
write ADDRESS to the file OUTPUT
284 CHAPTER 18. PROBLEM SET FOR C

write CITY to the file OUTPUT


write STATE to the file OUTPUT
write PIN to the file OUTPUT
get LAST name as input
end while
close OUTPUT
end

Also do the following:

(a) Write a write program for this algorithm so that it uses delimiters as
field separators.
(b) Write a program to read the above output file.
(c) Write a program to store five records per block in a file.
(d) Write a program to read the above blocked output file.

22. Write a program to create name and address file using fixed length record.
23. Write a program to read a file, record by record, displaying the fields from
each of the records on the screen.
24. Write a program to search sequentially through a file for a record with a
specified key.
25. Write a program to open or create a fixed length record file for updating.
Records may be added or changed. Records to be changed must be accessed
by relative record number (RRN).
26. Write a program so that it can delete and add records to a fixed-length record
file using a replacement procedure.
27. Write a program so that it can delete and add records to a variable-length
record file using a replacement procedure.
28. Design and implement a program to do the following:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 285

(a) Examine the contents of two sorted files f1 and f2 .


(b) Produce a third file f3 containing a copy of records from the original
two files that are identical.
(c) Produce a fourth file f4 that contains all records from these two files
that are not identical.

29. A file contains the following information about students residing in a hostel:
Number of meals taken
during the month
Roll No. Name Course Breakfast Lunch Dinner
*** *** *** ** ** **
Write a program (using dynamic memory allocation) in C which will print
the mess-bill for each course sorted in the roll number-wise. The charges for
breakfast, lunch and dinner is to be input through keyboard.
30. Write a program to search a key in a B-tree.
31. Write an interactive program that allows user to find, insert and delete keys
from a B-tree.
32. Write a B-tree program for string keys (not only single characters).
33. Write a program that builds a B-tree index for a data file in which records
contain more information than just a key.
34. Write a program to compare two binary search trees using recursion.
35. Write a program that accepts a file of strings as input. The input file should
be stored in an ascending order. Your program should use this input file to
build a sequence set with the following characters:

• The strings are stored in 15-byte records;


• A sequence set block is 128 bytes long;
• Sequence set blocks are doubly linked;
286 CHAPTER 18. PROBLEM SET FOR C

• The first block in the output file is a header block containing, among other
things, a reference to the RRN (Relative Record Number) of the first block
in the sequence set;
• Sequence set blocks are loaded where the blocks are as full as possible;
and
• Sequence set blocks contain other fields (other than the actual records
containing the strings) as needed.

36. Write an update program that accepts strings input from the keyboard, along
with an instruction either to search, add or delete the string from the se-
quence set. The program should have the following characteristics:

• String in the sequence set must be kept in order;


• Searching may be either successful successful or unsuccessful;
• A string should not be added if the search is successful;
• Blocks in the sequence set should never be allowed to be less than half
full, and
• Splitting, redistribution and concatenation operations should be written as
separate procedures.
Chapter 19
PROGRAMMING PROBLEMS FOR SYSTEM
SOFTWARE

Implement the following System software problems.

1. Write a preprocessor in C to translate programs written in language COMPO


to equivalent programs in C. COMPO deals only with complex variables
i.e., variables which can store complex numbers. A complex variable A rep-
resents a pair of integers, say, A.r is called the real part of the variable A and
A.i is the imaginary part. The statements allowed in COMPO are as follows:
(1) INPUT A : to input the pair of integers of the complex variables A
from terminal.
(2) PRINT A : to output the pair of integers of the complex variable A
into terminal.
(3) A := B|C : to add the two complex variables B and C and assign the
result to A. The operator ′ |′ assigns (B.r +C.r) to A.r and (B.i +C.i) to
A.i.
(4) A := B ∗C : to multiply the two complex variables B and C, and assign
the result to A. The operator ′ ∗′ assigns.
B.r ∗C.r − B.i ∗C.i to A.r and B.r ∗C.i + B.i ∗C.r to A.i.
(5) END : to indicate END of the program.
Assume that
(a) Every line of COMPO program contains a single statement.
(b) Variable names start with an alphabet and contains atmost 5 alphanu-
meric characters.
(c) Your preprocessor stops execution whenever it detects an error in input.
Clearly mention any other reasonable assumptions you make.

287
288 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

2. A program text beautifier for Pascal programs is to be designed which takes


in an arbitrary Pascal source file and produces. It should have the following
features:
(1) There should be a change in line after every semicolon(;).
(2) Keywords like var, begin, end, repeat, until, if, then, else, const must be
written in separate lines.
(3) The begin and corresponding end must be aligned. The matter in be-
tween must be indented.
(4) The if, then and else of a single if statement must be aligned and the
inner matter indented.
(5) The repeat and until must be aligned and the matter inside these state-
ments indented.
(6) If the while and do are in separate lines, then they must be aligned (or
they may also be in the same line). The matter relating to the while
statement must be indented.
(7) Constant and variable declarations must be indented below const and
var keywords respectively.
(8) The right margin must not cross the screen. Lines must be broken and
proper indentation maintained. Right margin is adjustable (as parame-
ter).
3. Write a program which takes another program as input and removes all com-
ments from it. The output program should maintain the same indentation as
input.
4. Write a program which will find all lines containing a specified string of
characters in a text file. Print out line numbers and the contents of lines.
5. Assume a machine that has a single register with the following instructions
as described.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 289

Instruction Description
LD A places operand A into the register.
ST A places the contents of a register into a variable A.
AD A adds the contents of variable A to the register.
SB A subtract the contents of variable A from the register.
ML A multiplies the contents of register by variable A.
DV A divides the contents of register by variable A.
Write a program that accepts a postfix expression containing single letter
operand and the operators +, −, ∗, /. And it prints a sequence of instructions
to evaluate the expression and leave the result in the register. Use variable
of the form TEMPn as temporary variable.
Example:
The postfix expression ABC ∗ +DE − / of {A + (B ∗C)}/{(D − E)} should
yield the following print out.
LD B
ML C
SD TEMP1
LD A
AD TEMP2
ST TEMP2
LD D
SB E
ST TEMP3
LD TEMP2
DV TEMP3
ST TEMP4
290 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

6. Write a program for the design of a graphics driver either for IBM color
display or some other suitable bit map display. This graphics driver routine
accepts commands for set and clear each specified pixels. Also user pro-
grams interface to the driver and writing commands to it.
7. [Long-Term Scheduling] Assume that a given group of jobs are on a disk
that updates with minimal line printer output. We could define a scheduling
metric S(T ) as follows:
10000
R =
10C + M
S(T ) = R(1 + T − A)k = R(T − Q)k
where,
C = Estimated execution time, ms,
M = Estimated memory requirement, bytes,
T = Current system clock time,
A = System clock time at which process arrives,
k = Relative importance of waiting time,
R = Priority change ratio based on estimated, CPU usage
and estimated memory required, and
Q = Constant, determined by time at which process ar-
rives.
Generally, the size of the job into memory and CPU are not separate. Now
10000
R may be redefined as R = , where x is a speak of a combined size
x
value, instead of individual C and M values.
Implement the above scheduling algorithm and tests it for various values of
k and various distributions of x (random). There will be one set of output for
each value of k, giving the average waiting time as a function of x.
In real-life situations, random quantities often behave in a normal fashion.
The normally distributed random number generation procedure is given be-
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 291

low.
Compute a sequence of normally distributed random number for G by sum-
ming 12 consecutive uniformly distributed random number over [0, 1] con-
vert these values for G to scheduling size values x by using x = (10000 +
W G) rounded to a multiple of 10000, where W is a weight function which
establishes the distribution parameters. Set up your program to run for speci-
fied input values of k and W . You should experiment with the values k = 0.5,
1 and 2, and W = 5000, 10000 and 15000.
Another important factor is arrival times of the jobs. For this program as-
sume a very simple case. The system starts at time 0 with 10 jobs in the
queue, and a new job arrives every i milliseconds. The system selects the
first job at time i and then selects subsequent jobs after an interval i defined
by
x + 6(15000 −W )
i= ms
10000
where, x is the scheduling size value of the last job selected.
Your first task for each value of k and W will be to adjust i to get a steady
state - a state in which the number of jobs in the queue remains approx-
imately constant. Keep printing the last 10 queue lengths and adjusting i
until this is achieved.
Once the steady state is achieved, start keeping statistics of average wait
time as a function x. The number of trials will depend on the speed of the
machine you are using - run each case for a reasonable time.
Plot the results. You need not use a computer plotting package, although
you certainly can if one is available and you know how to use it.
8. Implement a game called push and pull. The game starts with a number
(say, n), of bits in a central bit bucket. Each player also has his or her own
bit bucket (initially empty). A player is allowed to execute one of two com-
292 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

mands:
Push m : Move m bits for player’s bucket to central bucket.
Pull m : Move m bits from central bucket to player’s bucket.
In most versions of the game, the number of bits moved by one command is
limited to some maximum (say, ‘M’). In any case, the number moved must
be limited to the number available - if ‘I’ say Push 7 and ‘I’ have only 5,
then 5 will be moved. The loser of the game is the player who takes the last
bit from the central bit bucket whose Pull command drops the number of
bits in the central bit bucket to 0. The winner of the game is the player who
executes the last Pull command before the loser executes the Pull command
that takes the last bit.
9. [Benchmark] Write a benchmark program that will evaluate the perfor-
mance of several computers to which you have access (perhaps some per-
sonal computers, a minicomputer, or a mainframe). With this benchmark,
determine the execution times for the following operations:
Integer : add, subtract, multiply and divide.
Floating point : add, subtract, multiply and divide.
When making your measurements be sure to eliminate the effects of your
measurement tool on the results.
Turn in the following: (1) your benchmark program, (2) the timing measure-
ments, and (3) an analysis of the result.
If possible, your analysis should include a comparison between the observed
timings and the timings given by the manufacturer of the processor.
10. [Loading, Linking and Relocation] Write a relocating linkage editor for a
hypothetical machine whose compilers and assemblers generate the follow-
ing form of object module:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 293

Module name 8 characters.


Number of entry points 3 digit integer.
First entry point name 8 characters.
Relative displacement of
First entry point 5 digit integer.
Second entry point name 8 characters.
Relative displacement of second entry point 5 digit integer.
(same for remaining entry points)
Number of externals 3 digit integer.
First external name 8 characters.
Relative displacement of first external point 5 digit integer.
First reference to this external
second external name 8 characters.
Relative displacement of first reference to this external 5 digit integer.
(same for remaining external references)
Number of instructions 5 digit integer.
First instruction address type : 1 character.
r : relocate
a : absolute
e : external
s : skip storage
Op code, registers, etc. 3 digits.
Address 5 digits.
(same for remaining instructions)
Each of these components is on one line, separate by a space.
For example, an external reference would be of the form:
294 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

xxxxxxxx ddddd
TANGENT 00104
and an instruction would be of the form
x ddd ddddd
e 103 23456
where, x = alphabet and d = digit.
The input to the linkage editor consists of two lines followed by a sequence
of object modules:
Number of modules 3 digit integer.
Starting point for execution 5 digit integer.
Module 1 (as described)
Module 2 (as described) etc.
Output of your linkage editor should be a linked relocatable load module,
ready to be loaded into main memory. Each line in this module will simply
be
Address type 1 character.
r : relocatable
a : absolute
Instruction 8 digit integer.
Note that during linkages editing there could be errors. In this case no load
module would be generated.
11. An MS-DOS computer uses a FAT to keep track of disk blocks. Compare its
average performance by simulation to UNIX with respect to doing random
seeks on long files if (a) The FAT is always on disk. (b) The FAT is always
in memory.
12. [Memory management] Compare various memory management techniques
with the help of simulation technique with respect to user satisfaction (in
terms of waiting time) and system utilization.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 295

Input to this program will be job descriptors produced by a random genera-


tor. Each such descriptor has a job identifier and a set of job parameters, in
the following format:
Id Arrive MemTimeReq MemReqd
where,
Id : Job identifier.
Arrive : Arrival time, relative to the arrival of the last job.
MemTimeReq : Time that the job is in memory.
MemReqd : Amount of memory required, in KBytes.
Write a simulation program to simulate the performance of various mem-
ory management routines (i.e., memory manager) operating with this job
stream. These memory managers have a variable number of variable size,
non-movable regions; they use a highest response ratio next (HRRN) ser-
vice algorithm. The only variation among the managers is their placement
algorithm: best fit, worst fit, first fit, next fit and a comparison standard. The
comparison standard shows what would happen if regions were movable and
memory could be instantaneously burped (i.e., used memory backed to the
memory manager) at the termination of each job.
One output for each placement algorithm will be a partial trace to show that
the system is working properly. At an arbitrary selected point in the simu-
lation, trace 10 jobs (say) as they are taken from the wait queue and loaded
into memory. Show the wait queue just prior to each selection, and the mem-
ory map before and after the selected job is loaded.
The other output for each algorithm will be a set of statistics gathered with
the simulation in steady state. The required statistics are minimum, maxi-
mum and average queue length; and memory utilized, and average wait time
as a function of memory required.
296 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

Run all simulations with the same set of data. [Hints: use a random number
generator which can be restarted with the same seed value or generate the
job stream once and store it on a file.]
Memory size should be a parameter which can be specified at the beginning
of the simulation. All job parameters should be normally distributed about
the centers of their respective ranges.
Arrive : 4 to 96 time units.
MemTimeReqd : 4 to 96 time units.
MemReqd : 4K to 60K bytes.
Select jobs form the wait queue on the Highest Response Ratio Next (HRRN)
basis, using
wait time
S(wait time) =
memory required
with a bypass three times and freeze restriction.
13. Design and implement a cross-assembler for the processing of Intel8086
assembly language.
14. Design and implement a text editor with minimum number of function so
that it can perform editing functions.
15. Tree structured directories are found in most operating systems. The purpose
of this assignment is to create a file system and the part of a command
interpreter which provides the user interface to that file system.
Let us consider the hierarchical directory structure for the implementation
of the file system. Directories will just be ordinary files and any directory
may contain file entries for files that are themselves directories.
Disk format: The disk may be considered to be a sequence of blocks of size
blksize numbered from 0 to (nblk − 1). Block 0 will contain a bit map with
one bit corresponding to each of the blocks on the disk, where bit = 1 means
the corresponding block on disk is currently not in use. When the disk is
initialized, all the bits, except the first two, are set to 1. Block i will contain
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 297

the root directory for the disk, sometimes referred to as a volume. During
initialization, the root directory is set to all null characters and whenever a
new directory is created, it is also set to all null characters.
Directory format: The directory will be filled with ndir directory entries.
Each entry will be a record that includes the following fields:
Name : 9 characters.
Type : 3 characters, type of file (directory or other).
Location : integer, starting block of the file.
Size : integer, number of blocks in the file.
File format: Each file will contain some number of bytes followed by a
CTRL-C, which signifies an end of file (EOF). Text files will contain lines
of characters; each will be followed by a carriage return. When a new file is
created, an EOF character is inserted in the first position of the file.
File names: Names of directories and other files are specified by giving the
entire path name followed by the file name:
filename :: = [path:]name
directoryname :: = [path:]name:
path :: = name:name:,,name
name :: = 1 to 9 characters
Verify that the implemented file management system operates correctly with
the following commands.
L : list root directory.
L filename : list text in a file.
L directoryname : list directory entries.
M filename, size : make a file of size number of blocks.
M directoryname : make a directory file.
D filename : delete the specified file.
D directoryname : delete the specified directory, if it is empty.
298 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

B : list the bit map.


A filename : append to a text file (command is terminated by
”//” in first two characters of a line).
C filename1, filename2 : copy file from 1 to 2 (create new file2 if file2
doesn’t exist).
Directory listings should have the following header : Directory name: (in-
cluding path if any)
Name Type Location Size
File listings have the following format:
File name: (including path if any)
Line #
00001 (line 1)
00002 (line 2)
EOF
The bit map should be listed as a series of 1s and 0s, with 32 bits per line.
The number of lines required will depend on the number of block allocated
to the disk. In case of a floppy, this should be an entire diskette.
The implemented program must check some of the error conditions as given
below:
DUPLICATE FILE/DIRECTORY NAME filename
INVALID COMMAND (just display the message; then continue)
INSUFFICIENT SPACE
DIRECTORY EMPTY
16. Write a program for the implementation of an output spooler from each
output device after random delays. The output from each process should
be simple, consecutively numbered lines containing the process id so that
it can easily check the operation of the spooler. The processes should call
this pseudodevice driver rather than calling the standard output device (that
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 299

is, you should replace print, write(..), writeln(..), scan(..), scanf(..) in the
processes).
Write a program that randomly selects one of several different procedures
that in turn call sp − write(..) in a system even if it is not a multiprocessing
system. As above have each of the procedures send consecutively numbered
lines to the spooler to verify its operation.
In each case, check whether all the files are printed correctly with no missing
or added lines and also each file deleted after processing.
17. [Lexical analyzer] Lexical analyzer or scanner which is the interface be-
tween the compiler and the source program in high level language. Sep-
arates characters of the source program into groups that logically belong
together, these groups are valid tokens. In case of an ideal lexical analyzer
the usual tokens are identifiers, operator symbols, punctuation symbols etc.
The output of the lexical analyzer is a stream of tokens which is passed to
the next phase which is syntax analyzer or parser.
Let us consider a grammar whose
Reserved words : { begin, end, goto, if, then, else, while, do, or, and, not }.
Operator symbols : {+, −, ∗, /, :=, <, >, >=, <=, =, <>}.
Punctuation symbols : {; ( ) blank}
Sets: Letter, L ={A..Z,a..z} and Digit, D= {0..9},
Production rules : A subset of Pascal grammar as given below :
1. <Statement part> ::= <Compound Statement>
2. <Compound statement> ::= begin<L-Statement>end.
3. <L-statement> ::= <L-Statement> <Statement>; |
<Statement>;|;
300 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

4. <Statement> ::= <unlabelledStatement>|


label <unlabelled Statement>
5. <Unlabelled statement> ::= <Simple Statement> | <Structured Statement>
6. <Simple statement> ::= <AssignmentStatement> |
<Procedure Statement> | <Goto Statement>
7. <Assignment statement> ::= identifier:=<expression>
8. <Expression> ::= <Simple expression> |
<Simple expression>
<Relational operator>
<Simple expression>
9. <Relational operator> ::= = | < | > | <= | >= | <>
10. <Simple expression> ::= <Simple expression> <add-operator><term>
11. <Add-operator> ::= + | - | or
12. <Term> ::= <Term> <mul operator> <factor> | <factor>
13. <Mul operator> ::= ∗ | / | and
14. <Factor> ::= <identifier> | integer | <expression> |
not <factor>
15. <Procedure statement> ::= call id | call id (<Lidn>)
16. <Lidn> ::= <Lidn>, id | id
17. <Goto statement> ::= goto integer
18. <Structure statement> ::= <CompoundStatement> | <if Statement> |
<while Statement>
19. <If statement> ::= if <expression> then <Statement> |
if <expression> then <Statement>
else <Statement>
20. <While statement> ::= while <expression> do
<Statement>
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 301

Draw the deterministic finite automata (DFD) for the design of a lexical an-
alyzer. Write a program for the implementation of the lexical analyzer.
18. Implement the following efficient algorithm developed by Warshall for the
computation of the transitive closure: B+ = B + BB + · · · + B!n for the
Boolean matrix B.
Algorithm
(1) set a new matrix A = B,
(2) set i := 1,
(3) for all j,
if A[ j, i] = 1 then
for k = 1, 2, · · · , n
set A[ j, k] := A[ j, k] + A[i, k].
(4) add 1 to i,
(5) if i ≤ n then goto step 3;
Otherwise stop.
19. An operator precedence grammar
(1) E → E + T | T
(2) T → T ∗ F | F
(3) F → (E) | id
provides the following operator precedence relations table and its operator
precedence functions.
302 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

Precedence Relation
+ ∗ ( ) id $
+.><.<..><..>
∗ .>.><..><..>
( <.<.<.= <.
) .>.> .> .>
id . > . > .> .>
$ <.<.<. <.
Precedence Function
+ ∗ ( ) id $
f 2 4044 0
g 1 3505 0
Write a program for the implementation of the computation of operator
precedence function form the given operator precedence relation table.
20. Design and implement an interpreter for the subset of Basic/Pascal lan-
guage.
21. Implement the following method described in the example for the computa-
tion of operator precedence functions.
Example:
A simple grammar and its precedence Table is given below:
Grammar
Z ::= b M b
M ::= (L | a
L ::= M a)
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 303

Precedence Table (T)


zb ML a ( )
z .. . . . . .
b . . = . <<.
M. =. . =. .
L . >. . >. .
a . >. . >. =
( . . < =<<.
) . >. . >. .
Construct the G and L matrix using the following definition and the prece-
dence Table
 (T):
 1 if T [i, j] =′ >′ or ′ =′
G[i, j] = and
 0 otherwise.

 1 if T [i, j] =′ <′ or ′ =′
L[i, j] =
 0 otherwise.
So G and L will be as given below:
G= 0 0 0 0 0 0 0 LT = 0 0 0 0 0 0 0
0010000 0010110
0100100 0100100
0100100 0000000
0100101 0000001
0001000 0011110
0100100 0000000
 
0G
Construct: B =  ,
L0
Compute: B∗ = I + B+ where, B+ = B + B2 + · · · + B2n and
304 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

 1 if i = j
I = Identity matrix of size 2n × 2n, that is, I[i, j] =
 0 otherwise.
Here,
B∗ = 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0100010 0011000
0110010 0111100
0111010 0111100
0110110 0111101
0000010 0001000
0110011 0111100

0000000 1000000
0110010 0111100
0100010 0011000
0000010 0001000
0110010 0111100
0100010 0011010
0110110 0111101
Precedence functions f , g are as follows.
zbML a ( )
f 1 4 7 8 10 2 8
g17 4 2 7 59
2n
where, f [i] = ∑ B∗[i, j], for i = 1, 2, · · · , n
j=1
2n
g[i] = ∑ B∗[n + i, j], for i = 1, 2, · · · , n.
j=1
Illustration
Here n = 7
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 305

f (z) = f (1) = B∗ [1, 1] + B∗[1, 2] + B∗[1, 3] + B∗[1, 4] + B∗[1, 5] + B∗[1, 6] + B∗[1, 7]

+ B∗[1, 8] + B∗[1, 9] + B∗[1, 10] + B∗[1, 11] + B∗[1, 12] + B∗[1, 13] + B∗[1, 14]

= 1+0+0+0+0+0+0+0+0+0+0+0+0+0= 1

f (b) = f (2) = B∗ [2, 1] + B∗[2, 2] + B∗[2, 3] + B∗[2, 4] + B∗[2, 5] + B∗[2, 6] + B∗[2, 7]

+ B∗[2, 8] + B∗[2, 9] + B∗[2, 10] + B∗[2, 11] + B∗[2, 12] + B∗[2, 13] + B∗[2, 14]

= 0+1+0+0+0+1+0+0+0+1+1+0+0+0= 4

f (M) = f (3) = B∗ [3, 1] + B∗[3, 2] + B∗[3, 3] + B∗[3, 4] + B∗[3, 5] + B∗[3, 6] + B∗[3, 7]

+ B∗[3, 8] + B∗[3, 9] + B∗[3, 10] + B∗[3, 11] + B∗[3, 12] + B∗[3, 13] + B∗[3, 14]

= 0+1+1+0+0+1+0+0+1+1+1+1+0+0= 7

f (L) = f (4) = B∗ [4, 1] + B∗[4, 2] + B∗[4, 3] + B∗[4, 4] + B∗[4, 5] + B∗[4, 6] + B∗[4, 7]

+ B∗[4, 8] + B∗[4, 9] + B∗[4, 10] + B∗[4, 11] + B∗[4, 12] + B∗[4, 13] + B∗[4, 14]

= 0+1+1+1+0+1+0+0+1+1+1+1+0+0= 8

f (a) = f (5) = B∗ [5, 1] + B∗[5, 2] + B∗[5, 3] + B∗[5, 4] + B∗[5, 5] + B∗[5, 6] + B∗[5, 7]

+ B∗[5, 8] + B∗[5, 9] + B∗[5, 10] + B∗[5, 11] + B∗[5, 12] + B∗[5, 13] + B∗[5, 14]

= 0+1+1+0+1+1+0+0+1+1+1+1+0+1= 9

f (() = f (6) = B∗ [6, 1] + B∗[6, 2] + B∗[6, 3] + B∗[6, 4] + B∗[6, 5] + B∗[6, 6] + B∗[6, 7]

+ B∗[6, 8] + B∗[6, 9] + B∗[6, 10] + B∗[6, 11] + B∗[6, 12] + B∗[6, 13] + B∗[6, 14]

= 0+0+0+0+0+1+0+0+0+0+1+0+0+0= 2

f ()) = f (7) = B∗ [7, 1] + B∗[7, 2] + B∗[7, 3] + B∗[7, 4] + B∗[7, 5] + B∗[7, 6] + B∗[7, 7]

+ B∗[7, 8] + B∗[7, 9] + B∗[7, 10] + B∗[7, 11] + B∗[7, 12] + B∗[7, 13] + B∗[7, 14]

= 0+1+1+0+0+1+1+0+1+1+1+1+0+0= 8

Similarly,

g(z) = g(1) = B∗ [8, 1] + B∗[8, 2] + B∗[8, 3] + B∗[8, 4] + B∗[8, 5] + B∗[8, 6] + B∗[8, 7]

+ B∗[8, 8] + B∗[8, 9] + B∗[8, 10] + B∗[8, 11] + B∗[8, 12] + B∗[8, 13] + B∗[8, 14]

= 0+0+0+0+0+0+0+1+0+0+0+0+0+0= 1

g(b) = g(2) = B∗ [9, 1] + B∗[9, 2] + B∗[9, 3] + B∗[9, 4] + B∗[9, 5] + B∗[9, 6] + B∗[9, 7]

+ B∗[9, 8] + B∗[9, 9] + B∗[9, 10] + B∗[9, 11] + B∗[9, 12] + B∗[9, 13] + B∗[9, 14]
306 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE

= 0+1+1+0+0+1+0+0+1+1+1+1+0+0= 7
..
.

22. Let us consider the following LR grammar


(1) E → E + T
(2) E → T
(3) T → T ∗ F
(4) T → F
(5) F → (E)
(6) F → id
This grammar provides the following parsing table. It consists of two parts
(1) action table and (2) goto table.
State Action Goto
id + * ( ) $ ET F
0 s5 s4 12 3
1 s6 acc
2 r2 s7 r2 r2
3 r4 r4 r4 r4
4 s5 s4 82 3
5 r6 r6 r6 r6
6 s5 s4 9 3
7 s5 s4 10
8 s6 s11
9 r1 s7 r1 r1
10 r3 r3 r3 r3
11 r5 r5 r5 r5
Action table entries are single character and goto table contains numerical
entries. Action table entries are as follows:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 307

s : Shift current input element to the top of the stack.


r : Reduce by the production rule whose number is the correspond-
ing entry of goto table.
acc : Accept i.e. syntactically correct.
e or blank : Error whose number is the corresponding entry of goto table.
Example:
Let us consider the following input id ∗ id + id for parsing using the above
table.
Stack Input
(1) 0 id ∗ id + id$
(2) 0 id 5 ∗id + id$
(3) 0 F 3 ∗id + id$
(4) 0 T 2 ∗id + id$
(5) 0 T 2 ∗ 7 id + id$
(6) 0 T 2 ∗ 7 id 5 +id$
(7) 0 T 2 ∗ 7 F 10 +id$
(8) 0 T 2 +id$
(9) 0 E 1 +id$
(10) 0 E 1 + 6 id$
(11) 0 E 1 + 6 id 5 $
(12) 0 E 1 + 6 F 3 $
(13) 0 E 1 + 6 T 9 $
(14) 0 E 1 $
Implement the driver routine for the LR parser.
Chapter 20
PRACTICE PROBLEMS FOR DOS

DOS is the Disk Operating System for Personal computers. A set of simple
problem related to DOS commands are given below:

1. Disk and floppy file management varies from one operating system to other.
Most of the modern operating system (i.e. DOS, Unix etc.) maintains hier-
archical file structure (e.g. like a family tree structure or forest). The root
directory is created and owned by the operating system itself. But the rest
of the directories which are sub-directories of the root directory are created
by users. The following gives you a hierarchical structure to be created in
floppy disk.
ROOT
@
@
@
@
@
@@

PERSONAL OFFICIAL

Given the command(s) by which you can create above sub-directories.


2. Create two more sub-directories both named ACCOUNT under PERSONAL
and OFFICIAL (both the department may maintain separate account) in
above Q.1. The final structure will be

309
310 CHAPTER 20. PRACTICE PROBLEMS FOR DOS

ROOT
@
@
@
@
@
@@
PERSONAL OFFICIAL

ACCOUNT ACCOUNT

Give the command(s) by which you can do this.


3. So far we have created four empty sub-directories (directories are logical
separation in the disk to hold files and, if necessary, further sub-directories).
To create a file (not directory) under PERSONAL named LETTER.TEX
which will contain the following text.

Dear Sir,

Please find an application for the ...

Create this file.


4. One way to create small text files through your terminal (as in Q.3). Now
the current directory structure will now be as follows:
ROOT
@
@
@
@
@
@@
PERSONAL OFFICIAL
@
@
@@
ACCOUNT Letter.tex ACCOUNT
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 311

So a directory is a collection of sub-directories and files. We now want to


copy the file Letter.tex to a file under ROOT. Given the command(s) to do it.
Draw the final diagram.
5. Remember at any point of time you can only belong to one directory as you
personally belong to any one place at any point of time. When you switch
on the machine you belong to the ROOT directory. So your default directory
is ROOT. We sometimes term this directory as working directory or current
directory. If you desire to work in a directory other than ROOT, you have
to tell DOS through DOS command(s). Let us agree to work in ACCOUNT
directory under OFFICIAL. Give the command(s) to accomplish this.
6. Give a command for a ditto copy of Letter.tex in this current directory with
the name Letter1.tex. Draw the final diagram.
7. Change the name Letter1.tex to Letter.tex. Now the files with same name
may exist in different directories. Is it possible to have two files with same
name in one directory? The above fact holds good for directories too i.e.,
there may be more than one sub-directory with same name under different
directory. Note that directories are also files of special type only.
8. It is not true that to work with a file under OFFICIAL, you have to change
your current directory to OFFICIAL. In fact if you know the path (i.e., mile-
stones) you can easily look for files in other directories. Assume you are in
OFFICIAL, you want to see the content of Letter.tex file in PERSONAL.
Give necessary commands.
9. Being within a directory, you can execute commands which involve two
other directories. Explain the following command,
COPY C:\XYZ.DAT A:\OFFICIAL\XYZ.DAT.
312 CHAPTER 20. PRACTICE PROBLEMS FOR DOS

10. Assume you are in OFFICIAL directory. If the command cd .. is used what
will be the current directory? If cd\ is used what will be the current direc-
tory?
11. Factory made floppy diskette may be used by different operating system
and is different machines. Floppy diskette that is available in market has
only tracks. Operating system (OS) divides it into sectors called soft sector,
soft sectoring can be changed by other OS besides checking materials of
the medium. This process is more well-known as “formatting”. What is the
command to do this soft sectoring or formatting?
12. In DOS commands set, two special symbols ′∗′ and ′ ?′ are used with special
meaning. ′ ∗′ means any sequence of zero or more characters and ′?′ means
zero or one character. These two characters are known as wild card symbol.
Assume a directory that has the following files:
A, A.DAT, AA.DAT, B.EXE, CIVIL.EXE,
BB.EXE, BC.EXE, D, DCB.EXE, ASIT.DBF,
PAY.DBF, TAKE.ME, READ.ME, KILL.ME.
Which filenames will be displayed in each of the following commands.
(a) DIR ∗.∗
(b) DIR/P
(c) DIR/W
(d) DIR ∗.ME
(e) DIR ?.
(f) DIR B?.EXE
(g) DIR/P A∗.∗
13. What will the command ’DIR > PRN’ do?
14. What will the command ’C:’ do ?
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 313

15. The command


FORMAT A:
and
DEL A:∗.∗
effectively does the same thing. Explain.
16. If you want to delete the directory PERSONAL (in Q. 4) how will you do
it?
17. Can a sub-directory be full, when leaving some space in other directory?
Explain.
18. How the commands
copy A:∗.∗ B:∗.∗
and
diskcopy A: B:
differ?
19. What is meant by the internal command and the external command?
20. What is meant by a version of an Operating System? What is upward com-
patibility?
21. What is the difference between the following commands
(a) cd personal,
and
(b) cd\ personal.
22. What is the difference between the following commands
(a) copy A:XYZ.DAT C:
and
(b) copy A:xyz.dat C:\.
314 CHAPTER 20. PRACTICE PROBLEMS FOR DOS

23. What the command


DIR | SORT
will do?
24. Explain with a file structure the following commands.
cd ..\..
and
cd ..\personal.
25. What the following commands will do?
(1) copy xyz.dat ..\T\
(2) copy xyz.dat ..\T
26. Decide true or false
(a) Diskcopy does not format the target diskette if the diskette is al-
ready formatted.
(b) Recover is a DOS command for backing up hard disk from
floppy.
(c) del command can delete a subdirectory provided the path is prop-
erly defined for the subdirectory.
(d) Format A:/S is the only way to make a diskette bootable.
(e) If a set of file is deleted using del ∗.∗ the file can not be recovered.
(f) Two files on the same floppy must have different file name.
(g) F1 key reproduces the last DOS command typed.
(h) The purpose of Type filename|more is to display more charac-
ters from the file on same screen.
(i) More than two files (at a time) can not be concatenated using ′ +′
option while copying.
(j) High density floppy can be readable on a low density drive pro-
vided a low density drive is used to format the floppy.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 315

27. Floppy-1 contains 30 executable files and Floppy-2 contains 45 batch files
with same other files. Write a batch file to delete all executable files from
floppy-1 and all batch files from floppy-2 on a single floppy drive system.
28. A floppy has the following directory and sub-directory structure.
last
letter current
future

newyear
diary
oldyear

ROOT

self
appo
office

self
misl buy
gift
(letter, diary, gift etc. all are sub-directories containing files and/or sub-
directories)
Write a DOS batch file to clean all sub-directories and files without using
format or diskcopy.
Chapter 21
PRACTICE PROBLEMS FOR UNIX

UNIX operating system also creates an operating environment for the user.
It provides number of services to the programs. The standard C library pro-
vides number of functions that are used by almost every C program. A set of
following programming problem have considered for the practice of UNIX.

1. In an UNIX machine, given the following:

(1) A text file containing student performances in an examination with data


related to the following fields:
(a) students’ roll numbers (5 characters),
(b) students’ name (20 characters),
(c) aggregate marks obtained by the students (3 digits),
(d) students’ addresses (30 characters).
(2) A utility sort which sorts an ASCII file in ascending order by default,
key field starting from the first column and extending upto the end of line.

sort +mr < file1

sorts the ASCII file f ile1 in descending order, key field starting from the
(m + 1)st column, and puts sorted output on terminal.
(3) A utility

rem -n

317
318 CHAPTER 21. PRACTICE PROBLEMS FOR UNIX

which reads a text file from stdin, by default, removes all characters in
the line starting from the nth column, and displays the modified text on
stdout, by default. Thus e.g., if tstfile is a text file containing the lines this
is a file for testing remove

rem -10

will modify it to produce an output as this is a for test!


(a) Write an utility

tail n

in C which accepts input from a text file (by default stdin), selects the last
n lines and displays them on stdout, by default.
(b) Using this utility and the given utilities, modify the given text file to
produce a list of students (roll number, name and aggregate marks only)
occupying the first ten positions according to aggregate marks.

Assumptions :
(1) Each line of the given text file contains data for a particular student.
(2) The file may be sufficiently large enough to be accommodated in mem-
ory.
2. Justify the following statements in an UNIX system:

(a) If p f d[0] and p f d[1] refer to the read and write file descriptors of an
open unnamed pipe,

fstat(pfd[0],stat)

or

fstat(pfd[1],stat)

always returns the value of


COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 319

stat.st_nlink

as 2.
(b) If an existing file is opened for writing using an open system call, all
the data in the file is lost.
(c) The passwd file /etc/passwd must have read/write permissions for all
users so that they can change their passwords.
(d) If simultaneously active two processes write “abcdefgh” into the same
file, then whatever be the order of execution of the processes, the content
of the file will always be “abcdefgh”.
(e) Background commands can never be terminated by pressing <CTRL-
C>.

3. With reference to UNIX operating system, answer the following questions


in brief.

(a) Outline an implementation of sleep library function using alarm, pause


and other necessary system calls.
(b) How does the shell handle ‘>>’ in the command line?
(c) UNIX schedules highest priority process first. How does it manage
round robin scheduling?

4. A common problem in UNIX systems is the creation of a file named core


when a program has an execution error. The size of these ‘core’ files is
generally quite large and they unnecessarily consume a good amount of
disk space. The system administrator of a typical UNIX installation wants to
write a utility remcore which will scan the directory structure of the system,
starting from a given directory and remove all the ‘core’ files whenever they
exist. The program should work in the following way.

(1) user, while invoking remcore, may specify


320 CHAPTER 21. PRACTICE PROBLEMS FOR UNIX

(a) the maximum number (n) of child processes that can be created by
the parent process to do the job (default value of n is 1), and
(b) the name of the starting directory (default is the current directory).
Example:

remcore -5/dir1/dir2
will atmost create 5 child processes to do the job scanning the directory
structure starting from /dir1/dir2.
(2) When remcore is invoked, the main process creates a child process
to scan the starting directory. The child process searches for ‘core’ and
if such a file exists, removes it on the other hand, during the search if
the child process finds sub-directories, it sends the names of these sub-
directories to the parent process.
(3) The parent, on receiving the path names of the sub-directories, cre-
ates new child processes (subject to the maximum limit n as specified by
the user), one for each sub-directory, to handle the files in respective sub-
directories in a similar way as the child process described in (1). When the
number of child processes created reaches the maximum limit and there
are some other sub-directories yet to be scanned, the parent cannot cre-
ate any new child process but simply waits until the number of currently
active child processes goes below n.

Implement remcore in C. Assume that no deadlock situation occurs.


5. The faculty council (of a Board/University/Institute) comprising 5 members
is to be formed out of a total of 50 faculty members. The members of the
council will be selected through votes. It has been decided to conduct the
voting in the UNIX-based computer system having a number of terminals
located at various departments of the Board/University/Institute. On the day
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 321

of voting, between 10 AM and 5PM, any faculty member may cast one vote
by giving the command vote <voter-id> <candidate-id> where <voter-
id> and ¡candidate-id¿ refer to the employee codes (ranging between 1 and
50) of the voter and the faculty member whom he/she is voting for. More
than one person can vote at the same time and any one person can issue
the command any number of times. The voting scheme to be followed is
described below:

(a) Every faculty member is a candidate to the council.


(b) Only the faculty members can cast votes to select the members of the
council. A faculty member cannot vote for himself/herself.
(c) No faculty member can cast more than one vote in favor of any one
person.
(d) Each faculty member can have a maximum of 20 votes in his/her favor.
Once that limit is reached, no one else will be allowed to vote for him/her.
(e) A faculty member may cast atmost 3 valid votes. Implement the above
scheme in C employing shared memory segment(s).

6. Examine the headers of the system and list the actual data types used to
implement the primitive system data types.
7. If you open a file for read-write with the append flag, can you read using
lseek from anywhere in the file? Can you use lseek to replace existing data
in the file? Verify this with the help of a program.
8. What happens if the file mode creation mask is set to 777 (octal)? Verify the
results using shell’s umask command.
9. Turning off user-read permission for a file that you own denies your access
to the file – verify.
10. The hole can be viewed as follows :
The file’s offset can be greater than the file’s current size, in which case the
322 CHAPTER 21. PRACTICE PROBLEMS FOR UNIX

next write to the file will extend the file. This is referred to as creating a
hole in a file and is allowed. Any bytes in a file that have not been written
are read back as 0.
Write a utility like cp(1) that copies a file containing holes, without writing
the bytes of 0 to the output file.
11. Write a program to set only one of the two time values (e.g. calendar time
and process time) with the utime function.
12. The file(1) command reads the first part of the given file, examines the con-
tents applying some heuristics and finally determines the logical type of a
file such as C program, Pascal program, COBOL, FORTRAN program and
shell script etc. Also, some Unix systems provided a command that allows
us to execute another command and obtain a trace of all the system calls
executed by the command.
Unix System Command(s)
SVR4 truss(1)
4.3+BSD ktrace(1), kdump(1)
SunOS trace(1)
Run a system call trace of the file command as:

trace file a.out

We find it calls the following functions

lstat("a.out",oxf7fff650)=0
open("a.out",0,0)=3
read(3,""..,512)=512
fstat(3,0xf7fff160)=0
write(1,"a.out:demand paged execu"..,44)=44
a.out:demand paged executable not stripped
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 323

utime("a.out",oxf7fff1b0)=0

Why is the file command calling utime?


13. Write a program that creates a directory and then changes to that directory,
in a loop, so that it can find out a fundamental limitation on the depth of a
directory tree in Unix. Also check the PATH MAX limit. Answer the fol-
lowing questions:
(a) Can you call getcwd to fetch the directory’s pathname?
(b) How do the standard Unix tools deal with this long pathname?
(c) Can you archive the directory using either tar or cpio?
14. Write a program to implement setbut using setvbuf.
15. The following C-code works correctly on some machines, but not on others.
What could be the problem?

#include <stdio.h>
int main(void)
{ char c;
while ((c=getchar())!= EOF)
putchar(c);
}

16. Write a program to obtain the current time and print the output using strftime
so that it looks like the default output from date(1).
17. Write a program, so that a process can obtain its saved set-user-ID.
18. The kernel can discard all the memory used by the process and close its
open files. In Unix terminology the process that has terminated, but whose
parent has not yet waited for it, is called a zombie. Now write a program to
create a zombie and then call system to execute the ps(1) command to verify
that the process is a zombie.
324 CHAPTER 21. PRACTICE PROBLEMS FOR UNIX

19. Write a program that calls fork and has the child create a new session. Verify
that the child becomes a process group leader, and that the child no longer
has a controlling terminal.
20. Write a program using only a simple timer (either alarm or the higher preci-
sion setitemer) which provide a set of functions that allows a process to set
any number of timers.
21. Write a program so that it calls sleep(60) in an infinite loop. Every five times
through the loop (every 5 minutes) fetch the current time-of-day and print
the tm sec field. Run the program overnight and explain the results. How
would a program such as the BSD cron demon, which runs every minute on
the minute, handle this?
22. Write a program that calls fwrite with a large buffer (a few mega bytes).
Before calling fwrite, call alarm to schedule a signal in 1 second. In your
signal handler print that the signal was caught and return. Does the call to
fwrite complete? what’s happening ?
23. Write a program using tty raw and terminates (without resetting the terminal
mode). If the system provides the reset(1) command use it to restore the
terminal mode.
24. If the system provides stty(1) command for output the MIN and TIME val-
ues then perform the following experiment: Log in to the system twice and
start the vi editor from one login. Use the stty command from your other
login to determine what values vi sets MIN and TIME to (since it sets the
terminal to noncanonical mode).
25. Implement the function sleep us that is similar to sleep, but waits for a spec-
ified number of microseconds. Use either select or poll.
26. Write two test programs, one using select and one using poll to explain how
select and poll handle an input descriptor that is a pipe, when the pipe is
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 325

closed by the writer. Repeat this experiment for looking at an output de-
scriptor that is a pipe, when the read and is closed.
27. Write a program for the following operations to understand the effects of
queue identifiers.

(a) Execute a loop five times:


(1) create a message queue,
(2) Print the queue identifier, and
(3) Delete the message queue
(b) Then execute the next loop five times:
(1) create a message queue with a key of IPC PRIVATE, and
(2) place a message on the queue
(c) After the program terminates look at the message queues using ipcs(1).
Chapter 22
COMPUTER PROBLEMS ON SOFTWARE
ENGINEERING

To practice the following software engineering problems.

1. Prepare a system flow-chart showing the following steps in processing cus-


tomer sales order:

(a) Open the incoming mail.


(b) Make an entry for the receipt of each order in an order log recording.
(c) Edit the order for missing or erroneous information.
(d) Add any needed information.
(e) Check the credit rating of the customer.
(f) Forward orders from customers with bad credit ratings to the credit
manager.
(g) Forward orders from customers with good credit ratings to the data
entry department.
(h) Enter the data to the sales order file.
(i) Check the sales orders.
(j) Sort the sales orders into item number sequence.
(k) Process the sales orders against the inventory master file producing an
updated master file and a printed listing of each transaction.

2. Prepare the systems flow-chart for the narrative describing the handling of
a request for data from a library information system. The steps involved in
the processing are as follows:

327
328 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

(1) A request for library information is made by filling a library request


form.
(2) The librarian checks the filled form for accuracy. Improper entries are
rewritten until corrected. Valid forms are accepted by the librarian.
(3) Data taken from the library request form is entered into the computer
manually through an online terminal.
(4) The main library computer processes each request, assessing data from
a disk file for the library.
(5) The response by the computer to each individual request is displayed
on a terminal located at the library. A listing for proof of all data requests
handled that day is retained for 24 hours at the main library′ s computer
center.

3. Keeping track of manuscripts submitted for review and publication is a dif-


ficult task in the offices of journals and magazines. Literally hundreds of
manuscripts of size from 1 to 50 pages, arrive in editorial offices each day.
It is important for these businesses to have an orderly system for keeping
truck of incoming articles/papers, their status and their eventual disposition
– not only it is a good business practice, but doing so is also important from
a public relations stand point.
Let us examine the system used by one magazine or journal publisher. The
firm is considering redevelopment of its system, which consists of both man-
ual and automated process.
Submission Cycle: Manuscripts are submitted to the company directly by
the authors (or by agents acting for authors) and arrive either by post, e-
mail, fax, courier, or delivered in person. All incoming articles or papers are
delivered to the editorial office. The editorial department makes an arrange-
ment for review those papers or articles for acceptance or rejection. There
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 329

is a high rejection rate. Even those articles that are eventually accepted for
publication must often undergo editing before they are finally in usable form
that can forward to the copy department for actual publication.
All manuscripts are logged when they arrive in the editorial department,
regardless of how they are delivered. Once logged, they are evaluated for
suitability and usability on the basis of various criteria, including general
interest for the subject matter of the article or paper. Various members of
the department of the editorial board review manuscripts, depending on their
areas of interests and expertise. In all cases, the reviewers convey a message
for the acceptance or rejection decision to the control clerk who originally
forwarded it to them.
All the logging and controlling works are handled by two persons in edito-
rial. However, once an article or paper is accepted, it is worked on by others,
but the control clerks still maintain the log.
Accepted manuscripts are forwarded by the control persons to the editing
staff responsible for the primary edit of the written materials. When this
primary edit is completed, the manuscripts are forwarded to a staff that does
a secondary edit for final style and phrasing. This is the final edit of the
manuscripts.
Finished manuscripts are logged out from the control system of the editorial
department. These are sent to the copy department where they are prepared
for publication in the magazine or journal.
Between primary and secondary editing, it is often necessary to redraw fig-
ures and diagrams or line art for some of the manuscripts. When these are
completed, the articles are sent to those staff members who do the secondary
editing work.
330 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

The editorial department maintains both an author file and an article file.
When a newly arrived article is logged in, a record is added to the article
file. This record is updated when the same manuscript is logged out of the
editorial department at the end of editing.
The author file contains the names of all authors who have previously writ-
ten manuscripts for the journal or magazine. When a manuscript is first
logged in. The control clerk updates the author′ s record in the author file (or
enters a new one if it is a first time author). This file is used again when the
accepted manuscript has been edited, to update the status of the manuscript
(i.e., ready for publication).
Acceptance letters are generated for accepted manuscripts, and are accom-
panies by a royalty cheque.
Once sent to the copy department, all accepted and edited manuscripts be-
come their responsibility.

(a) Develop the context diagram for the manuscript acceptance and review
process.
(b) Develop a detailed logical data flow diagram (DFD) for the editorial
department.

4. The following narrative describes a railway reservation system. Read it care-


fully and answer the questions given below:
“At the reservation counter the customer hands in a request for reserva-
tion/cancellation. The request is in a fixed format provided by railways. The
customer is expected to fill in the following details – his/her name, address,
telephone number and signature; the name, sex, age and special require-
ments (if any) of each person travelling (maximum six per form) (special
requirements - ladies cabin, lower slipper etc. and only while reserving);
the date of reservation/cancellation; the date of journey; the type of accom-
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 331

modation reserved/required; number of seats; station from, station to; train


number and/or train name. At the bottom of the form is a detachable bill
section in which the customer fills his/her name and address.
The reservation clerk accepts the form and does a rough validation (correct
train number/name, all details filled etc.). If the form is incorrect or incom-
plete he/she either corrects/completes the form or returns it to the customer.
Reservation Procedure: The clerk has an availability chart pasted on
his/her desk which indicates whether accommodation is available, or wait-
ing list is open, or no reservation is possible. Each counter caters to a set of
trains, and for each train reservations can be made from only one counter.
If no reservation is possible the clerk makes a note on the remarks column
and asks the customer for an alternative date/train/class. If the waiting list
is open the clerk confirms that the customer is willing to be wait listed. If
he/she is willing to be wait listed or if the chart shows available the clerk
selects the appropriate reservation book and enters the name, sex and age of
each prospective passenger. He/she then issues a ticket(s) to the customer,
calculates the amount from the fare calculation handbook and collects the
money from the customer. Details of the payment are entered in the bill sec-
tion of the form, detached and all bill sections and cash collected are sent to
the accounts office at the end of the day. Reservation forms are sent to the
central reservation office (CRO) at the end of the day. No reservation forms
are returned to the customer.
Cancellations: The clerk calculates the money due to the customer from the
fare calculation handbook and notes the amount returned to the customer
on the bill section. The bill section is returned to the accounts office as
described above, and cancellation forms go to the CRO.
CRO (Central Reservation Office)
332 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

This office compiles a list of cancellations for each train/date combination.


The list contains the type of accommodation, coach number, berth number,
special nature of each cancelled ticket. The office also samples reservation
forms to ensure that no customer has been unfairly refused a seat. Twenty
four hours before the scheduled departure of the train he wait listed pas-
sengers are allocated berths from the cancellation list and the passenger list
made. The passengers′ list is a list of numbers corresponding to actual seat
numbers. The passenger list is created as follows. First the cancellations are
totaled for each class and the waiting list size reduced to match this. Next
names are copied from the reservation book into the passenger list unless
the reservation has been cancelled. If the reservation has been cancelled and
the seat is not of a special type (available from the cancellation list) the seat
is allocated to the next available passenger on the waiting list and the pas-
sengers name is removed from the waiting list. If the seat is of a special
type then the waiting list is scanned to see if any passenger has requested a
seat of this type. If such a passenger exists the seat is allocated to him/her
otherwise the seat is allocated in the manner described above.
When the passenger list is ready, it is dispatched to the station master”.

(1) Draw a logical Data Flow Diagram (DFD) for the system described
above.
(2) Make a complete data dictionary entry to describe the reservation/cancellation
request form (include the bill section).
(3) Use structured English to describe the logic of the process which gen-
erates the passenger list from the reservation book and the cancellation
list.
(4) Describe the components of all files used by the system and normalize
the data base.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 333

(5) Indicate three different physical alternatives for improving system per-
formance. What are the cost/benefit tradeoffs of each alternative?
(6) Draw a new physical DFD for each alternative.

5. “After the order is confirmed, a salesman sends the sales order to the sales
supervisor who updates the credit status of the customer. The order is then
spent to the stock clerk who updates (1) inventory, (2) prepares a packing
list and (3) dispatches the product. A copy of the invoice and the original
order are then sent to the billing clerk who prepares a bill. A copy of the
bill is sent to the accounts department and another copy to the customer. An
order is confirmed only after stock availability and credit status have been
checked”.
Draw a physical DFD for the process described above and its logical equiv-
alent. Use the figure to explain the advantages of logical DFDs′ .
6. Some of the DFDs′ (shown below) contain errors. Identify the errors and

'$
DFD principle violated by the errors.
-
Invoice VALIDATE
Valid-invoice -
(1)
&%
BOOK

6
PURCHASE ORDERS

(2) '$
ADD

- -
SALE TO
Customer-details BALANCE
Customer-details

&%
(3) '$
UPDATE
Accepted invoice -INVENTORY
WITH
 - INVENTORY

&%

RECEIPTS
Accepted invoice 6

'$
?

 Issue voucher
UPDATE
INVENTORY

&%
WITH
ISSUES

 Requisitions
334 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

(4) '$
copy1 -
Order - Receive copy2 -

&%
sales
order copy3 -

(5) '$
Paid-invoice -Determine Tax-total -

&%
tax
Destination-Name - total

7. Consider the situation in EASYGO, a large travel agency. The agency has
several customers, some of them individuals and some organizations.
The agency books tickets for different mode of travel such as rail, road,
ship and air travel, and within each mode of travel, for several classes like
economy, first, luxury etc.
Typically a customer booking requisition (CBR) will be for several tick-
ets and may require booking on different modes and by different classes.
Payment is usually made by the customer after receipt of the tickets corre-
sponding to the CBR. An invoice is given to the customer along with the
tickets. In cases where the customer′ s credit is not alright, prepayment is
requested.
Internally, for case of operation, EASYGO accumulates the CBR′s and re-
organizes the tickets to be booked by mode of travel and by source and
destination. This produces a Block Booking Requirement (BBR) for each
mode of travel and these are sent to the respective booking offices. Payment
is made by the agency at ticket booking time itself.
On receipt of tickets (and booking lists) are verified with the original BBR′s
to ensure that the right tickets have been booked. After this, the tickets are
reorganized corresponding to the original CBR′s. Invoices are then sent to
the customers along with tickets and the necessary entries made to accounts
receivable. After payments are received from the customers, they are suit-
ably processed.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 335

(a) Identify the various data flow diagram (DFD) components in the above
description.
(b) Draw a very broad level data flow diagram (DFD) and then refine it
further to include all the major processes mentioned in the problem de-
scription (at least two data flow diagrams are required).
(c) Identify two possible automation boundaries and mention for each
which processes will be manual, batch and on-line.

8. Draw a complete data flow diagram (DFD) for the following system. Show
that the data structure for all the data flows to be used in data dictionary.

(a) Computech is a medium-sized computer consulting and training com-


pany that teaches public and inhouse sessions in different cities of the
country.
(b) People register for seminars by mail, e-mail, fax or by phone. There are
five types of transactions – enrollment, cancellation, payments, inquires
and others that are none of these. An editing is performed on input data
for validity.
(c) Enrollments are noted in three places namely student file, seminar file
and payment file.
(d) A confirmation is to be sent to the student.
(e) Payment comes by mail (via cheque, credit-card) which is to be matched
up to its associated invoice to credit accounts receivable.
(f) (1) The database has to support such queries as when a particular
course in a particular city would be held.
(2) Who are the persons from a specific organization that have attended
a course?
(3) What is the grade of a student in a specific course?
(4) Who is the instructor of a specific course?
336 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

9. Draw a physical data flow diagram (DFD) and it’s equivalent logical DFD
for the following system and use this as an example to explain the difference
between a logical and a physical DFD.
When a teller in a Bank receives a cheque for less than Rs.1000/- he pays the
amount without checking the customer′ s balance. The cheques are passed
(at the end of the day) to a clerk who updates all balances (overdrafts are
allowed). The clerk passes all the cheques to the Accounts Supervisor who
prepares a daily withdrawals report.
10. Component Manufacturing Company is a small manufacturing firm spe-
cializing in the designing and production of small electric components and
parts. The firm has been growing rapidly over the last few years and though
it has a recently built modern manufacturing facility, it is thinking of con-
structing another one at a nearby location.
The company was set-up in 1990 by Sri Madhav Rao who is currently the
president of the firm. Mr. Sudip Mukerjee is the General Manager Oper-
ations and his role is to oversee everything that goes on in the company.
Manufacturing is looked after by Ranjit Ghosh.
The increase in the firm′s business over the last few years has resulted in a
larger volume of orders being received and managed by it. Both Mukher-
jee and Ghosh are worried that as business expands further they will lose
control of orders and receivables. Ghosh has requested that the firm′s order
entry and invoicing operations be studied to determine the suitability of au-
tomating the processing of sales orders. While the present system appears
to be working satisfactorily, Mukherjee feels that the incidence of lost or-
ders appears to be increasing. A description of the order entry and invoicing
process follows.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 337

Orders are received over the telephone, by mail/e-mail, or by telex/fax. All


orders are manually acknowledged. Telex/fax orders are acknowledged by
telex/fax while the rest are acknowledged by mail/e-mail.
When orders are received, they are price-verified by Mukherjee and ap-
proved by either Ghosh or Rao. Orders are usually rejected if the wrong
price has been mentioned or if the customer has an overdue account or poor
payment history.
After approval, orders are sent to the order control desk, where they are
logged and assigned an internal job number. An order card is prepared and
current information about the customer updated. Customer information in-
cludes current items on order and a running account balance and is kept on
large individual cards called order cards.
Copies of the order are given to the production manager and to a clerk who
maintains a list of open (unfinished) orders. At the end of each week, the
order clerk assembles a report of open orders. The production manager veri-
fies his set of order copies accumulated during the week against the prepared
open order report. The order becomes the production order for manufactur-
ing. Orders are manufactured on a FIFO (First In First Out) basis. When
work on the order is completed the production manager writes down (on a
sheet of paper) who the part is for and the quantity ready for shipping. This
is used to type out the invoice and packing slip as well as to update the open
order list.
The parts are then moved to the shipping area where they are packaged and
dispatched along with the invoice and packing slip to the customer.
A copy of the invoice is sent to the book-keeper who files it on the cus-
tomer’s accounts receivable file. A second copy is placed in a master ac-
338 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

counts receivable file. Invoices are also numbered and logged on an invoice
log sheet.

(1) Draw a logical Data Flow Diagram (DFD) for the order processing and
invoicing activities described above.
(2) Indicate automation boundaries for a batch processing system and an
on-line processing system on the DFD.
(3) Describe how the on-line processing system will work. Your answer
should not exceed 100 words (10-15 lines).

11. XYZ is a regional airline company of a country. Daily operations of XYZ


are summarized as plane movements, ticket sales and personnel operations.
Ticket sales consist of local flights and international flights. Personnel op-
erations mainly consist of checking the attendance of the personnel. Plane
movements include daily plane landings and plane takeoffs. Prepare a HIPO
(Hierarchy plus Input-Process-Output) package to represent the daily oper-
ations of XYZ airlines.
12. Prepare a DFD (Data Flow Diagram) to describe the activities for

(a) Getting a plane ticket through a travel agent.


(b) Pumping fuel (i.e. Petrol, Diesel, etc) into your car.
(c) APM (Auto Parts by Mail) corporation that stocks auto parts and sup-
plies them by any one of these order such as phone, mail, e-mail, fax
order.
(d) Eating a coconut.

13. ABC is an international trade corporation. Customer orders are received via
mail, phone, telex, e-mail and fax. Customer order processing, correspon-
dence and accounting are some of the major processes. Customer file, ven-
dor file, materials and equipment specifications are some of the data stores
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 339

in the company’ database. Using data flow diagram (DFD), represent the
activities of this company.
14. Using DFD, represent the following activities:

(a) The reserved books section of an Institute/School/College/ University


or a research laboratory′s library.
(b) Getting a student transcript in a university/institute’s registration office.
(c) The various stages of a linear programming (LP) application for a busi-
ness problem.

15. Convert the following DFD into a proper SADT (Structured Analysis and
'$
Design Technique) diagram. TAX TABLE
ITEM
Item quantity -TAX CAL-
CULATION 
&%Item Tax -
TAX RATE
Item value -

16. Prepare an activity diagram and data diagram for the following:

(a) A telephone billing project.


(b) An electricity consumption for the customer billing.
(c) The customer billing system of a company.
(d) A student registration system for an Institute or an University.
(d) The forecasting activities in a production system.

17. Using SADT diagram, represent an information retrieval system.


18. Consider a small farm that produces wheat and oil seeds as two major crops.
Each year at winter, the wheat area and oil seed areas are determined from
the following year to maximize the profit of the farm in terms of yield and
selling price of each of the crops.
Prepare a structure chart for crop planning for this farm by getting the crop
record, computing the wheat and oil seed areas, and printing the result.
340 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

19. On a structure chart show how to compute and print the monthly schedule
of payments resulting from a credit purchase in the credit purchase system
of a company, also given the amount of credit purchase and the number of
monthly payments planned.
20. Prepare a structure chart for an inventory update operation of a company in
terms of the following process:
(a) Get transaction, (b) Get inventory, (c) Process transaction, (d) Rewrite
inventory, and (e) Write reorder.
21. Consider a computer program which has more than three modules. Deter-
mine the type of cohesion of each module and the type of coupling of each
pair of modules. Use a table to show the type of coupling between the mod-
ules. (A modules in PL/I is a procedure; it is a procedure or function in PAS-
CAL or C; subroutine or function subprogram in FORTRAN. In COBOL
program, subprogram, section and paragraph are examples of modules.)
22. The people’s Health Services is a large hospital providing treatment for var-
ious types of diseases. As it is a public hospital, a large number of people
come for treatment.
The hospital has a computer system which is used for the purpose of reg-
istering the patients admitted to the hospital. It is also used for keeping ac-
counts of the expenditure relating to treatment of each patient and prepara-
tion of bills for the treatment given to each patient.
In the computerized system, there are two files maintained on the computer.
The description of the two files is given below.
There is a master file called Patient’s Master file which contains one record
for each patient. When a patient is admitted to the hospital a record is created
in this file. The record has a patient number which is a specific number given
to each patient for his/her identification. In addition, the following data is
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 341

also entered in the record viz. (a) the name, (b) full address of the patient,
(c) the date of admission of the patient, (d) description of the disease, and
(e) the name of the doctor who is treating the patient.
There are a number of departments in the hospital which render vari-
ous services to the patients. For example, the pharmacy department issues
medicines for treatment of the patients. The radiology department takes X-
ray, CT scan, MRI etc. of the patients as advised by the doctors. When a
patient is given a service by a department in a document called expense
sheet. This document contains patient number, data, description of the ser-
vice like medicine issued, radiological facilities taken etc. and the amount
payable for the service.
At the end of every day (or immediately through local area network (LAN)),
each department send its expense sheet to the computer department, where
the data contained in the documents are entered into a transaction file called
daily expense file. The records of this file are then added to those in another
file called cumulative expense file in which all transactions upto the previ-
ous day in that month are available. Thus the cumulative expense file will
contain all the charges upto the end of the day, or at the end of a month.
When a patient is discharged from the hospital, a computer processing is
done to match the patient master record with the records available in the
cumulative expense file for that patient. All the records in the cumulative
expense file for that patient are printed out in the form of a bill. The bill
contains the details of services given to the patient on each date along with
the charges is printed at the end of the bill showing the total amount due
from the patient. The name and address of the patient, and the name of the
doctor who treated the patient is also printed on the bill, using the master
record data.
342 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

Answer the following questions.

(a) Draw a data flow diagram (DFD) showing the procedure adopted for
patient billing.
(b) Suggest record formats with data fields for the master file and the ex-
pense file separately.
(c) It is found sometimes that there are mistakes in the bill. The mistakes
relate to charges for services not given to the patient. How can this be
eliminated?
(d) What is the file organization for both master file and expense file that
is likely to be used in the above system?
(e) At present the disease is described in the master file with words like
cholera, typhoid etc. It is proposed to have a statement prepared every
day on the number of patients admitted disease – wise. Suggest a method
for generating such a report.

23. The hostel of a big college has more than 500 rooms with four messes.
There are more than 1000 students staying in the hostel (with all rooms
being double-seated). The students can eat in any of the messes. There is a
standard menu everyday for which standard rates are charged. In addition
to normal menu, there are extra items like sweets, ice-cream etc. which are
given to the students on additional payment. Students who do not dine in the
mess continuously for more than 4 days at a time are given rebate provided
advance intimation is given.
The hostel has a computerized system for keeping a database on the students
and also maintain accounts of their billing for the students. In addition, the
expenditure accounts relating to the purchase of food articles, salary of mess
staff etc. are also maintained on the computer, which helps in working out
the monthly standard rate for charging the students.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 343

The following information requirements are met by the system:

(a) Preparation of standard mess bills for all students.


(b) Weekly report on outstanding bills from students.
(c) Bills for extras and rebates to student.
(d) Monthly calculation of standard rate for charging students based on
previous monthly’s expenditure.
(e) Monthly report on stock of items purchased and issued to the mess, for
standard menu.
(f) Monthly report on purchase of extra items by students – itemwise.
(g) Monthly report on rebates given to students.

Answer the following questions:

(1) Draw a data flow diagram (DFD) for the following:


• Processes involving preparation of bills for students.
• Processes involving mess accounts relating to calculation of standard
menu rate for each month.
(2) A number of files are maintained in the system relating to maintenance
of database for students. Preparation of mess bills for students etc. Give
the record structure of the following files given below.
• Student master file.
• Payments to suppliers.
(3) The computer system consist of a computer in the Hostel Warden’s
office with terminals at the four messes. What controls and checks would
be required in the system?

24. An educational institute follows the procedures given below.


Selection procedure: The candidate seeking admission collects the enquiry
slip from the reception counter. The enquiry slip gives information regarding
344 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

the courses offered by the institution and has a questionnaire for the candi-
date to furnish information about himself. The candidate files in the ques-
tionnaire. This is sent for screening. Based on this information the counsel-
lor decides if the student can be given an aptitude test. If so, the student is
asked to pay the fee for the aptitude test. He pays it in the accounts depart-
ment and gets a receipt. The receipt is shown to the counsellor who then
gives the aptitude test. The candidate who does not choose to take the test,
need not pay the fees.
The candidate, who is successful in the aptitude test, is called for coun-
selling. He and the counsellor jointly select the course. Then the counsellor
fills in the admission card. The admission card contains the admission num-
ber (AD.No.), candidate’s name and the selected course. This is prepared in
triplicate : one copy is given to the candidate, one to the accounts depart-
ment. The counsellor retains the third copy. This completes the selection
process for the candidate. But only when he pays the course fees he is ad-
mitted into the selected course and becomes a student.
Admission procedure: The candidate, takes the admission card to the ac-
counts department. In his admission card, the fee payable for the course and
the due date are written by the accounts department and returned to him. The
accounts department also updates its copy of the admission card with this
data. When the candidate pays the course fee the accounts department gives
him a receipt. The receipt contains receipt number, the AD.No., amount
paid. This receipt is prepared in duplicate one copy is given to the student
and the other one is retained in the accounts department. The copy of the
admission card with the accounts department is returned to the counsellor
with fee receipt number. The counsellor updates the course-wise admission
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 345

list with this data. Now the candidate is admitted in the course and becomes
a student.
He who does not pay the fees within a week after the due date is given a
remainder. If the dues are not paid even after 15 days after the due date the
student’s admission is cancelled and a copy of the cancellation letter is sent
to the counsellor.
The accounts department maintains a student’s dues register and updates it
with the receipts.
Library procedure: There is a library attached to the institution. To avail
this facility, the student is to make an initial caution deposit. The student
pays deposit in the accounts department which prepares the receipt with
student AD.No. in triplicate. One copy is given to the student, one is sent
to the library and third is retained. The student then can borrow books from
the library. For each book borrowed, the student has to pay a charge as
per the lending rate maintained in the library. The student has to fill in a
requisition from with his Ad.No. for borrowing books. When the book is
issued, the lending rate is entered therein and the requisition form is sent to
the accounts department to update the student’s due register.

(a) The counsellor prepares a weekly statement giving course-wise avail-


ability of seats for his counselling. Each course has only a specified num-
ber of seats. He also keeps track of the progress of each student in his
chosen course.
(b) The accounts department prepares monthly statements to know the fees
collected in respect of aptitude test, course fees and the library. It also
prepares a monthly student’s due statement to be given to the concerned
student.

You are required to:


346 CHAPTER 22. COMPUTER PROBLEMS ON SOFTWARE ENGINEERING

(i) Draw a DFD for the procedures.


(ii) Give the contents of the master files maintained by the counsellor and
the accounts department.
Chapter 23
PROBLEMS ON DECISION TABLE

An analysis of decision-making criterion for a deterministic system consider


the following:
(1) The necessity to take a quick decision,
(2) The selection and evaluation of large number of existing alternatives,
and
(3) The difficulty in detecting in advance, all the operating alternatives, and
all the possible and significant combinations of values of selection cri-
teria, etc.

One can program the above activities using a set of decision-making rules
that are the combinations of actions (i.e., the measures to be taken once an
alternative has been selected) and conditions (i.e., the selection criteria for
these alternatives).
There are various ways of representing rules depending on the importance
afforded,
either (1) the specification of rule,
or (2) the selection process aspects.
Example:
• The narrative method (e.g., evaluation of “if <conditions> then
<action>)”,
• The flow-chart method (e.g., draw the flow chart of the problem for
implementation),

347
348 CHAPTER 23. PROBLEMS ON DECISION TABLE

• The tabular method (e.g., this method shows the functional dependence
in every point of its definition domain. This method is of two types as
the expositive table method and the decision table method.

The tabular method


The expositive table method
This method shows the functional dependencies f = f (c1 , c2 , · · · , ck ) where,
c1, c2 , · · · , ck are the conditions in every point of its definition domain.
A projection of this function in 2-D space is made in the form of a table with
row and column entries that cross each other, specifying the action program to
be performed.
Let c1 , c2 are the two conditions and vi j are values then the expositive table
used to represent the rules for decision-making activity:
c1
v11 v12 v13 v14
v21 f11 f12 f13 f14
c2 v22 f21 f22 f23 f24
v23 f31 f32 f33 f34

Let c1 , c2 , c3 are the three conditions and vi j are values then the expositive
table used to represent the rules for decision-making activity:
c1
v11 v12 v13
c2 c2 c2
v21 v22 v23 v21 v22 v23 v21 v22 v23
c3 v31 f111 f121 f131 f211 f221 f231 f311 f321 f331
v32 f112 f122 f132 f212 f222 f232 f312 f322 f332
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 349

The decision table method


There are other way of representing this function f = f (c1 , c2 , · · · , ck ) in a
plane by using Monge Projection in descriptive geometry as for example, let
P(α , β , γ ) be a point in x − y − z rectangular system, then the traces P′ on x − y
plane and P′′ on x − z′ plane of P. Similarly, the decision table represents the
functional dependence of f = f (c1 , c2 , · · · , ck ) by means of two planes: (1) a
condition plane, and (2) an action plane, as shown below:
Decision Table Quadrants
Conditional plane → Condition stub Condition entries
I II
Action plane → Action stub Action entries
III IV
Also a decision table is to provide information concerning problems and so-
lution in a concise format that is easy to read and understand. This tabular
approach is used to express complex decision logic in a manner that encour-
ages the system analyst to reduce a problem to its simplest form by assigning
and presenting logical alternatives under various conditions.
Decision table construction procedure
Step 1: List all actions that can be associated with a specific procedure
(or module).
Step 2: List all conditions (or decisions made) during execution of the
procedure.
Step 3: Associate specific sets of conditions with specific actions, elim-
inating impossible combinations of conditions; alternatively, de-
velop every possible permutation of conditions.
Step 4: Define rules by indicating what action(s) occurs for a set of con-
ditions.
350 CHAPTER 23. PROBLEMS ON DECISION TABLE

To practice the following decision table problems.

1. In an university admission rules for its post-graduate course are as follows:


Admit a student who has undergraduate grades of B or better, has test scores
on the admission test of over 550, and has a grade average of B or better for
the past 2 years. Also admit if the overall grade average is less than B but
the last 2 years′ average is B or better and the test score is over 550. Admit
on probation if the overall and 2-year grade averages are B or better but test
score is 550 or less. Admit on probation if overall grade average is B or bet-
ter and test score is above 550 but grades during the last 2 years are below
B. Also admit on probation if overall grade average is less than B and test
score is 550 or less, but grades for past 2 years are B or better. Refuse to
admit all others.
You are required to do the following:
(1) Find the minimal sets of conditions and actions.
(2) Prepare a fully expanded decision table.
(3) Minimize the table obtained in (2).
(4) Draw a program flowchart for the table obtained in (3).

2. The policy followed by a computer to process customer orders is given by


the following rule.
(1) If a customer order is less than, or equal to that in stock and his credit
is O.K., supply his requirement.
(2) If his credit is not O.K., do not supply. Send him an intimation.
(3) If his credit is O.K. but items in stock is less than his order, supply what
is in stock, enter the balance to be sent in a back order file.
Obtain a decision table corresponding to these rules.
3. A company manufactures three products: AC/DC motors, pumps and fans.
They give a discount of 10% on orders for motors if the order is for
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 351

Rs.5,000/- or more. The same discount of 10% is given on pump orders


of Rs.2,000/- or more and on fan orders for Rs.1,000/- or more. On all other
orders they do not give any discount. Obtain a decision table corresponding
to this word statement.
4. An insurance company of the country follows the following rules to calcu-
late premium:

(1) If a person’s health is excellent and the person is in between 25 and 35


years of age and lives in a city and is male, then the premium is Rs.2 per
thousand and his policy may not be written for more than Rs.2 lakhs.
(2) If a person satisfies all the above conditions except that the sex is fe-
male, then the premium is Rs.1.50 per thousand and her policy may not
be written for more than Rs.1 lakh.
(3) If a person’s health is poor and age is in between 25 and 35 and the per-
son lives in a village and is a male then the premium is Rs.9 per thousand
and his policy may not be written for more than Rs.10,000.

Construct a decision table.


5. The CBM (Computer Books by Mail) Corporation is a book-jobber com-
pany. It receives orders for books about computers, order the books from the
appropriate publisher at a discount, and fills the order on receipt of books
from the publisher. Orders from customer can be treated either on a priority
basis or on a normal basis. The criteria for treating an order as a priority
order or on a normal order are

(1) If the customer orders more than Rs.1,00,000 a year and has a good
payment history then treat the order as a priority order.
352 CHAPTER 23. PROBLEMS ON DECISION TABLE

(2) If the customer orders more than Rs.1,00,000 a year, has a bad payment
history but has been ordering for more than 20 years then treat the order
as a priority order.
(3) If the customer orders more than Rs.1,00,000 a year, has a bad payment
history and has been ordering for less than 20 years than treat the order as
normal order.
(4) If the customer orders less than Rs.1,00,000 and has a good payment
history then treat the order as a priority order.
(5) If the customers orders less than Rs.1,00,000 and has a bad payment
history treat the order as a normal order.

Construct a decision table.


6. The entrance fee changes for a film show in determined by the following
rules: “Adults pay Rs.5.00 on weekdays and Rs.7.50 on weekends. Those
70 years or older pay half the adult price. Children twelve or older are con-
sidered adults. Children 6 years through 11 years pay Rs.2.50 on weekdays
and Rs.3.50 on weekends. Construct a decision table.
7. A well-known management institute is evaluating the proposals of its old
computer system′ s upgrade and the installation of as many number of new
personal computers (PC′s) as possible. However, because of the budget lim-
itations decisions regarding these proposals are very critical. There is a third
proposal for installation of an uninterrupted power supply (UPS) system for
its another newly installed computer system with financial supports from
a financial institution. Thus the chairman of the computer committee has
chalked out a plan as following:

(1) If the computer committee feels that the performance of the old com-
puter system is very poor and the improvement will not be cost effective
and therefore, the machine should not be upgraded then the entire sum of
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 353

money would be spent towards the purchase of maximum number of PC′s


if the PC′s are found to be of satisfactory performance in the market.
(2) If the committee decides that the upgrading of the old computer system
will be cost effective and also the performance of the new personal com-
puters are quite satisfactory then the major portion of the money would be
spent on upgrading and the rest would be spent towards the purchase of
the personal computers and both the proposals would be put in the pend-
ing purchase order file.
(3) If the committee members find that the personal computers (PCs) are
not good, the proposal of the personal computers would be turned down
and the entire sum of money would be spent towards the upgrading of
the old computer system if it is found to be cost effective, otherwise the
budgeted amount would be forwarded to the next year′s budget.
(4) If the committee feels that in addition to the memory backup system
available with the next computer system, the UPS system is really re-
quired to protect the new computer, and the performance of the UPS sys-
tem available in the national market is known to be satisfactory, the pur-
chase of UPS system would be recommended. Otherwise, if the financial
institute approves the transfer of this money for the purchase of number of
personal computers, the money for UPS system would be spent towards
the purchase of personal computers, and the other budgeted amount would
preferably be spent for the upgrade. However, if this transfer is not possi-
ble, this amount would be added with the new computer center′s general
budget. (Make any necessary assumptions).

For the above problem you are required to:

(a) Find all the conditions and actions.


(b) Prepare a decision table illustrating the total decision making process.
354 CHAPTER 23. PROBLEMS ON DECISION TABLE

(c) Minimize the decision table obtained in (b), and


(d) Convert the minimized table obtained in (c) into a program flow chart.

8. An employee should use the following decision table before entering the
office of the director of the organization.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Door open n y n y n y n y n y y n n y n y
Ring ‘on’ n n y y n n y y n n y y n n y y
Enter ‘on’ n n n n y y y y n n n n y y y y
Door locked n n n n n n n n y y y y y y y y
Ring bell x x * * * *
Enter x x x x * * * *
Wait x x * * * *
Leave x x x * * x x * x *
where, n for no, y for yes, x for don’t care, * for action are logically impos-
sible combinations.
Minimize the decision table.
9. An insurance company uses the following rules to determine the eligibility
of a driver for insurance. The driver will be insured only if

(1) The driver lives in a city with population less than 5000 and is a married
male, or
(2) The driver lives in a city with population less than 5000 and is married
and over 30 years, or
(3) The driver lives in a city with population less than 5000 or more and is
a married female.
(4) The driver lives in a city with population less than 5000 and is a male
over 30 years, or
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 355

(5) The driver lives in a city with population less than 5000 and is married
and under 30 years.

Write down the decision table from the above rules.


10. Obtain a decision table from the following specifications for an automatic
stamp venting machine.

(1) To dispense Rs.10.00, Rs.5.00, Rs.2.00, Re.1.00, 50 Paise, 25 Paise


stamps.
(2) To accept Rs.5.00, Rs.2.00, Re.1.00, 50 Paise, 25 Paise, 20 Paise and
10 Paise coins.
(3) Do not return change if it entails returning more than 2 coins of the
same denomination.

11. An airlines reservations decision table can be formed using the following
rules:

(1) If the request is for first class and first class space is available then issue
a first class ticket and subtract 1 from the first class seats available.
(2) The request is for first class, but no first class seats are available. Tourist
space is open, and the passenger will accept tourist accommodations. The
actions call for the issuance of a tourist ticket and the subtract 1 from the
number of tourist seats available.

12. Sum up the following operating alternatives in a complete decision table and
also draw the final decision table.
“In a petrol filling station there are two petrol pumps, one for Gr.I petrol and
the other for Gr.II petrol, as well as a pressure gauge for tires. Each driver
asks the attendant to fill his petrol tank with the required grade of petrol; if
the requested grade of petrol is not available, the driver leaves the station,
sometimes adjusting the tire pressure before leaving. If the grade of petrol
356 CHAPTER 23. PROBLEMS ON DECISION TABLE

requested is available, the driver gets his tank filled, possibly adjusts the tire
pressure, and then leaves the station.”
13. Sum up the following operating alternatives in a complete decision table and
also draw the final decision table.
“In a petrol filling station there are two petrol pumps, one for Gr.I petrol
and the other for Gr.II petrol. Every driver entering the station will require
his petrol tank to be filled with the necessary petrol grade; if the requested
grade of petrol is not available, the driver may choose the other grade of
petrol. If the driver asks for petrol of the later grade and it is available, then
his petrol tank will be filled with the alternative grade of petrol, otherwise
he leaves the station.”
14. The manager of the credit verification department of the sunrise sportswear
company explains the logic of the credit verification process as follows:
When our secretary receives orders without any payments enclosed, he/she
forwards them to us. We look at the order to determine if the customer wants
to pay by credit card. If so, we check the credit card company to make sure
so we will get paid. If the credit card company says their credit is OK, then
we go ahead and process the order. If the credit card expires, we turn to our
internal system and handle it like a regular credit purchase.
In the case of new customer (say one year old) if there is no overdue balance,
we process the order, but if they owe us money, then we determine whether
the overdue balance is more than 60 days or not. If it is over 60 days, we
reject the order. As for old customers, there is no problem if there is no over
due balance. But if there is, and the balance is over 60 days late, then we
reject the order.
For the above policy, prepare either a decision tree or a decision table.
Chapter 24
PROBLEMS ON DATA STRUCTURE

Implement the following data structure problems.

1. Implement a circular queue (Q) using an array of fixed size. Write the
Create-Q, Add-Q, Delete-Q, Empty-Q and overflow operations. Using these
operations implement a stack (with two queues) along with its necessary
manipulation functions.
2. Design an efficient data structure to sort integers of arbitrary length (i.e.,
variable number of digits). Write procedures to read, write, add and mul-
tiply such long integers. Is your data structure efficient in terms of storage
utilization? Discuss.
3. Implement queue data structure using link list.
4. Using the heap data structure implement a priority queue with the following
operations (a) insert, (b) delete minimum.
5. A pointer T points to the root of a binary tree represented as a linked list.
Write a procedure that will determine and return the height of the binary
tree.
6. Write a program to search for an item I (say) from a binary-search tree.
7. Let P(x) and Q(x) be two polynomials in the variable x. We will say that
Q(x) is a factor of P(x) if there is a polynomial R(x) in x such that P(x) =
Q(x).R(x).
Example:
x2 +x +1 as a factor of x3 −1, but 5x +1 is not a factor of 5x2 −1. The terms
of a polynomial are only allowed to have real numbers as coefficients.

357
358 CHAPTER 24. PROBLEMS ON DATA STRUCTURE

The two polynomials P(x) and Q(x) are represented as circular lists with
pointers P and Q pointing to the respective head nodes. Write a procedure
that will return the Boolean value true if Q(x) is a factor of P(x) and the
Boolean value false otherwise.
8. Write a program to do the following operations on the polynomials P and
Q with one or more variables (i.e., x or x, y, z, ...) having degrees m and n
respectively.
(a) Add or subtract two polynomials P and Q.
(b) Multiply two polynomials P and Q.
(c) Divide the polynomial P by Q.
Print the output in a suitable readable format.
9. Write a program to do the following operations on the sparse matrices P and
Q.
(a) Add or subtract two sparse matrices P and Q.
(b) Multiply two sparse matrices P and Q.
Print the output in a suitable readable format.
10. A tree traversal of the nodes of a binary tree is said to be level-by-level if
the following condition holds: if the level of a node P is a strictly smaller
number than the level of a node Q, then P must be visited before Q. Thus
the root node is visited first, followed by the nodes at level two (in any order
amongst themselves) followed by the nodes at level three, and so on. Write
a procedure, which when supplied a pointer T to the root of a binary tree,
prints out the data fields of the nodes in a level-by-level sequence.
11. Write a program to compare two binary search trees using recursion.
12. Let us consider the Josephus problem described as follows. Suppose that n
objects are arranged in a circle and are numbered 1, 2, · · · n. We are given a
positive integer m ≤ n. Beginning with object number 1, we proceed around
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 359

the circle, removing every mth object. After each object is removed, it is no
longer counted in the subsequent rounds. This process continues until all
objects are removed from the circle. Corresponding to the order in which
objects are removed from the circle, there is a particular permutation of the
integers 1, 2, · · · , n, which is called the (n, m)-Josephus permutation.
Example:
The (7, 3)-Josephus permutation is (3, 6, 2, 7, 5, 1, 4). Suppose m is a con-
stant. Describe an O(n)-time algorithm that, given an integer n, outputs the
(n, m)-Josephus permutation. Describe the data structures that are needed.
Explain, how your algorithm is taking O(n)-time in the worst-case.
13. Given two strings a = a[0..p] and b = b[0..q], where each a[i] and b[ j] is
in some ordered set of characters, we say that string a is lexicographically
less than string b if either (i) there exists an integer j, 0 ≤ j ≤ min{p, q},
such that a[i] = b[i] for all i = 0.. j − 1 and a[ j] < b[ j], or (ii) p < q and
a[i] = b[i] for all i = 0, 1, · · · , p. For example, if a and b are bit strings, then
10100 < 10110 by rule (i) above, and 10100 < 101000 by rule (ii) above.
This is a similar ordering to that used in English-language dictionaries.

The radix tree data structure shown in Figure 1 (below) stores the bit strings
1011, 10, 011, 100, and 0. When searching for a key a = a[0..p], we go left
at a node of depth i if a[i] = 0 and we go right if a[i] = 1.

Let S be a set of distinct binary strings whose lengths sum to n. Show how to
use a radix tree to lexicographically sort S in O(n)-time. Explain, how your
algorithm is taking O(n)-time in the worst case.
360 CHAPTER 24. PROBLEMS ON DATA STRUCTURE

Example:
In Figure 1, the output of the sort would be the sequence 0, 011, 10, 100,
1011.
u
"b
" b
0 "" b 1
b
" b
e" bu
" b
0 " b
b "
bu e10
b1 0"
"
b 1 "b
be e 1bu
b "0 b
"
b 1
be
011 100 b
1011

Figure 1: A radix tree that stores the bit strings 1011, 10, 011, 100, and 0.
Each node′ s key can be determined by traversing the path from the root to
that node. There is no need, therefore to store the keys in the nodes; the keys
are shown here for illustrative purposes only. A node is heavily shaded to
represent that the key corresponding to it is not in the tree, and the node is
present only to establish a path to other nodes.
14. Write a program to merge two linked lists such that elements of the two
lists alternate in the new list. Do not create a new list but implement using
pointer changes in the old lists.
15. Give a non-recursive algorithm to construct a binary tree given its preorder
and inorder sequences. What is the time taken by your algorithm in the worst
case?
16. Consider the problem of finding the minimum-cost spanning tree connect-
ing n distinct points in the plane, where the distance between two points is
the Euclidean distance. For each of the following procedures, either argue
that it constructs the minimum-cost spanning tree of the n points or give a
counter example.
(a) Sort the points in order of their x−coordinates. (You may assume with-
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 361

out loss of generality that all points have distinct x−coordinates; this can be
achieved if necessary by rotating the axis slightly.) Let p[1..n] be the sorted
sequence of points. For each point p[i], 2 ≤ i ≤ n, connect p[i] with its clos-
est neighbor among p[1..i − 1].
(b) Draw an arbitrary straight line that separates the set of points into
two parts of equal or nearly equal size (i.e. within one). (Assume that this
line is chosen so it does not intersect any of the points.) Recursively find
the minimum-cost spanning tree of each part, then connect them with the
minimum-length edge connecting some point in one part with some point in
the other (i.e., connect the two parts in the cheapest possible manner).
17. Consider the following Disjoint set Union-Find problem. We start with n
disjoint sets {1}, {2}, · · ·, {n}, where n = 16.
(a) What is the sequence of union (with weighting rule) operations that
will create a worst possible tree (i.e. a tree of maximum possible height)
representing the set S of all elements (i.e., 1 to n)?
show the content of the data structure that supports the set S. What is the
total time taken in performing these unions?
(b) Now, apply a sequence of n FIND operations (with collapsing rule,
which may reconstruct the tree) on the set S. What is the sequence of FINDS
that will take maximum time?
18. A sorting method is called stable if it preserves the order of records having
equal keys (i.e. if in the input file, record X precedes record Y and key of X
= Key of Y, then X precedes Y in the sorted output). For the heap sort, either
argue that it is stable or give a counter example.
19. Consider the problem of implementation of file storage on disk. Two com-
mon data structures used are B − tree and hashed table.
Assume there is a file of N (usually larger) records where each record con-
362 CHAPTER 24. PROBLEMS ON DATA STRUCTURE

sists of r bytes, and the primary key-field has k bytes (the value of the pri-
mary key-field is unique for a record). Each sector or block of a disk has s
(≥ r) bytes. The file is assumed to be indexed on the primary key. The oper-
ations of interest are: insert, delete, modify and retrieve, using key value for
searching.
(a) Describe the B-tree organization for this problem. Analyze the time
taken in the worst case as well as in the average case for each of the op-
erations mentioned above.
(b) Repeat (a) for the hashed organization. Clearly state your assumptions.
(c) Make a comparative study between the two implementations.
20. Construct a hash table, TAB[0..m − 1], using double hashing method. The
hash functions are:
h1(k) = k mod m and h2(k) = k mod (m − 2) + 1;
and the input sequence is : 10, 5, 11, 18, 14, 21, 12, 7, 6, 16. Calculate the
average number of probes for a successful search as well as an unsuccessful
search. State your assumptions about probabilities.
21. Construct an AVL tree through insertions for the input sequence:
10, 15, 8, 9, 12, 17, 18, 11, 13, 14.
Calculate the average number of comparisons for a successful search as well
as an unsuccessful search. State your assumptions about probabilities.
22. We would like to implement a GIS (Geographic Information System) for
a country (say, India). We are giving below a hypothetical division of the
country in different regions and their inter-relationship.
For administrative purposes, the country is divided into a number of zones
(e.g., S, NE etc.), which are non-overlapping in area. Each zone consists of
a few states (once again non-overlapping in area). Each state in turn con-
tains a few districts, which again contains a number of blocks/city in area).
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 363

A block may further be subdivided into a number of villages. In short, the


strict hierarchical division of the country (as a geographical region) is in
the sequence : zone, state, district, block/city, village. Information, at each
level, to be maintained is as follows:
Zone : Name.
State : Name, capital, number of universities.
District : Name, headquarter, area, number of colleges, average rain-
fall.
Block : Name, headoffice (location), literacy(%).
City : Name, class, population, number of schools, literacy(%).
Village : Name, population, number of schools.
We are interested in processing a variety of query/data manipulation oper-
ations on this GIS. A few sample queries/manipulation operations are indi-
cated below:
Queries:
(1) List states in a particular zone.
(2) List states along with their districts.
(3) List cities with very high literacy (e.g. 75%) along with their state
names.
(4) How many villages with school are in a particular state?
(5) List states with total area, population, number of universities, number
of colleges, number of schools, literacy, average rain fall.
(6) Give the state to which a particular city belongs.
Data Manipulation:
(1) Addition and deletion of a village/city.
(2) Name of a region (e.g., state, village) is changed.
(3) Data of a particular region changes (e.g. number of colleges in a district,
literacy of a block are modified).
364 CHAPTER 24. PROBLEMS ON DATA STRUCTURE

(4) Modification in the region division information (e.g., a block was


wrongly put under a district, a state is shifted from one zone to a differ-
ent zone).
(5) Combining regions (e.g., two districts join together).
(6) Splitting of regions (e.g. a district is split in two; a state is split in three).
Assume splitting of a region at any level occurs only along the boundaries
of the subregions of the next lower level.
You are required to do the following:
(a) Determine a suitable data structure to hold the entire data, in a way
that facilities operations (i.e. queries or manipulations) to be performed
efficiently. State your assumptions clearly, if any.
(b) Write procedures for the following operations: queries numbered 2, 3
and 6 (see above); Data manipulations numbered 1, 2 and 6 (see above).
Give a time analysis for each of these procedures (or algorithms).
(c) Identify a few general procedures which can be useful in solving many
queries/manipulations. Give the parameters of these procedures.
(d) Enumerate the strengths and weaknesses of your proposed data struc-
ture. Also suggest a few remedies, if necessary.
(e) Now consider how to save the entire data (which is held in your data
structure) onto a (sequential) file. Write procedure to do the job. Give a
time analysis of this algorithm too.
(f) Describe briefly the following procedures:

(1) How shall you create an initial data structure (starting with some
amount of information)?
(2) How do you reconstruct your data structure from the backup file?
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 365

23. Write a program which will differentiate a given differentiable function f (x)
with respect to x. Here input is f (x) and print the output in a suitable format.
24. Write a program to find the k smallest elements in an array of length n. What
is the time complexity of your program? For what value of k does it become
advantages to sort the array?
25. Write a program to find the length and smallest elements in an array. Can
this be done in fewer than 2n − 3 comparisons?
26. Write a program to find the mode (the most frequently occurring element)
of a list of elements. What is the time complexity of your program?
27. An array contains only two types of objects viz. 1 and 2. Design a linear
time algorithm to sort the array. No extra storage is allowed.
28. Design an algorithm for sorting an array of elements with a O(n), where,
n = number of elements. [Hints: Use hashing technique].
29. [Division method] If maxtable is the maximum address size of a hash table,
then we can define a hash function

hash(key) = key mod (maxtable + 1)

where, key is key of a record to be stored in a hash table. Implement the hash
function.
30. [Multiplicative method] If a hash function returns 0 to m − 1 by an input
key. The mathematical formulation is given below:

hash(key) = trunc(m ∗ f rac(c ∗ key))

where, trunc is a function truncate the integer part of a real number 0 <

5−1
c < 1, f rac(x) = x − trunc(x), x = real and the good values of c = 2 or

5−1
1− 2 . Implement this hash function.
366 CHAPTER 24. PROBLEMS ON DATA STRUCTURE

31. [Mid-square method] If a table size is 00 to 99 then we can define a hash


function as
hash(key) = Mid(key ∗ key)

where, Mid(x) is a function which returns the middle two digit (since table
size 00 to 99). Write a general function of it.
32. [Folding method] Breaks up a key into several segments which are added
or exclusive ORed together to form a hash value.
Example : key = 01011 10010 10110,
index = 5 bit segment,
XOR of 01011, 10010, 10110 = 01111 = 15 = hash value.
Implement a general folding hash function.
33. [Combinations of multiplicative and folding method] Break up a key into
several segments and then apply a multiplicative hash function to each seg-
ment individually before folding. Implement this algorithm using the above
multiplicative and folding hash functions.
34. [Order preserving] Implement an order preserving hash function given be-
low:
hash(key) = key div c;
where, div = an integer division operator,
c = highest possible key or maxtable.
35. [Ordered minimal perfect hashing with single parameter]

(1) Let K = {k1 , k2 , · · · , kn } be a finite key set. There exists an integer c


such that h(k) = ⌈c/nk−1 ⌉ mod n is a perfect hash function.
(2) if k1 < k2 < · · · < kn then
n−1
c = (n − 1)nkn −1 − ∑ (n − i + 1)nki −1 .
i=2
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 367

Implement this algorithm and test with the example


K = {4, 11, 2, 9, 7} ⇒ K = {2, 4, 7, 9, 11} → {0, 1, 2, 3, 4}.

36. [Prime number hash function] If p(key) is a set of number for a given
set of keys where prime number function p(x) = x2 − x + 41 for 1 ≤ x ≤
40 such that key1 < key2 ⇒ p(key1) < p(key2) then the hash function is
defined as hash(key) = c mod p(key) where, c is a constant produced by an
algorithm for a given set of keys. Device an algorithm and implement the
hash function.
37. [Direct chaining] Implement the direct chaining method with search, inser-
tion and deletion a key. The method is given below :

Search: When a key is to be looked up, its hash address is computed and
then
(1) if that address is empty, the key has not been entered.
(2) if that address is occupied, search down the chain hanging from that
address; if the key is not encountered, it is not in the table.
Insertion: When a new entry is to be made, compute its hash address and
then
(1) if that address is empty, install the item there.
(2) if that address is occupied by the head of a chain, find an unallocated
cell in the scatter table by any technique whatever, and place the new
entry in the newly allocated cell. Then insert the new entry into the
chain hanging from the calculated address.
(3) if that address is occupied by an entry which is not the head of a
chain, i.e, by an entry which is not at its own calculated address, then
the old entry must be moved to another slot and the new entry inserted
in its place. Moving the old entry requires finding an empty slot for it,
placing it there, and updating the chain it is on.
368 CHAPTER 24. PROBLEMS ON DATA STRUCTURE

Deletion: The technique for deleting items entered by chaining is as fol-


lows:
(1) an entry not stored at its calculated address may be marked empty
and its former chain joined around it.
(2) an entry stored at its calculated address, but with no chain hanging
from it, may merely be marked empty.
(3) an entry stored at its calculated address with a chain hanging from it
must either be marked as deleted or one of the items on its chain must
be moved to the calculated address and the chain property fixed up.

(i) [Direct chaining with limited allocated memory] Implement the


above direct chaining algorithm with limited allocated memory for data
or information and separate header (i.e., addressed region) to be linked
with data.
(ii) [Separate chaining or direct chaining with a facilities for dynamic
(run time) memory allocation] Implement above algorithm with run-
time memory allocation for each record (i.e. New instruction in Pascal or
malloc in C).

38. [Late-insertion coalesced hashing (LICH)] Implement the following late-


insertion coalesced hashing (LICH) algorithm as it searches an M ′ -slot hash
table, looking for a given key k. If the search is unsuccessful and the table
is not full, then k is inserted. The size of the address region is M; the hash
function hash returns a value between 1 and M. For convenience, we make
use of slot 0, which is always empty. The global variable R is used to find an
empty space whenever a collision must be stored in the table. Initially, the
table is empty, and we have R = M ′ + 1; when an empty space is requested,
R is decremented until one is found. We assume the following initializations
have been made before any searches or insertions are preferred: M ← ⌈bM ′⌉,
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 369

for some constant 0 < b ≤ 1; EMPTY [i] ← true, ∀ 0 < i ≤ M ′ and R ←


M ′ + 1.

(1) [Hash] Set i ← hash(k). (Now 1 ≤ i ≤ M).


(2) [Is there a chain?] If EMPTY [i] then go to step 6 (otherwise, the ith
slot is occupied, so we will look at the chain of records that starts there.)
(3) [Compare] If k = KEY [i], the algorithm terminates successfully.
(4) [Advance to next record] If LINK[i] 6= 0, then set i ← LINK[i] and go
back to step 3.
(5) [Find empty slot] (The search for k in the chain was unsuccessful,
so we will try to find an empty table slot to store k). Decrease R one or
more times until EMPTY [R] becomes true. If R = 0, then there are no
more empty slots, and the algorithm terminates with overflow. Otherwise,
append the Rth cell to the chain by setting LINK[i] ← R; then set i ← R.
(6) [Insert new record] Set EMPTY [i] ← f alse, KEY [i] ← k, LINK[i] ←
0, KEY [i] ← k, LINK[i] ← 0 and initialize the other fields in the record.

39. [Early Insertion Coalesced Hashing (EICH)] Implement the following


Early Insertion Coalesced Hashing (EICH) algorithm given as: N = The
number of inserted records. M = The number of slots in the address region
of the hash table. M ′ = The number of slots in the hash table.
{Initializations}
R := M ′ + 1; M = ⌈bM ′⌉; {0 < b ≤ 1}; table[i].empty := true ∀ 0 < 1 ≤ M ′;

i := j := k := hash(k); {compute hash function}


if not table[i].empty then
{search through the chain}
begin
repeat
370 CHAPTER 24. PROBLEMS ON DATA STRUCTURE

if k = table[i].key then return(successful,i);


if table[i].link = 0 then break;
i := table[i].link;
forever;
if i > M then j := i;
{At this point the search is unsuccessful,
so the record will be inserted}
repeat R := R - 1 until table[R].empty;
if R = 0 then return(overflow,0);
{Link the Rth slot to the end of the chain}
if R > M then j := k;
table[R].link := table[j].link;
table[j].link := R;
i := R;
end;
{insert the new record into the ith slot}
table[i].empty := false;
table[i].link := 0;
table[i].key := k;
Initialize the other fields of the new record;
return(unsuccessful,i);
The break command causes the flow of
control to leave the repeat loop.
Chapter 25
PROGRAMMING PROBLEMS WITH
DATABASE

Implement the following problems using Database .

1. Suppose we informally define the data in the database of a departmental


stores as follows:

(a) Each employee is represented by the data as: employee number, name,
address and the department he works for.
(b) Each department is represented by the data as: its employees, manager
and items sold.
(c) Each item sold is represented by the data as: its name, manufacturer,
price, model number (assigned by the manufacturer), and an internal item
number (assigned by the store).
(d) Each manufacturer is represented by the data as: are sites name, ad-
dress, items supplied to the store and their prices.

Give an entity-relationship (E-R) diagram for the database. Note that, some
information may be represented by attributes; other information may be rep-
resented by relationships. Also indicate: (1) a key for each entity set; and (2)
which relationships are one-one and which are many-one. Specify any as-
sumptions you make.
2. Suppose in an airline reservation system an updated list of all passengers of
a particular airplane flight is required. The master and transaction files both
are sequential. If following are the details of master and transaction record
keys, what should be the content of the updated master file and the error

371
372 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

report (if printed) in terms of record keys?


where the trans-
action codes have
Trans. Trans. Masters
the following
Code Key Key
meanings:
1 35 10
Transaction
2 50 20
code Meaning
1 60 30
1 Addition
3 80 40
2 Deletion
2 85 50
3 Updating
2 90 60
..
.
500

3. A construction company is mainly engaged in the construction of roads and


bridges. First is thinking of setting up a DBMS (database management sys-
tem) to keep track of the construction materials. Suggest and outline entity-
relationship model for the database, clearly specify any assumptions you
make.
4. The attached sample data provides all necessary information on suppliers (S
relation), parts (P relation), projects (J relation), and actual supplies made
(SPJ relation). The significance of an SPJ tuple is that the specified supplier
(SNO) to the specified project (JNO) in the specified quantity (QTY). Using
the given database, formulate the following queries for implementation:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 373

Sample data:
P relation
S relation
PNO PNAME COLOR WEIGHT
SNO SNAME STATUS CITY
P1 Nut Red 12
S1 Digital 20 Bombay
P2 Bolt Green 17
S2 HCL 10 Bangalore
P3 Screw Blue 17
S3 SUN 30 Bangalore
P4 Screw Red 14
S4 IBM 20 Bombay
P5 Fan Blue 12
S5 Wippro 30 Calcutta
P6 Cable Red 19
J relation SPJ relation
JNO JNAME CITY SNo PNo JNo Qty.
J1 CD Driver Bangalore S1 P1 J1 200
J2 Key board Delhi S1 P1 J4 700
J3 Mother Board Hyderabad S2 p3 J1 400
J4 Modem Hyderabad S2 P3 J2 200
J5 Hard disk Bombay S2 P3 J3 200
J6 Monitor Delhi S2 P3 J4 500
J7 Mouse Delhi S2 P3 J5 600
S2 P3 J6 400
374 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

SPJ relation (cont.) SPJ relation (cont.)


SNo PNo JNo Qty. SNo PNo JNo Qty.
S2 p3 J7 800 S5 P5 J5 500
S2 P2 J2 100 S5 P5 J7 100
S3 P3 J1 200 S5 P6 J2 200
S3 P4 J2 500 S5 P1 J4 1000
S4 P6 J3 100 S5 P3 J4 1200
S4 P6 J7 100 S5 P4 J4 800
S5 P2 J2 1000 S5 P5 J4 400
S5 P2 J4 1100 S5 P6 J4 500
(1) Get full details of all projects.
(2) Get full details of all projects in Bombay.
(3) Get SNO value for suppliers who supply project J1.
(4) Get SNO values for suppliers who supply project J1 with part P1.
(5) Get JNAME values for projects supplied by supplier S1.
(6) Get COLOR values for parts supplied by supplier S1.
(7) Get SNO values for suppliers who supply both projects J1 and J2.
(8) Get PNO values for parts supplied to any project in Bombay.
(9) Get JNO value for projects supplied by at least one supplier not in the
same city.
(10) Get all (CITY, PNO, CITY) triples such that a supplier in the first city
supplies the specified part to a project in the second city.

5. A database for an order-entry system contains the following information


about customers, items and orders:
a) For each customer:
(1) Customer number (unique),
(2) Valid ship-to addresses (several per customer),
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 375

(3) Balance,
(4) Credit limit, and
(5) Discount.
b) For each order:
(1) Order number (unique);
(2) Heading information, i.e. customer number, ship-to address, date of or-
der; and
(3) Detail lines (several per order) each giving item, number and quantity
ordered.
c) For each item:
(1) Item number (unique),
(2) Manufacturing plants,
(3) Quantity on hand at each plant,
(4) Stock danger levels for each plant, and
(5) Item description.
For internal processing reasons a quantity outstanding value is associated
with each detail line of each order. This value is initially set equal to the
quantity of the item ordered and is progressively reduced to zero as partial
shipments are made.
Draw an entity-relationship diagram for the database. Suggest a tabular im-
plementation giving the column headings of each table. Clearly specify all
primary keys.
6. The Goodnight Hotel has five hundred rooms. Its room types include sin-
gles, doubles and suites. The hotel often books rooms a year in advance.
Rates vary according to the category of customer. There are separate rates
for group, government and standard categories.
Business has increased dramatically in the past few years. The hotel’s reser-
376 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

vation procedures are inefficient, and the present paper system can no longer
handle the volume of reservations. Many rooms remain unsold because of
cumbersome cross referencing methods. The Goodnight Hotel, therefore,
needs a systems to manage and control its resources.
The front office that handles the hotel’s reservations must support the fol-
lowing tasks:

• Controlling rooms inventory: The hotel must know at all the times in
which rooms are reserved and which are available for allotment. This is a
requirement of reservation function.
• Managing and controlling bills: The hotel must be able to compute
charges and prepare customer’s bill for services. This requirement comes
from the billing function.
• Determining effectiveness of advertising and sales force: By analyzing
the types of rooms sold and the types of customers reserving them, the
sales force can determine the correct sales emphasis. The billing function
records data for this output.
• Identification of established customers: Keeping track of past transac-
tions shows which customers are likely to return for repeat business. This
data is available from the customer or customer history function.
• Identifying market mix: The hotel studies the rate of government, com-
mercial and regular customers to determine its attractions and future sales
approaches. Information about such hotel transactions comes from the
reservation function.
• Determining effective and attractive room type mix: The reservation
or customer history function supplies information about relative demand
for each room type and its appeal to help determine room upgrades and
possible conversion to another type room.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 377

The reservation process involves the following steps:

• A customer calls on the Goodnight Hotel to reserve a room on a specific


date.
• The hotel request such information as: date, number in the party, name,
address, type of room desired, length of stay.
• The reservation clerk checks the inventory of available room type for the
date specified.
• If a room is available, the clerk tells to the customer about it’s rate.
• If the rate is acceptable, the hotel confirms the reservation.
• The clerk creates a record containing information collected from the cus-
tomer.
• The clerk starts a billing record to store all charges incurred during the
stay.
• The clerk reserves the hotel room and removes it from the inventory of
hotel rooms available during the time of the customer’s stay.

Draw a complete Entity-Relationship (E-R) diagram. Show clearly the rela-


tionship (one-one, one-many etc.). List all the relations. For each relation,
give the list of its attributes along with the key attribute(s).
Write database programs to answer the following queries:
(a) Find out the rooms of a particular type available between two given
dates.
(b) How much billing came from a particular type of room from Delhi-
based customer?
(c) Give the names and addresses of the customers along with their room
numbers who will be arriving next week.
7. A departmental library maintains a catalog of its books through a PC using
database software. For this purpose, it maintains a catalog file with a given
378 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

structure (below).
Using database you are required to do the following:
(a) Create a catalog file with given structure.
(b) Enter data for 8 records for the file using.
(c) Change the price of the first catalog record to Rs.450.00.
(d) Delete the catalog record for the book ’Advanced DBMS’ (say).
(e) Recover the record again and permanently delete the same record.
(f) List the price and title of the books whose year of publication is 2003.
(g) Find the books published from New York.
(h) Change all books for overnight issue and whose price is more than
Rs.300.00 to reference.
(i) List the books in reference section.
(j) Find the books purchased after 10.10.03.
Field Name Field Type Field Width
Author Character 30
Title Character 30
Subject Character 20
Publisher Character 10
Address Character 42
Year of publication Numeric 4
Number of copies Numeric 2
Overnight Logical
Reference Logical
Date of Purchase Date
Price Numeric 7.2
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 379

(k) Find the average price of all books published in the year 2003.
(l) Find the total number of books in reference section.
(m) Write a program which will accept the name of a book and will check
if the book is purchased at most four years back and report whether it is
for overnight issue or in reference. If the book is purchased before this
period, the program should give a message accordingly.

8. The Gofast company is involved in a car-rental business. Although the com-


pany owns a few cars most of its cars come from the outside owners. There
are different types of cars such as economic, luxury, two seaters etc. The
customer comprises of other companies, vacationing families, executives
on tours and tourists (both domestic as well as foreigner). The customer has
to produce his license (for Indians) or passport (for Foreigners) when the
cars are issued to them. The major functions of this business can be outlined
as follows:

• Keeping car inventory: The company must know all the times which cars
are reserved and which will be available for rental. This is a requirement
of reservation function.
• Maintaining contract with outside owner: Each time a car joins its in-
ventory, the company signs an agreement with the car-owner and keeps
the relevant information like car number, rate, date of return, address of
its garage, name and address of the car owner etc.
• Managing and controlling bills: The Company charges its rent from the
customer in advance. Extra amount is charged while returning the car, if
the car is returned after the due date or any damage is found. The Com-
pany also should be able to compute charges payable to the car owners as
per the contract.
380 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

• Keeping track of repairing: The company keeps the information about


the nature of break downs, duration and cost of repairing.

The reservation process involves the following steps:


When customer approaches for a car:
(1) A customer calls on Gofast to reserve a car on a specific date.
(2) The company request such information as: date, type of car required,
length of time, name, address.
(3) The reservation clerk checks the inventory of the available car type for
the date specified.
(4) If the car is available, the clerk tells to the customer about the rates.
(5) If the rate is acceptable, the company confirms the reservation.
(6) The clerk creates a record containing information collected from the
customer.
(7) The clerk prepares bills for the customer.
(8) The clerk reserves the car and removes it from the inventory of car
available during the time of its use.

When the owner approaches to let his car:


(1) The owner calls on Gofast to enquire about demand.
(2) If the company has any demand, it asks for mileage run, expected time
of availability etc.
(3) If the owner agrees, then it produces the car for physical inspection.
(4) If the company accepts, it goes for contract signing.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 381

List of queries:
(a) List the cars which are currently booked.
(b) Calculate the total bill amount on account of booking.
(c) What is the contract number for a given car.
(d) List the garages in Calcutta for luxuriates cars.
(e) List of cars issued on a given date.
(f) List of cars of economic type.
(g) Find the number of economic cars.
(h) How many contracts that has been signed this week?
(i) List of the contracts that were signed last month.
(j) Calculate and print out all amounts payable in the next week to the car
owners.
(k) Find out the utilization percentage in terms of days and the total mileage
run for a particular car.
(l) Find out the cars of a particular type available between two given dates.
9. A file has number of duplicates records on a certain key. Write a dbase pro-
gram which will print out all duplicates records and corresponding counts
of such duplicate records. You can assume very suitable structure to solve
this problem.
10. A database file (say, foxpro) has two address fields each of 70 characters
long. Print out the address in 30 column format. Minimum twenty five char-
acters must be written on each time. A hyphen (−) may be used for word
break in one of the length falls below 25 when rounded to word.
11. A file has a field name with first name at the beginning. Print out all names
with surname first.
12. A company has five department under each department there are 10 sections.
Records are stored in a file, with department as 2 digit code and section as 2
digit code. You have to print out a report which will count the total number
382 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

of employees in each section and each department. Your output will be in


sorted sequence of department and section. Do not use report format.
13. A file contains bill number as 1/89-90, 200/89-90 etc. To sort against the
financial year it has required to put the bill number as 89-90/001, 89-90/200.
Write a dbase program which will do the reversing bill number as above, you
can assume that bill maximum 4 digits long.
14. Calculate the income tax liability using income tax rule.
15. Draw a flow-chart and write a computer program with print layout design to
print a sales register in the following format:
XYZ & Co. Ltd. Page No : xxx
Cust Name/ Date Product Qunty Rate Value
No Addr
xxx xx...xxx xx.xx.xx xxx xx.xx xx.xx xxxxx.xx
xx...xxx xx.xx.xx xxx xx.xx xx.xx xxxxx.xx
x...xx
x...x
Total Sale : xx.xx
xxx xx...xxx xx.xx.xx xxx xx.xx xx.xx xxxxx.xx
xx...xxx xx.xx.xx xxx xx.xx xx.xx xxxxx.xx
x...xx
x...x
Total Sale : xx.xx

Grand Total: xxxxx.xx


Assuming that there is a master file named customer.dat and a transaction
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 383

file named salestran.dat whose layouts are described below:


customer.dat salestran.dat
Custno 6 Digits Custno 6 Digits
Custnm 25 Characters Date 6 Characters
Address1 20 Characters Product 3 Digits
Address2 15 Characters Qunty 6 Digits (4 + 2)
Address3 10 Characters Rate 4 Digits (2 + 2)
16. In a due date for casting problem of bills which are due next months are
projected on a tabular form. Assume a file contains the bill data as follows.
Assume bill are normally earned for 36 days.
Field Name ⇒ Bill No. Amount Bill Date Paid
Field Type ⇒ Numeric Numeric Date Logical

The table will be printed as follows:


Bill Amount Month Week2 Week3 Week4 Overdue
No.
January
5 525 Y
17 1000
19 Y
For example, bills raised on 01.04.98 will be due on 01.05.98. Bill already
overdue, due to the current due on the current date will be paid in overdue
also.
17. Big companies use rupee analysis when they withdraw sum from the bank
for their salary. A file contains the employee code and the total salary in a
file. You have to produce a report which will decomposed the salary into a
lowest possible denominate of rupees. The report must work like as follows:
384 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

Employee Total (Rs.) 100 50 20 10 5 1


Code
E0005 540 5 2
at the end you give of all denominations.
18. A file contains the scale, and number of increment in the job. Calculate
the present break pay. For example, a record in the file is: ‘250-25-650-30-
900 3’. A change in scale may be put not twice.
19. A gas dealer deals with various kinds of gases filled in different sizes of
cylinders for trading. The dealer has number of inventories located in dif-
ferent locations. The main branch of the office is located in Calcutta and
maintenance all its book-keeping on a computer. The customers are other
companies like cold storage, ice factory, refrigerator manufacturer etc. Em-
ploy cylinder may be owned by a customer or by the dealer. The business
can be outlined as follows:

• Maintenance of empty cylinder: At any point of time, the dealer is in-


terested in details of empty cylinder in its inventories. The information
required are cylinder number, owner, location and type of the cylinder.
• Monitoring of tested cylinder: Empty cylinders and the cylinders which
cross the expiring date are tested for leakage and any other damages at the
dealer’s inventory. If the test indicates any defect, it is marked as defec-
tive and the nature of defect is noted. The cylinder may subsequently be
repaired as scraped.
• Sending the tested cylinder to filling section: Tested and empty cylin-
ders are send to the filling station for refilling of gas. The information
collected at this point are expiring date, refiller name, address, refilling
date and gas memo.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 385

• Sale of filled cylinders: Filled cylinder are sold to customers. The cus-
tomer, after using it the empty cylinder back to the dealer. The information
collected are date of sale, customer name, address, type of cylinder and
the date of return.
• Calculation of rent: Rent of a cylinder is calculated at different rates
depending on the number of days. Normally there are 3 to 4 slab rates.
Note that, treats are calculated for dealer’s cylinder only.

The dealer has the following queries:


(1) How many of his cylinders were damaged during a specified period?
(2) What is the amount of rent receivable from a certain customer?
(3) How many filled cylinders have crossed the expiring date in dealers
inventory so that they may be retested?
(4) Customer-wise cylinder list.
(5) How many customer cylinders are in any inventory for more than a
specified period?
(6) Day-wise receipts of cylinder from customer and filling station.
(7) To execute on under from a customer it attempts to sale customer cylin-
der to the customers to minimize the rent. However one customer’s
cylinder can never go to other customer.
Draw an ER-diagram. List out the files with fields and key(s). Assume the
following question in database.
(a) Print out customer-wise rent bill for a certain month.
(b) Give all gas cylinders destination which are not on my inventory at
present.
20. A construction company deals with several construction projects. Each
project has a manager with good performance rating and a project is rep-
resented by project number, scheduled completion date, site, rupee value
and brief description of the project, several employees work in a project but
386 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

at any time an employee belongs to only single project. Each employee has
the details about his Idnumber, name, address and designation.
Items are used in projects. Each items has details of item number, descrip-
tion and quantity on hand. Separate information is maintained about quan-
tity of each item used in each project. There are many suppliers supplying
items. Every supplier has details about supplier number, name, address and
his rating. Separate information is also recorded about the quantity of each
item being supplied by each supplier and used in each project.
You are required to do the following:
(1) Identify entity sets and relationships.
(2) Specify the type of relationships between entity sets (give assumptions).
(3) Prepare an entity-relationship (E-R) diagram.
(4) Give a layout of data files with formats.
21. We would like to implement a GIS (geographic information system) for In-
dia. We are giving below a hypothetical division of India in different regions
and their interrelationship.
For administrative purposes, India is divided into a number of zones (e.g.
S, NE etc.), which are non-overlapping in area. Each zone consists of a
few states (once again non-overlapping in area). Each state in turn contains
a few districts, which again contains a number of blocks/city in area). A
block may further be subdivided into a number of villages. In short, the
strict hierarchical division of India (as a geographical region) is in the se-
quence: zone, state, district, block/city, village. Information, at each level,
to be maintained is as follows:
Zone : Name.
State : Name, capital, number of universities.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 387

District : Name, headquarter, area, number of colleges, average rain-


fall.
Block : Name, head office (location), Literacy(%).
City : Name, class, population, number of schools, literacy(%).
Village : Name, population, number of schools.
We are interested in processing a variety of query/data manipulation oper-
ations on this GIS. A few sample queries/manipulation operations are indi-
cated below:
Textual Queries:
(1) List states in a particular zone.
(2) List states along with their districts.
(3) List cities with very high literacy (e.g., 75%) along with their state
names.
(4) How many number of school villages are there in a particular state?
(5) List states with total area, population, number of universities, number
of colleges, number of schools, literacy, average rain fall.
(6) Give the state to which a particular city belongs.

Graphical Queries:
(1) Display a district of a state with its headquarters (with or without color),
also print all district names.
(2) Display a state (a) with/without district boundaries with its headquar-
ters, (b) with or without color for district/state.
Create a suitable database for the implementation of this system.
22. The pathology department of a cancer research hospital wants to maintain a
database of leukemia which is known to be either of myeloid or lymphoid.
In both cases a patient admitted to the hospital is tested for hemoglobin,
total and differential counts of blood cells in peripheral blood smear and
388 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

sometimes in bone marrow. This tests are conducted from time to time on
a patient to keep track of the progress of the disease apart from the count,
general characteristics of the cells such as, the average diameter, number and
size of the nuclei, color, and a qualitative feature called ‘look of the cell’ are
also recorded. At the same time clinical signs such as fever, tenderness of
glands, along with medication administered are recorded from time to time.
Create a relational database for the hospital.
23. Create a file of employee records when each record has the following fields:
Employee number, name, date of birth, salary, joining date, allow for the
following queries to the system:

(1) Retrieve and print all information corresponding to an employee of a


given name or given employee number.
(2) Retrieve the records corresponding to all employees whose birth date
is in between two specified years and write those records into a specified
field (to be inputed by the user).
(3) Update the salaries of all employees whose joining date is in between
two specified years (to be inputed by the user) by a given percentage. (The
original file has to be modified).
(4) Print a list of names of all employees whose birth date falls on a par-
ticular month (to be inputed from outside).

24. A car insurance company maintains a database for its customers to keep
track of the claims and their settlements. The company allocates a unique
customer number to each of its customers and maintains the name and ad-
dress of a customer against his customer number. The record of each car
insured with the company is retained with its year of manufacture, model
name and car number. One customer may own more than one car. Detail
record of claims for different accidents are also maintained by the company
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 389

where claim number, date of claim, date of settlement, amount claimed and
amount paid are recorded. For unsettled claims, the date of settlement and
amount paid attributes would store blank values. It has been assumed that a
customer always makes a claim in case of an accident.
Design a suitable database and draw its E-R diagram.
25. A socioeconomic survey has been done in a set of remote tribal villages to
study their agricultural practices. A village is identified by a name which
may be considered unique. Each village has certain number of houses iden-
tified by a house number. Each house belongs to a certain tribe like San-
thal, Munda, Onrao etc. In each house, the number of persons involved in
agriculture may vary. Some houses may have some non-agricultural income
also. A village has three types of lands defined as HF(highly-fertiled), MF
(moderately-fertile) and UF(unfertile). UF lands are used for raising fruit
trees only. Each plot of land is identified by a plot number, land type and
the cropping practice. Cropping practice signifies whether a land is used for
mono-cropping or multi-cropping (cultivated more than once a year). Vil-
lage authority for each village keeps an account of the crops cultivated in
that village in a year and the average yield for each of them in tons/acre.
Design a suitable database and draw its E-R diagram.
26. An organization involved in management consultancy maintains records for
its employees, departments and projects. The company has two types of em-
ployees; regular and part-time. Similar records are kept for both the types.
However, a regular employee gets a monthly salary for which basic-salary is
kept in the record, whereas for a part-time one a consolidated allowance is
paid and recorded. An employee is identified by his employee number. His
name, address, date-of-birth and date-of-joining are also recorded. Against
each employee company also maintains a list of dependents for providing
390 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

free medical facilities. Each employee is associated with only one depart-
ment and works in only one project. A department is identified by a unique
name. Project name is also unique. Each department has its own budget.
Against each project its cost estimate, starting date and an expected date of
completion are recorded.
The company runs a health center which is attend by part-time specialists.
For each attending doctor his field of specialization is recorded. Besides
this, a doctor is treated like any other part-time employee. Any employee
and his dependents can use the facility of the health center. Visits made
by the employees and their dependents to the health center are recorded in
chronological order. The number of patients treated by each doctor every
month is also recorded.
Design a suitable database and draw its E-R diagram.
27. ABC company limited is a project oriented organization, it is also very much
quality conscious. To serve its strive for quality it requires a lots of proce-
dures should be streamlined. Currently they are in process of automation of
the project quality assurance of the organization.
In each project there is one project leader (PL). Apart from that a project
manager is also attached to a project and he usually oversees more then one
projects. For big projects the project may be divided in different modules
where each of the modules will have one Module leader (ML). A project
may be executed in different phases according to the nature of the project.
A typical full life cycle project will have following phases:
(1) Strategy planning, (2) Analysis, (3) Design, (4) Construction, (5) Test-
ing, and (6) Implementation.
In each phase there may be number of work items. Usually each work item
is produces by only one team member. PL/ML prepares a schedule of work
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 391

items: (a) at which states, (b) which work item to be prepared by whom,
and (c) when it will be submitted to internal quality assurer (IQA). IQA
may be a designated person/team or may be anybody at any instance of time
designated by the PL/ML.
One work item is reviewed by one IQA at a time. PL/ML notes down the
actual date of submission, the person submitted and the person IQAing for
each work item. IQA person gives back the reviewed item with the review
report to the PL/ML, the date of which is also to be noted by PL/ML. Format
of review report is provided in Table 1 (below).
Errors are characterized as per severity i.e. major and minor. All errors and
suggestions are categorized according to their type like inconsistent, inad-
equate, typographical etc. These categories may be defined by the teams
also. There should be some list of standard causes for each of the errors like
oversight, lack of training etc.
The team member who prepared the document should take proper action on
the errors/suggestion and return it to the IQA. IQA will verify the changes
and then signed them off. This is known as document closing. The causes
of each error will be filled up by the person who has produced the docu-
ment. The date of returning to the IQA and the date of closing is also to be
tracked. IQA may return the document to the person even without closing
them returning date is also to be noted down.
This system provides lots of MIS to management to properly monitor the
progress and quality of the project. They are as follows:
Work item movement report: Which should have work item name, person
responsible, intended date of submission, actual date of submission, date of
return by IQA, sending date to IQA for closing date/returning date.
392 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

• Team member-wise work item detail,


• Person-wise work item review detail,
• Work items undergone more them one cycle for closing,
• Work item-wise summary of error severity categories of errors,
• Work items pending IQA,
• Work items pending closure,
• List of work items submitted to IQA but not IQAed,
• Work item-wise summary of causes,
• Project-wise summary of error severity and categories,
• Project-wise summary of causes.
Security methods should be taken care as of there are some classified in-
formation which can only be queried by PL/ML. There should be enough
queries to get information on quality of work item.
You have to prepare a requirement document, design document and con-
struct the code to fulfill the desire of top management of ABC Company
Limited.

Table 1 : Format
Format for review report
Project name :
Client name :
Document reviewed [with version] :
Document prepared by :
Document reviewed by :
Project Related Documents Referred :
Recommendations/Suggestions :
1 <TEXT>
Severity .... Category ....
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 393

Action Taken
By Date Cause
Closed by Date
2 <TEXT>
Severity .... Category .....
Action Taken
By Date Cause
Closed by Date

28. Write a program which will edit a file whose record contains address in-
formation to see if any obvious data entry errors are included. The records
contain the following information
Column Item Column Item
1-18 Last Name 60-65 Pin Code
19 First Initial 66-71 Date Subscription
Ends (Numeric)
20 Middle Initial 72-77 Account Number
(Numeric)
41-50 Town/City 78 Sex Code (Alpha-
betic)
51-59 State 79-80 Age
Check all columns that should contain alphabetic information to see if they
do, and check all columns that should contain numeric data to see if they
do. Print the contents of record that contain anything wrong. Columns 21-
40 cannot be checked, as they contain alphanumeric information.
Also print address labels, four across the sheet, of the form:
394 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

U.K. Bhattacharyya
C/20 New Garia
Kolkata, W.B. 700094
The program should include the periods after the first and middle initial, and
the comma after the city, as these characters are not on the data.
29. Every year the National Institute of Computer Science conducts an admis-
sion test for selection of candidates for their degree/diploma course in com-
puter science. The test consists of five groups (say, GK test, IQ test, Maths
test, Logic test, Figures) with twenty questions per group. The questions
are multiple choice type with four alternatives A, B, C, D per question. The
scoring pattern is 2 for a correct answer, 0 for no answer and −1 for an
incorrect answer. The final score is the total of the marks obtained by the
candidate in five groups. The first hundred candidates (in order of merit) are
issued call-letters for interview.
The institute wants to design a computerized result processing system that
would care the following:
(1) Entry and updating of candidates details.
(2) Entry of answers with validation checks on roll number and answers.
(3) Generation of final selection list.
(4) Query on total performance on a particular question (this may required
to remodel the scoring scheme), i.e., how many times a question is an-
swered correctly, or not attempted, or answered incorrectly.
Identify the necessary files, with the mention of the key-fields, non-key
fields and the organizations of the files. Implement the system.
30. Write a program to calculate grade point averages (GPA) for a group of
students. The input of the program should include the number of credit hours
for which a grade of A, B, C, D, or E was earned. The following grade points
are assigned.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 395

Grade A B C D E
Point 4 3 2 1 0
Incomplete grades are not included. If desired, you may extend this program
to produce class ranks, and a list in rank order.
31. A simple library information system of an educational and research institute
follow the following file structure.
Particulars Column
Subject code 1- 5
Particulars Column
First au- 6-15
Publisher 51-60
thor’s last
Year published 61-64
name
Cost (9999V99) 65-70
Second 16-25
Edition 71-75
author’s last
Catalogue number 76-80
name
Title of 26-50
book/ mono-
gram
The library contains the books mostly related to Statistics, Mathematics,
Computer Science, Biology, Physics, Chemistry, Geology, Economics etc.
discipline. Your are required to prepare your own sample data to test your
program which will do the following: (a) Count the number of books in
each discipline. (b) Print the names and other particulars of all books in
each discipline alphabetically. (c) Write the name and the author of the most
expensive book in your list. Modify the file structure so that it is possible to
list out the missing books from the library. Write a program to print out a
list of missing books.
396 CHAPTER 25. PROGRAMMING PROBLEMS WITH DATABASE

32. A file contains two types of records. Record-type = 1 indicates that it is a


salesman record. The layout is as follows:
Columns Fields Columns Fields
1- 6 Salesman number 41-42 Age
7 Record type 43 Sex
8-40 Salesman name 44-45 Years-in-sales
Each salesman record is followed by the customer record (record type = 2).
There is one record for each of the customers served by the salesman. The
layout of this record is as follows:
Columns Fields Columns Fields
1- 6 Salesman number 31-70 Customer
7 Record type Address
8-30 Customer name 71-80 Max credit
(in Rs.)
Create a database and program according to the following instructions: (a)
Describe the record for a record type 1 and then redefine the entire record to
describe this record type 2. (b) Describe just one record and redefine only the
portions that are not common in the two types of records. Now write down a
program if after reading a record you want to find out its type; which of the
two names (salesmen record type or customer’s record type) will you use to
test whether the record type is equal to 1 or 2.
33. Write a program which will accept master file and transaction file for depart-
ment store credit accounts. Assume that there will be a record in the master
file for all account numbers, and any number (even none) of transaction
records against on account number in the transaction file. A transaction may
represent a purchase or a payment. Data should be sequenced (or sorted) on
account number, with master cards preceding transaction card for each par-
ticular account number. The program should include a sequence check. If a
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 397

sequence error is found all remaining data cards should be listed on the out-
put sheet, but no further action should be taken. The output should include
at least the account number and account due.
34. Create a database and draw a flow-chart and writea program with print lay-
out design to print a sales register in the following format:
XYZ & Co. Ltd Page No : xxx
Sales Register for the month of xxx...xxx
-------------------------------------------------------------
Cust No Name/Address Date Product Qunty Rate Value
-------------------------------------------------------------
xxxxxx xxxx ...xx xx.xx.xx xxx xxxx.xx xx.xx xxxxxx.xx
xxxx ...xx xx.xx.xx xxx xxxx.xx xx.xx xxxxxx.xx
xxxxxxx
xxxxx
Total Sale: xxxxxx.xx
xxxxxx xxxx ...xx xx.xx.xx xxx xxxx.xx xx.xx xxxxxx.xx
xxxx ...xx xx.xx.xx xxx xxxx.xx xx.xx xxxxxx.xx
xxxxxxx
xxxxx
Total Sale: xxxxxx.xx
Grand Total xxxxxx.xx

Assume that there is a master file named “CUSTOMER.DAT” and a trans-


action file named “SALESTRAN.DAT” whose layouts are described below:
“CUSTOMER.DAT” layout “SALETRAN.DAT” layout
Custno 6 digits Custno 6 digits
Custnm 25 characters Date 6 characters
Address1 20 characters Product 3 digits
Address2 15 characters Quantity 6 digits (4 + 2)
Address3 10 characters Rate 4 digits (2 + 2)
Note: The ‘6 digits (4 + 2)’ in the above table means before decimal point 4
digits and after decimal points 2 digits.
Chapter 26
SOLVE PROBLEMS USING WORKSHEET

Implement the following work-sheet problems.

1. [Break Even Analysis] Suppose a company ABC Ltd. is producing only an


item X whose variable cost per unit (v) is Rs.2/-, its selling price per unit (s)
is Rs.3/- and company’s fixed cost ( f ) is Rs.500/- per month. Use excel and
find out the break-even quantity (q0 ) (for a month) by graphically and also
by computation (with the help of a formula f /(s − v), put into the work-
sheet). And also take care (in the design) the following changes.
(a) f = Rs.600/-, v = Rs.2/-, s = Rs.3/-, q0 = ?
(b) f = Rs.500/-, v = Rs.2.2/-, s = Rs.3/-, q0 = ?
(c) f = Rs.500/-, v = Rs.2/-, s = Rs.3.5/-, q0 = ?
(d) f = Rs.600/-, v = Rs.2/-, s = Rs.3.5/-, q0 = ?
2. Prepare a P/V (Profit/Volume) graph from the following data:
Unit produced : 60,000
Selling prices per unit : Rs.15
Variable cost per unit : Rs.10
Fixed cost : Rs.1,50,000
Show the expected sales on the graph when the profit to be earned is
Rs.87,500. Also find out the Break-Even Point. Solve this problem using
Excel .
3. [Materials: ABC analysis] Analysis the following items into A, B and
C categories on the basis of information given below, and prepare a report
showing your findings with comments.

399
400 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET

Category A : Rs.4,000 and above (total value).


Category B : Rs.1,000 to Rs.3,999 (total value).
Category C : Below Rs.1,000 (total value).
Sl. Part Qty. Rate
No. No. (Rs.)
1 345 147 3.00
2 400327 986 2.00
3 400358 353 4.00
4 194 8931 0.10
5 13 1239 0.15
6 157 100 0.25
7 1411 18 513.00
8 10119 3770 2.50
9 10059 683 2.00
10 10074 134 0.70
11 10075 190 0.40
12 10412 1 43.00
13 10429 52 0.70
14 11260 426 0.10
15 11474 4725 0.60
16 11550 10 30.27
17 14025 20 1.40
18 75533 6542 0.02
19 74335 329 0.40
20 72037 10 134.00
Solve this problem using excel. Write a generalized solution for a set of 20
items. So that the report and comments writes automatically.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 401

4. You are given the following data for the coming year of a factory.
Budgeted output 80,000 units
Fixed expenses Rs.4,00,000
Variable expenses per unit Rs.10
Selling price per unit Rs.20
Draw a break-even chart showing the break-even point. If the selling price
is reduced to Rs.18 per unit, what will be the new break-even point? Verify
the results by numerical computation. Solve this problem using Excel.
5. Compute the direct cost of a job A from the following data using excel.
Time employed in hours
Day Worker X Worker Y
Monday 10 8
Tuesday 9 10
Wednesday 10 11
Thursday 11 10
Friday 6 5
Saturday 6 4
(a) Normal working hours on week days are 8 hours and on Saturdays 4
hours.
(b) Overtime is paid for at double normal rates.
(c) Normal daily wages for X = Rs.3.00 and for Y = Rs.4.00.
(d) Four hours work on Saturdays paid for at full days wages. Work on
Saturday in excess of 4 hours is treated as overtime and is paid for at
1.5 normal wages upto a total of 8 hours work and beyond that at double
the normal rate.
(e) D.A. has to be added to the total wages including overtime at 50% of
wages.
402 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET

6. ABC Company is an one product company manufacturing and selling


lighter. The lighter are priced at Rs.12/- each, with variable cost being Rs.7/-
per unit. Fixed costs are Rs.500/- per month. The objective of this exercise
is to carry out a break-even analysis using excel in steps as follows:
(1) Obtain a profit-volume chart showing possible monthly sales between
50 and 500, with corresponding total contribution and profit/loss per
month.
(2) Calculate the break-even volume of no profit no loss basis.
(3) Confirm the result obtained in step (2) from a graph (drawn with the
help of GRAPH command).
(4) Change the following parameters to see its effect on the break-even
volume. (a) Change the fixed cost to Rs.450. (b) Change the variable
cost to Rs.7.50, keeping the fixed cost at Rs.500.
Note:
Unit contribution = unit price − unit variable cost.
Total contribution = unit sales × unit contribution.
Profit = total contribution − fixed costs.
Break-even volume units = fixed costs / unit contribution.
7. A company manufactures four size of the product Modern Model called
A, B, C and D in the department. The workers are paid the price rate of
Re.1.00, Rs.1.50, Rs.2.00 and Rs.3.00 per unit of the product size A, B, C
and D respectively. Dearness allowance paid to the workers is Rs.4.00 per
day. Miscellaneous payments are 20% of the basic wages.
From the following information for the month of January, you are required
to find the total cost per units of each size of the product Modern Model
using excel.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 403

Product
Size A Size B Size C Size D
Direct labor (Days) 104 78 52 52
Production (units) 320 150 70 55
Direct material (Rs.) 250 150 100 125
Overhead Expenses
Indirect material : Rs.500,
Indirect labor : Rs.572,
Indirect expenses : Rs.429.
8. The annual accounts of a trading company are to be made up to December
31 but it was not possible to carry out a stock-taking until January 5 at which
date stock was valued at cost at Rs.68,567.
The following transactions took place between 1st and 5th January.
Rs.
Goods received 4,600
Goods returned 200
Sales 10,500
Returns by customer 625
The rate of gross profit is 25% of cost.
Prepare a statement to show the valuation of stock as at December 31. Write
a generalized solution using excel.
9. Following information gathered from cost records of an industrial unit pre-
pare necessary accounts in the cost ledger using excel.
Opening Closing
balance balance
(Rs.) (Rs.)
Work-in-progress 3,800 2,500
Materials 22,000 15,000
Finished stock 17,000 32,000
404 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET

Transactions during the period:


Material purchased 58,000
Direct labor wages 21,000
Electricity charges 20,000
Factory overhead expenses incurred 27,000
Factory overhead expenses applied to production 26,000
Selling distribution and administration expenses 28,000
Selling distribution and administration charged
to finished stock sold 29,000
Sales 1,86,000

10. An Engineering company undertakes a long term contract which involves


the fabrication of prestressed concrete blocks and the erection of the same
on consumer′ s site.
The following information is supplied regarding the contract which is in-
complete on at the end of the financial year.
Cost incurred: Rs.
Fabrication cost to date
Direct materials 2,80,000
Direct labor 90,000
Overheads 75,000
4,45,000
Erection cost to date 15,000
Total 4,60,000
Contract price 8,19,000
Cash received on account 6,00,000
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 405

Technical estimate of work


completed to date
Fabrication:
Direct materials 80%
Direct labor and overheads 75%
Erection 25%
You are required to prepare a statement for submission to the management
indicating: (a) The estimated profit on the completion of the contract. (b)
The estimated profit to date on the contract.
Solve this problem using excel. A generalized solution is necessary.
11. [Cash budgeting problem] A monthly cash budget for XYZ Company is
to be prepared for the months January 1999 to June 1999. The present time
point is ended-December 1997.
Sales: XYZ’s total sales in November 1998 and December 1998 are
Rs.300,000 and Rs.350,000 respectively. The monthly sales forecast for six
months in 1999 are given below in Table 1.
Table 1 : Sales Forecast (Rs. in thousand)
Month Jan Feb Mar Apr May June
Sales forecast 250 200 250 300 350 380
About 10% of total sales in a month is cash sales. Of the credit sales (90%
of monthly sales) receivables, about 90% are collected one month from the
date of sale, and about 10% are collected two months from the date of sale,
with no bad-debt losses.
Disbursements : Given the sales forecasts, a production schedule has been
established. The production program calls for manufacture of goods in the
month prior to the month of sale. It is assumed that there is a one-month lag
between the time of a purchase is made and the time of actual cash payment.
406 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET

The schedule of expenses is given below in Table 2.


Table 2: Schedule of Operating Expenses
(Rs in thousand)
Month Dec Jan Feb Mar Apr May June
Purchase 100 80 100 120 140 150 150
Cash payment
for purchase – 100 80 100 120 140 150
Wages paid – 80 80 90 90 95 100
Other expenses – 50 50 50 50 50 50
In addition to operating expenses, cash disbursements are necessary for
planned capital expenditures, dividends, income taxes etc. Table 3 provides
the schedule of such disbursements.
Table 3: Schedule of Additional Cash Disbursements
Month Jan Feb Mar Apr May June
Capital expenditure – 150 50 – – –
Dividend payable – – 20 – – 20
Income taxes 30 – – 30 – –
Obtain a cash budget for the months January 1999 to June 1999 that will in-
dicate for each month total cash receipts, cash disbursement, net cash flow,
beginning cash (without financing) and ending cash (without financing) bal-
ance. Assume Rs.100,000 as the beginning cash balance in January 1999.
12. [Projected profit-loss account] Mr. Make Money is proposing to start a
business which will manufacture and sell automobile horns. He is currently
preparing the feasibility report to be submitted to lend fund limited which
provides loans to entrepreneurs.
The data which follow give the assumptions of Mr. Make money regarding
the operational details of his proposed venture.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 407

(1) Sales quantity: 500,000 units in the first year with a possible growth
rate in between 2% and 4% per annum for the subsequent years.
(2) Selling price: Rs.20 for the first year with a possible growth rate in
between 3% and 6% per annum for the subsequent years.
(3) Discount: A discount 1.5% on sales value is to be provided.
(4) Direct material: Rs.12 per unit in the year and 3 to 6% per annum
growth for subsequent years.
(5) Direct labor: The factory labor operates on a piece rate basis at Rs.2
per unit for the first year and a 2% increase thereafter.
(6) Maintenance: Assumed to be fixed at Rs.50,000 per annum.
(7) Quality control: Assumed to be fixed at Rs.25,000 per annum.
(8) Marketing expenses: Fixed at Rs.10,000 per annum.

Mr. Make Money expects the initial cost of plant and machinery to be Rs.2.5
lakhs with a possible variation of 10% on both sides. The plant and machin-
ery will be depreciated on a straight line basis over a period of 20 years.
The proposed capital structure is as follows:
Equity : Rs.100,000.
Long-term loans : Rs.200,000 @15% per annum.
The loans are not to be repaid in the planning horizon. Sales and material
purchases are on cash basis.
Raw material inventory of 2 months average consumption and finished
goods inventory of 1 month average sales are to be maintained. These are to
be financed by short term loans taken at 20% per annum.
Corporate tax rate is 60%. Prepare worksheet for the profit and loss (P/L)
statements for the next 5 years for Mr. Make Money’s business.
408 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET

Draw a bar graph showing the net sales over the 5 years. Draw a pie chart
showing break up of the net sales into various costs and profits. Carry out a
sensitivity analysis by varying the assumptions.
13. The experimental results of a template matching thinning algorithm is given
below:
Image No. of processor (P) used for Speed up value
Size Vector Processor 1 2 3 4 5 6 7 8
1600 1.45 0.85 1.70 2.50 3.10 3.50 4.20 4.80 4.80
5184 1.95 0.90 1.80 2.66 3.40 4.00 4.70 5.20 5.90
10816 2.25 0.94 1.85 2.70 3.58 4.42 5.10 5.80 6.50
18496 2.40 0.96 1.90 2.78 3.65 4.53 5.27 6.00 6.80
28224 2.60 0.96 1.93 2.81 3.70 4.62 5.32 6.20 7.00
40000 2.65 0.97 1.94 2.83 3.75 4.66 5.38 6.30 7.10
53824 2.75 0.97 1.95 2.85 3.79 4.70 5.56 6.40 7.30
69694 2.80 0.97 1.95 2.87 3.80 4.72 5.60 6.50 7.35
87616 2.85 0.97 1.96 2.88 3.81 4.73 5.65 6.52 7.40
107584 2.90 0.98 1.96 2.89 3.82 4.75 5.70 6.55 7.50
129600 2.93 0.98 1.97 2.90 3.85 4.80 5.71 6.60 7.55
153664 2.95 0.98 1.97 2.91 3.87 4.80 5.72 6.65 7.60
179776 3.00 0.98 1.97 2.93 3.88 4.80 5.73 6.70 7.61
207936 3.01 0.99 1.97 2.94 3.89 4.80 5.74 6.71 7.62
238144 3.05 0.99 1.97 2.95 3.90 4.80 5.75 6.72 7.65
270400 3.10 0.99 1.97 2.95 3.90 4.80 5.80 6.73 7.70
This result fit a specific pattern of curves
S p (P, N, I) = P(1 − be−c log10 N )
where, S p = Speed-up values, P = Number of processor, N = Image size,
I = Number of iteration to the thinning process, c = Constant, and b = A
function of P most likely to be a parabola or a straight line.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 409

Compute the parameters using excel. Also study the effects of the speed-up
values with the number of processor for a fixed image size and visa-versa.
If possible, suggest a better expression?
14. Pictorially study the effect of mean (m) and standard deviation (σ ) of a nor-
mal distribution  2
1 x−m
− ,
N(x, m, σ ) = √
1
e 2 σ − ∞ < x < ∞.
2πσ 2
Draw a smooth curve for other statistical distribution: (1) Binomial distribu-
tion, (2) Poisson distribution, (3) Gamma distribution, (4) Beta distribution,
(5) t−distribution, (6) F−distribution and (7) Chi-square distribution.
15. Suppose the experimental results of template matching thinning algorithms
are shown in Table 1. On observation of the experimental results, a negative
exponential function f (t) can be the possible number of matching at the ith
iteration. The f (t) as follows.
f (t) = b exp(−wt + d(1 + t)2 + c)
where, b is a constant in the case (1) Zhang and Suen (ZS), (2) Holt et al.
(H+) and (3) Pal and Bhattacharyya (PB) algorithms. But b is a function of
t for Chain et. al.’s algorithm (C+). Again the parameters c and d are con-
stants for these algorithms. The values of b, c and d are shown in Table 2
(below).
The above mathematical function has been used to compute the percentage
(%) of matched elements occurring at different iterations. These results are
shown in Table 3. It is interesting to note that the computed results (Table 3)
are very close to the experimental results (Table 1).
Verify these results by excel. Also show the deviations of experimental and
estimated values by graphs. Can you give better estimated values by modi-
fication of the parameters of the function f (t).
410 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET

Table 1 : Average % of matched elements in the cycles


Algorithm Cycle
1 2 3 4 5 6 7
Zhang and Suen 6.0920 1.1653 0.1712 0.0349 0.0064 0.0008 0.0000
Chain et. al. 5.5059 1.5890 0.5351 0.1948 0.0698 0.0249 0.0092
Holt et al. 6.7958 0.6754 0.0725 0.0088 0.0006 0.0001 0.0000
Pal and Bhattacharyya 7.3009 0.6179 0.0722 0.0093 0.0002 0.0000 0.0000
Table 2: Parameters of f (t) for different
thinning algorithms
Algorithm Constants
b c d w
Zhang and Suen 6.64 -0.085 -0.010 3
Chain et. al. 9.37 × 2t−1 0.180 -0.020 3
Holt et al. 7.36 -0.001 -0.070 4
Pal and Bhattacharyya 7.78 0.002 -0.060 5
Table 3 : Average % of matched elements in the cycles
Algorithm Cycle
1 2 3 4 5 6 7
Zhang and Suen 6.0383 1.0367 0.1745 0.0288 0.0046 0.0007 0.0001
Chain et. al. 5.4979 1.8321 0.5866 0.1804 0.0533 0.0151 0.0041
Holt et al. 6.8555 0.7521 0.0717 0.0059 0.0004 0.0001 0.0000
Pal and Bhattacharyya 7.3416 0.6554 0.0519 0.0036 0.0002 0.0000 0.0000

16. The successful (CN ) and unsuccessful (CN′ ) search performance (without cel-
lar) for different chained hashing algorithms are given below:

(1) Bucket Chaining:


a
CN = 1 + , CN′ = a + e−a , 0 ≤ a ≤ 1.
2
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 411

(2) Late-Insertion Standard Coalesced Hashing (LISCH)


1 −2a  a
CN = 1 + e − 1 − 2a + ,
8a 4
1 2a
CN′ = 1 + e − 1 − 2a , 0 ≤ a ≤ 1.

4
(3) Early-Insertion Standard Coalesced Hashing (EISCH)
1 1
CN = (ea − 1), CN′ = 1 + e2a − 1 − 2a , 0 ≤ a ≤ 1.

a 4
(4) Double Linked Insertion Standard Coalesced Hashing (DISCH)
a a2 1
CN = 1 + + , CN′ = 1 + a2 , 0 ≤ a ≤ 1.
2 6 2
The performance are not easily understandable from these relations. The
pictorial presentation of CN and CN′ can be easily understandable within the
range of a. Draw a smooth pictorial view for each of them. Compair their
performance.
17. The successful (CN ) and unsuccessful (CN′ ) search performance (with cellar)
for different chained hashing algorithms are given below:

(1) Bucket Chaining


a
CN′ = a + e−a , CN = 1 + , 0 ≤ a ≤ 1.
2
(2) Late-Insertion
 a Coalesced Hashing (LICH)
 − a


 e b + , if a ≤ yb,

 b
a
 
CN = 2( − y)
 
1 1 2 1 a 
+ e b −1 3 − + 2y − − y , if a ≤ yb.

  

b 4
 b 2 b
 a

 1 + , if a ≤ yb,
 2b 
a

 
b  2( − y)
 a   
2


CN = 1 + 8a e b −1−2
b
− y  3 − + 2y
b


  
1 a  1 b


+ +y + y 1−y , if a ≤ yb.


4 b 4 a
where, y is the unique non-negative solution to the equation
1
e−y + y = .
b
412 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET

(3) Early-Insertion
 a Coalesced Hashing (EICH)
−b a
e + b, if a ≤ yb,


CN′ = 1 2( ab −y)
4 e (3 − b2 + 2y)

 ( ab −y) 1

+e ( b − 1) + 14 (1 − 2 ab + b2 ), if a ≥ yb.


1a
1 + 2 b, if a ≤ yb,


a
CN = 1 + 21 ba + ba [(e b −y − 1)(1 + y)−


1 a a
2 ( b − y)(2 + y + b )], if a ≥ yb.
where, y is the unique non-negative solution to the equation
1
e−y + y = .
b
(4) Varied-Insertion
 a Coalesced Hashing (VICH)
−b a
e + b, if a ≤ yb,


a
CN′ = b1 + 14 (e2( b −y) − 1)×


(3 − 2b + 2y) − 21 ( ba − y), if a ≥ yb.




 1 + 12 ba , if a ≤ yb,
 1 + 1 a + b [(e( ab −y) − 1)(1 + y)


2b a
CN =


 − 21 ( ba − y)(2 + y + ab )]
 a
+ a [( b − y) − (e( b −y) − 1)], if a ≥ yb.
 1−b a

where, y is the unique non-negative solution to the equation


1
e−y + y = .
b
(5) Double
 Linked Insertion Coalesced Hashing (DICH)
 e− ab + a , if a ≤ yb,
b
CN′ =
 1 + 1 a ( a − 2 + 2) − 1 y(2 − 2 + y), if a ≥ yb.
b 2b b b 2 b


1a
1 + 2 b, if a ≤ yb,


CN = 1 + 21 ba + 16 ( ba )2 − 12 ba ( 1b − 1) − y( 2y − 1b + 1) + 13 y3 ab


− 12 y2 ab ( 1b − 1), if a ≥ yb.

COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 413

where, y is the unique non-negative solution to the equation


1
e−y + y = .
b
Draw a smooth curves for each of CN and CN′ by varying a (0 ≤ a ≤ 1) for
a particular value of b (0 ≤ b ≤ 1) for the comparative study of chained
hashing (with cellar) methods.
18. [Flowering model] In a laboratory some experiments are conducted to
study the effect of water pollutants (e.g. PbCl2, PMA, Hg2Cl2 , HgCl2 ,
CdCl2 ) on pollen tube morphology and germinability of the aquatic weeds.
The experimental results are shown below in Table 1.
Table 1: Average Flowering Time (Experimental)
Treatment Flowering Time (days)
(hours) PbCl2 PMA Hg2Cl2 HgCl2 CdCl2
0.5 10 10 17 14 18
1.0 12 15 20 17 22
3.0 18 20 26 24 26
6.0 24 24 28 27 30
12.0 30 27 37 33 36
24.0 34 36 44 41 44
48.0 38 40 46 43 48
72.0 44 44 52 49 55
This experimental results (Table 1) satisfies an empirical relationship as
shown below.

 a + b(1 − e−| f (t)| ), if t ≤ t ,
d
F(t) =
 ∞, if t > td ,
where, t = Treatment time in hours, F(t) = Flowering time in days, a =
Constant, related to the fresh water flowering time, b = Constant, td = Time
taken in days after treatment to death the plant without flowering, f (t) =
414 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET

Polynomial of t whose degree either 1 or 2.


Table 2: Average Flowering Time (using Model)
Treatment Flowering Time (days)
(hours) PbCl2 PMA Hg2Cl2 HgCl2 CdCl2
a 4.00 4.00 10.00 6.00 10.00
b 38.00 40.00 44.00 42.00 46.00
m 0.08 0.08 0.08 0.08 0.10
c 0.16 0.16 0.16 0.16 0.14
0.0 4.0 4.0 10.0 6.0 10.0
0.5 10.9 11.2 18.0 13.6 18.0
1.0 12.1 12.5 19.4 15.0 20.0
3.0 16.5 17.2 24.5 20.0 26.4
6.0 22.0 22.9 30.8 26.0 34.0
12.0 29.6 30.9 39.6 34.3 44.0
24.0 37.2 39.0 48.5 42.7 52.4
48.0 41.3 43.2 53.2 47.2 55.7
72.0 42.0 43.9 53.9 47.9 56.0
Also you can observe that the polynomial f (t) satisfies some properties or
it can bedefined as follows:
 0,

 if t = 0,
f (t) = mt + c, if 0 < t ≤ td ,

∞,

if t > td ,

where, m and c are constants.
Test these results (Table 2) using excel. Can you suggest better model for
the study.
Chapter 27
PROGRAMMING PROBLEMS ON IMAGE
PROCESSING

Digital image processing deals with only digital images. These are obtained
using different scanning devices and techniques such as (1) a digital camera
or a CCD (Charge-Coupled-Device) camera: it directly produces digital pic-
ture/image, (2) a scanner: it scans directly an object (document) or a picture to
form a digital image. Some other useful images are satellite images (using dif-
ferent kinds of sensors eg, PAN), medical images (using X-ray, CT scan, MRI
etc.), natural images (via digital camera) etc. In our study, images are avail-
able from different sources viz. internet or agency. Our objective is to process
visual and graphical information using computers with the help of computer
vision, graphics and image processing tools and techniques. Assume an image
frame is an integer matrix of size n × n. An element of this matrix is known as
gray value or intensity or magnetic field value that depends upon the sources
and the devices used to collect the image. This element is also known as pixel
(picture elements or pel).
Now implement the following image processing problems.

1. Suppose a scanner scanned a picture and formed a digital image. This image
is an integer matrix of size n × n (say), where the ranges of integer values
(i.e. matrix elements) depends on the specification of the scanning device.
Each element of the matrix indicates the intensity of the picture (known as
gray value) of the corresponding position (i.e., one-to-one correspondence
with the object and the picture). These values are stored in a file (known as
image file) with a particular format. Few rows of a sample scanned image

415
416 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

data of size 64 × 64 is given in the appendix of this chapter. Assume these


data are in a file, write a program to read these values from the file and also
write on a paper. Ensure that the reading and writing are properly done.
2. Write a program to compute the maximum (gmax ) and the minimum (gmin )
gray values from a given digital image M(i, j), i = 1, 2, · · · , u, j = 1, 2, · · · , v
and each M(i, j) lies between 0 to g, the range of gray value g depends on
the physical device.
3. [Frequency distribution] A digital image M(i, j), i = 1, 2, · · · , u, j = 1, 2, · · · , v
and each M(i, j) lies between 0 to g, the range of gray values. Write a pro-
gram to study the distribution of gray values (called histogram) in the image.
4. [Filter] Suppose the output of a scanning device is noisy due to (1) synchro-
nization problem of the device and/or (2) the input image itself noisy/dirty.
By using a filter, we can remove the noise upto certain level. A filter may
be a software or a hardware device. Suppose we have a good digital image
data. We want to test an image filtration algorithm, First add some noise
to the above image and use these image to test this filter algorithm. Write a
program that will add a random noise to a digital image. [Remember: Digital
image is a matrix of integers within a range].
5. [Histogram] Write a program to generate a smooth histogram for an image
and also find the position of peaks and valleys from a smooth histogram.
6. [Score computation] Write a program to compute a score for a histogram
of an image. The definition of score is as follows:
Np
W−
2Pk −Va −Vb Pk
score = ×
2Pk W
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 417

where,
Np = The actual frequency at the peak.
Pk = Computed regularized value at the peak k.
Va = Computed regularized value at the valley a.
Vb = Computed regularized value at the valley b
a, b = Consecutive two valleys (i.e., only one peak between this two
valley).
W = Width between two consecutive valleys a and b.
2Pk −Va −Vb
= Relative depth between two consecutive valleys.
2Pk
Np
W−
Pk
= Sharpness of the peak.
W
7. Write a program to find a peak and its corresponding valleys where criterion:
deeper valleys and the sharper peak are most desirable.
8. [Regularization] If Mu×v is a noisy image then the histogram does not looks
like a mixture of normal curves, or there exists some point of discontinuity
(or jump) in the histogram. So by regularization we can remove these spu-
rious picks and valleys, and smooth the curve. Since gray value are equi-
spaced, so we can regularize by the following algorithm. Implement this
algorithm and draw the curves.
Algorithm
fi = Zi − Xi fi+1 −Yi fi+2 , for i = n − 2, n − 3, n − 4, · · · , 2, 1
418 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

where,
fn−1 = Zn−1 − Xn−1 fn , fn = Zn
Bi
Xi = , i = 1, 2, · · · , n − 1
Ai
1
Yi = , i = 1, 2, · · · , n − 2
Ai
K1i
Zi = , i = 1, 2, · · · , n
Ai
Ai = (6 + h2 p) −Yi−2 + 4Xi−1 + Xi−1 Xi−2 , i = 1, 2, · · · , n
Bi = −4 + 4Yi−1 + Xi−2Yi−1 , i = 1, 2, · · · , n − 1
K1i = Ki − Zi−2 + 4Zi−1 + Xi−2 Zi−1, i = 1, 2, · · · , n
h = 1 = Difference between two consecutive gray levels.
p = Smoothing parameter.
Also X0 = 0, X−1 = 0, Y0 = 0, Y−1 = 0 Z0 = 0 and Z−1 = 0
9. The computer screen is a matrix of pixels (picture elements or pels). Each
pixel has two state: on and off, on represents an information otherwise no
information. Write a program to on the (i, j)th pixel on the screen.
10. [Halftonning: 3 × 3 pattern filling] Each element M(i, j), i = 1, 2, · · · , u
and j = 1, 2, · · · , v of a digital image M contains the gray value gi j in between
0 and 31. Now we shall convert this gray level image to its binary image.
Suppose the computer screen is a matrix of pixels with two states: on and
off. Here each gray value g = M(i, j), ∀ i, j ∈ {0..u, 0..v} converts to another
scale t where g ∈ {0, 1, · · · , 32} and t ∈ {0, 1, · · · , 9} as using
 the following

g
formula t = g mod 10, or t = Int((g/32) × 10) or t = Int ×10
1 + gmax
where, gmax is the maximum gray value of the image M. Substitute each t
by a 3 × 3 pattern (known as sicell) to its corresponding position given as
follows:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 419

0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0
0 0 0 0 1 0 0 1 1 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
(0) (1) (2) (3) (4) (5)
0 1 0 0 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
1 1 0 1 1 0 1 1 0 1 1 1
(6) (7) (8) (9)

3 × 3 pattern’s with value of t in () below each pattern as shown in the


above figure. Write a program to display the converted binary image of size
3u × 3v.
11. [Halftonning: 5 × 5pattern filling]  As in the above problem, if t =
g
g mod 26 or t = Int ×26 i.e., basically gray scale down from
1 + gmax
0 − 31 to 0 − 25 for a given image, where g is a gray value lies between 0
and 31 for an image M. The value of t can be replaced by the following 5 ×5
patterns to its corresponding position.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
(0) (1) (2) (3)
0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0
0 0 1 1 1 0 0 1 1 1 0 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
(4) (5) (6) (7)
0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 0 1 1 0 0
0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 1 0 0
(8) (9) (10) (11)
420 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

0 0 1 0 0 0 0 1 0 1 0 0 1 0 1 1 0 1 0 1
0 0 1 1 0 0 0 1 1 0 0 1 1 1 0 0 1 1 1 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0
1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0
(12) (13) (14) (15)
1 0 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 0 1
0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 1 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 1 1 1
1 0 1 0 0 1 0 1 0 1 1 0 1 0 1 1 0 1 0 1
(16) (17) (18) (19)
1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1
1 0 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 0 1
(20) (21) (22) (23)
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 0 1 1 1 1 1 1
(24) (25)

5 × 5 pattern’s with value of t in () below each pattern as shown in the above


figure.
Write a program to 5 × 5 pattern (given above) filling algorithm.
12. [Halftonning: direct threshold] The gray value of an image of size n × n
at any position (x, y) be g(x, y) where, x, y = 1, 2, · · · , n and gmin ≤ g(x, y) ≤
gmax . A threshold value (T h) on gray levels is supplied by the user or can
be computed as T h = 12 (gmax + gmin ) or average of all the gray values in
the image or the valley between two peaks of the histogram of the image.
Now apply this threshold on g(x, y) and it produce a binary image B(x, y) as
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 421

follows. 
 0 if g(x, y) < T h,
B(x, y) =
 1 if g(x, y) ≥ T h,
for x, y = 1, 2, · · · , n (say).
Write a program to implement the above algorithm and display the image.
13. [Halftonning: modulation] Modulates the intensity signal with another
signal S(x, y) whose values ranges from −T h to +T h with average value
zero. The pixel at (x, y) is made on (or white) if g(x, y) + S(x, y) ≥ T h oth-
erwise off (or black), where g(x, y) = gray value of the original image at
(x, y). T h = threshold value as input and S(x, y) = T h ∗ sin(ax) ∗ sin(by) in
which a and b are uniformly distributed random numbers. Write a program
to implement the above algorithm.
14. [Halftonning: order dither technique] A bilevel (i.e., binary) representa-
tion of continuous tone image is generated by using the gray value, g(x, y)
at (x, y) and a position dependent set of thresholds. The set of thresholds
contained in a n × n dither matrix Dn . For the pixel at a (k, l) position of the
image matrix, the threshold value Dn (i, j) which is at the (i, j)th position of
Dn , is selected provided
i = k mod n, and j = l mod n.
The decision to display white (i.e., 1) or black (i.e., 0) is taken as follows:
If g(k, l) ≥ Dn (i, j) then B(k, l) = 1 else B(k, l) = 0
where,   
n n n n
4D + D200U 4D + D201U
2 2 2 2 02
Dn =  n n n n
 , D2 =  
4D 2 + D210U 2 4D 2 + D211U 2 31
n×n 2×2

in D2 , D200 = 0, D201 = 2, D210 = 3 and D211 = 1;


422 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING
   
1 1 ... 1 0 8 2 10
   
 1 1 ... 1   12 4 14 6 
and U n =  D4 = 
   
 
 .. .. ... ..   3 11 1 9 
   
1 1 ... 1 15 7 13 5
n×n 4×4
Implement the above algorithm and display the image.
15. [Halftonning: constrained average method] In this method, first, the local
average intensity, Lavxy , in the 8-neighbors of g(x, y) is calculated. Next the
threshold T hxy is computed
 as: 
2f
T hxy = f + 1 − Lavxy ,
gmax
where f < T hxy < gmax − f and gmax = maximum of all the gray levels in
the image. The parameter, f , controls the apparent contrast of the output
image and f 6= 0 is required to control a gray scale in the output image. The
decision to display white or black is as follows:
If g(x, y) > T hxy then B(x, y) = 1 else B(x, y) = 0, where B is the binary
image. Implement the above algorithm and display the image.
16. [Halftonning: dynamic threshold] Input the lower and the upper cutoff
ranges of gray values as LOWER and UPPER respectively. Other two input
parameters are al pha and beta (say). Let M(x, y) be a digital (gray level)
image and B(x, y) be the converted binary image by the following procedure.
If M(x,y) < LOWER then B(x,y) = 0 else
If M(x,y) > UPPER then B(x,y) = 1 else
find out average of 8-neighbors is avg (say)
davg = alpha * avg;
DC = [M(x,y) - M(x-1,y)]/2 + [M(x,y) - M(x,y-1)]/2
If M(x,y) > beta * DC + davg then B(x,y) = 1 else B(x,y) = 0.

Write a program to implement the above logic, and run this program to find
out a suitable value of controlling parameters al pha and beta for a particular
image.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 423

17. [Halftonning: error distribution method] A gray value g(x, y) is selected


for display at (x, y) position and to distribute its error occurred due to the
3
threshold, to its four neighbors as follows: th of the error is propagated to
8
3 1
the right neighbor, th to the bottom neighbor and th along the two bottom
8 4
diagonals as shown below:
3
∗ (x, y)
8
1 3 1
4 8 4
where, ∗ is the processed element and (x, y) is the currently processing ele-
ment.
Write a program to implement the above algorithm and display the image.
[Assume: error can be calculated statistically from unprocessed four neigh-
bors and the image is processing sequentially according to the following
direction, row by row and left to right direction, starting from left top cor-
ner.]
18. [Halftonning: generalized error diffusion] Suppose Am×n is a normal-
ized digital image of a gray level image Mm×n where 0 ≤ A(i, j) ≤ 1
and 0 ≤ M(i, j) ≤ gmax , gmax is the maximum gray value in the image,
i = 1, 2, · · · , m and j = 1, 2, · · · , n. B(i, j) ∈ {0, 1} ∀ (i, j) ∈ {1..m, 1..n} is
generated by the application of a threshold on the normalized digital image
Am×n . The 8-neighbors is shown below.
j−1 j j+1
i−1
i ∗ a
i+1 b c d
where, ∗ is the currently processing element and (a, b, c, d) is the error dis-
tribution to their corresponding positions.
Now the conversion is as follows:
424 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

for i := 1 to m do for j := 1 to n do
begin if A[i,j]<0.5 then B[i,j]:=0 else B[i,j]:=1;
err := A[i,j] - B[i,j];
A[i,j+1] := A[i,j+1] + err * a;
A[i+1,j-1] := A[i+1,j-1] + err * b;
A[i+1,j] := A[i+1,j] + err * c;
A[i+1,j+1] := A[i+1,j+1] + err * d;
end.
 
7 3 5 1
The error vector (a, b, c, d) = , , , is proposed by Floyd &
16 16 16 16
Steinberg (1975).
If a + b + c + d < 1 then this implies sometimes ghost images which is an-
other image found on the original image during display. Try to generate a
ghost image and report the error distribution vector (a, b, c, d). Implement
the above described algorithm.
Also implement the error distribution algorithms proposed by different re-
searchers with the following error distributions.
!
1 x ∗ 7
(a) Floyd and Steinberg (1975) : .
16
3 5 1
x x ∗ 7 5
 
1 
(b) Jarvis, Judice and Ninke (1976) : 3 5 7 5 3.

48
1 3 5 3 1
x x ∗ 8 4

1 
(c) Stucki (1981) : 2 4 8 4 2.

42
1 2 4 2 1
(d) Stevenson and Arce (1985):

 
x x x x 32 x
12 x 26 x 30 x 16 
 
1  .
200 
 x 12 x 26 x 12 x 

5 x 12 x 12 x 5
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 425

where, (a), (b) and (c) for rectangular grids and (d) for hexagonal grids. [∗
represents the origin and x not considered]
Give a comparative study of the algorithms.
19. [Halftonning: dot diffusion] Prof. Knuth conducted a matrix (intuitively)
like order dither matrix but entries are different in different positions but
numbers are distributed within the range 0, 1, · · · , 63.
Write a program to implement the following diffusion algorithm and display
the image.
for k := 0 to 63 do
for all (i,j) of class k do
begin if A[i,j]<1/2 then B[i,j]:=0 else B[i,j]:=1;
err := A[i,j] - B[i,j];
<distribute err to the neighbors of (i,j)
whose class numbers exceeds k>
end
and the clause <distribute err to the neighbors of (i,j)
whose class numbers exceeds k> can be written as
w := 0;
for all neighbors (u,v) of (i,j) do
if class(u,v) > k then w := w + weight(u - i,v - j);
if w > 0 then for all neighbors (u,v) of (i,j) do
A[u,v] := A[u,v] + err * weight(u - i,v - j)/w;
weight(x,y) = 3 - x*x - y*y

20. Write a program to print the displayed binary image on the screen using
print screen option.
21. Write a program to enlarge the size of an image (say, twice of the original
image) for display and also extend your idea for generalization.
22. Write a menu driven package for image display with its suitable printing
facilities and also store the previous screen. A number of rectangular image
frames are displayed sequentially on one screen, also you can rotate the
image frame as and when require. Erase the content of the screen when it is
426 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

full (for example, “Screen is full !”) and also provide a suitable message to
the user.
23. [Edge detection using 2 × 2 operator : Robert’s method] Robert sug-
gested two edge detection operators Rh1 and Rh2 of size 2 × 2. If Mn×n is
the original image then the 3 neighbors of M(i, j) and itself is denoted by
M, a 2"× 2 matrix as follows. #
M(i, j) M(i, j + 1)
M= ,
M(i + 1, j) M(i + 1, j + 1)
! !
0 −1 −1 0
Rh1 = , Rh2 = .
1 0 0 1
Now, we can define gi = M ⊗ Rhi , i = 1, 2 as g1 = 0 ∗ M(i, j) + (−1) ∗
M(i, j + 1) + 1 ∗ M(i + 1, j) + 0 ∗ M(i + 1, j + 1). Similarly we can com-
pute g2 . Now the edge information and its orientation is given by edge =
q
g21 + g22 or |g1 | + |g2 |. Supply a threshold value and check the follow-
ing. Decision: If edge ≥ T hreshold then edge found at (i, j) location i.e.
A(i, j) = 1 otherwise A(i, j) = 0, no edge information, where, A(i, j) is the
π g2
output edge image. Direction at (i, j) = + tan−1 . So we can compute
4 g1
these two information for all i, j = 1, 2, · · · , n. Implement this algorithm.
24. [Edge detection using 3 × 3 operator : Sobel’s method] Sobel suggested
two edge detection operators Sh1 and Sh2 of size 3×3. If Mn×n is the original
image then the 8 neighbors of M(i, j) and itself is denoted by M, a 3 × 3
matrix
 as follows.
M(i − 1, j − 1) M(i − 1, j) M(i − 1, j + 1)

M =  M(i, j − 1) M(i, j) M(i, j + 1)  and


 

M(i + 1, j − 1)
 M(i +
1, j) M(i + 1, j 
+ 1)
1 0 −1 −1 −2 −1

Sh1 =  2 0 −2 , Sh2 =  0 0 0 .
   

1 0 −1 1 2 1
Now, we can define gi = M ⊗ Shi , i = 1, 2 as g1 = 1 ∗ M(i − 1, j − 1) + 0 ∗
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 427

M(i − 1, j) + (−1) ∗ M(i − 1, j + 1) + 2 ∗ M(i, j − 1) + 0 ∗ M(i, j) + (−2) ∗


M(i, j + 1) + 1 ∗ M(i + 1, j − 1) + 0 ∗ M(i + 1, j) + (−1) ∗ M(i + 1, j + 1).
Similarly we can compute g2 . Now the edge information and its orientation
q
is given by edge = g21 + g22 or |g1 | + |g2 |. Supply a threshold value and
check the following. Decision: If edge ≥ T hreshold then edge found at
(i, j) location i.e., A(i, j) = 1 otherwise A(i, j) = 0, no edge information,
π g2
where, A(i, j) is the output edge image. Direction at (i, j) = + tan−1 .
4 g1
So we can compute these two information for all i, j = 1, 2, · · · , n. Implement
this algorithm.
25. [Edge detection] Implement the following edge detection methods.

(1) Robert′ s method


! (same as above problem)
!
0 −1 −1 0
Rh1 = , Rh2 = .
1 0 0 1
g1 = M ⊗ Rh1 and g2 = M ⊗ Rh2 .
q π g2
edge = g21 + g22 or |g1 | + |g2 | and angle = + tan−1 .
4 g1
(2) Sobel′
 s method 
1 0 −1 −1 −2 −1
 

Sh1 =  2 0 −2 , Sh2 =  0 0 0 .
   

1 0 −1 1 2 1
g1 = M ⊗ Sh1 and g2 = M ⊗ Sh2 .
q g2
edge = g21 + g22 or |g1 | + |g2 | and angle = tan−1 .
g1
(3) Prewitt′
 s method 
1 0 −1 −1 −2 −1
 

Ph1 =  1 0 −1 , Ph2 =  −1 −1 −1  .
   

1 0 −1 1 1 1
g1 = M ⊗ Ph1 and g2 = M ⊗ Ph2 .
q g2
edge = g21 + g22 or |g1 | + |g2 | and angle = tan−1 .
g1
428 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

(4) Isotropic
 method √
−1 0 1 −1 − 2 −1
  
 √ √ 
Ih1 =  − 2 0 2 , Ih2 =  0 0 0 .
 

−1 0 1 1 2 1
g1 = M ⊗ Ih1 and g2 = M ⊗ Ih2 .
q g2
edge = g21 + g22 or |g1 | + |g2 | and angle = tan−1 .
g1

(5) Chebyshev s operator
(a) 2 × 2 operator
! !
1 1 1 −1
C2 h1 = , C2 h2 = ,
1 1 ! 1 −1 !
1 1 1 −1
C2 h3 = , C2 h4 = .
−1 −1 −1 1
g0 = M ⊗C2 h1 , g1 = M ⊗C2 h2 , g2 = M ⊗C2 h3 and g3 = M ⊗C2 h4 .
q
edge = g21 + g22 + g23 or |g1 | + |g3 | and
g0 + g1 + 2g2
angle = tan−1 .
g0 − g1
(b) 3 × 3 operator
1 1 1 −1 0 1
   

C3 h1 =  1 1 1 , C3 h2 =  −1 0 1 ,
   

 1 1 1   −1 0 1 
1 −2 1 −1 −1 −1
C3 h3 =  1 −2 1 , C3 h4 =  0 0 0 ,
   

 1 −2 1   1 1 1 
1 0 −1 −1 2 −1
C3 h5 =  0 0 0 , C3 h6 =  0 0 0 ,
   

 −1 0 1  1 −2 1 
1 1 1 −1 0 1
C3 h7 =  −2 −2 −2 , C3 h8 =  2 0 −2 ,
   

 1 1 1  −1 0 1
1 −2 1
C3 h9 =  −2 4 −2  .
 

1 −2 1
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 429

g0 = M ⊗C
s 3 hi , i = 1, 2, · · · , 9
8 8
9 g5 − 2g3
edge = ∑ g2i or ∑ |gi| and angle = tan−1 8 g0 + 3g1
.
i=1 i=1

26. Display the following feature images measured over 3 × 3, 5 × 5, 9 × 9 and


16 × 16 windows of a 512 × 512 image: (a) mean, (b) median, (c) disper-
sion, (d) standard deviation, (e) entropy, (f) skewness and (g) kurtosis.
Repeat this experiment for different images and draw conclusions about the
possible use of these features in an image processing application.
27. [Binarization] If a raster image data contains only line information (i.e.,
map data) then a variable thresholding technique is necessary by which it
can preserve all the line information. In a parallel variable thresholding tech-
nique, the threshold for each image pixel n, for the window of size u × v,
is calculated for binarization using the following relation: T hreshold(n) =
{K(n) × StandardDeviation(n) + Mean(n)} f or n = 1, 2, · · · , M
where,
M = Row ×Column
= Total number of pixels in the frame,
K(n) = a ∗ Histogram(n)/M,
a = Constant,
Histogram(n) = Value of histogram at pixel n,
w
Mean(n) = ∑ P[i]/w, n is the center of the window
i=1
w = u × v = size of the window, and
P[i] = Gray level value of pixel i.
v " #
u1 w
u
StandardDeviation(n) = t ∑
w i=1
(P[i] − Mean(n))2 .
430 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

Write a program using above described method for binarization of an image


whose main information are line drawings such as engineering drawing and
cartographic map.
28. [Thinning: Zhang and Suen algorithm] Zhang and Suen proposed a par-
allel thinning algorithm for extracting the skeleton of a binary picture. This
process removes all the contour points except those are not belongs to a
skeleton. In order to preserve the connectivity of the skeleton, the algorithm
works as follows: consider a 3 × 3 window of a binary image as given be-
low:
P9 P2 P3
P8 P1 P4
P7 P6 P5
where Pi′ s are the pixels of the edge image.
They have considered two sub-iterations to preserve the connectivity of the
skeleton.
First sub-iteration
The contour point P1 is deleted from the digital pattern if it satisfies the fol-
lowing conditions:
(a) 2 ≤ B(P1 ) ≤ 6, (b) A(P1 ) = 1 (c) P2 ∗ P4 ∗ P6 = 0, (d) P4 ∗ P6 ∗ P8 = 0
otherwise P1 not deleted.

Second sub-iteration
The contour point P1 is deleted from the digital pattern if it satisfies the
following conditions:
(a) 2 ≤ B(P1 ) ≤ 6, (b) A(P1 ) = 1 (c) P2 ∗ P4 ∗ P8 = 0, (d) P2 ∗ P6 ∗ P8 = 0
otherwise P1 not deleted.
1 9 9
where, A(P1 ) = ∑ |Pi − Pi+1 |, P10 = P2 and B(P1 ) = ∑ Pi .
2 i=2 i=2
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 431

Algorithm
Pass I In this algorithm, a 3×3 window is applied on the given binary image
in left to right and subsequently top to bottom manner. At every position of
the window it is checked whether the central pixel (P1 ) is to be transformed
from 1 to 0. The necessary steps are shown below.
Step 1.1: Assuming that P1 be the central pixel then compute the following:
A(P1 ) = Number of ‘01’ patterns occurring in the ordered (clock-wise)
sequence P2 , P3 , · · · , P9 , P2 of 8-neighbors of P1 .
B(P1 ) = Number of 1’s among the 8-neighbors of P1 .
Step 1.2: If A(P1 ) = 1 and 2 < B(P1 ) < 6 then check whether at least one of
the following conditions is true or false:
(1) the pixel at north (P2 ) and the pixel at west (P8 ) are both zero,
(2) the pixel at east (P4 ) is zero,
(3) the pixel at south (P6 ) is zero.
If the above condition is true then make P1 zero for the next Pass II.
Step 1.3: Slide the window by one position at a time and apply Step 1.1 and
Step 1.2.
Step 1.4: When all the pixels of the given image have been visited and at
least one pixel has been transformed from 1 to 0 in Step 1.2 then set a flag
is true otherwise the flag is false and go to Pass II.
Pass II
Step 2.1: Same as Step 1.1 in Pass I.
Step 2.2: If A(P1 ) = 1 and 2 < B(P1 ) < 6 then check whether at least one of
the following conditions is true or false:
(1) the pixel at east and the pixel at south are both zero,
(2) the pixel at north is zero,
(3) the pixel at west is zero.
If above condition is true then make P1 zero.
432 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

Step 2.3: Slide the window one position at a time and apply Step 2.1 and
Step 2.2.
Step 2.4: When all the pixels of the given image have been visited and at
least one pixel has been transformed from 1 to 0 in Step 2.2 then set a flag
for Pass II is true otherwise the flag is false.
Step 2.5: If both the flags of Pass I and Pass II are false then stop otherwise
go to Pass I, and repeat.
Implement this algorithm and test using a set of binary images.
29. [Thinning: logical formulation] Implement the following algorithm and
show that it is an equivalent to the Zhang and Suen’s thinning algorithm.
Consider a 3 × 3 window:
P9 P2 P3
P8 P1 P4
P7 P6 P5
where Pi′ s are pixel of the edge image. Assume P1 , P2 , · · · , P9 are Boolean.
First sub-iteration: P1 := P1 (not f (P1 ) + (P4 ∗ P6 (P2 + P8 ))).
Second sub-iteration: P1 := P1 (not f (P1 ) + (P2 ∗ P8 (P4 + P6 ))).
where,f (P1 ) = P1 ∗ t00 ∗ t11 ∗ t01s
 1, i f ′00′ f ound in P , P , · · · , P
2 3 9
t00 =
 0, otherwise,

 1, i f ′11′ f ound in P , P , · · · , P
2 3 9
t11 =
 0, otherwise,

 1, i f more than one ′ 01′ f ound in P , P , · · · , P
2 3 9
t01s =
 0, otherwise,

 1, i f ′01′ f ound in P , P , · · · , P
2 3 9
t01 =
 0, otherwise.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 433

30. [Thinning: Lu and Wang algorithm] In 1986, Lu and Wang observed the
following draw-backs in the Zhang and Suen′s algorithm
(1) Noise that should be eliminated,
(2) Structures that should be preserved, and
(3) Even worse, some digital patterns will totally disappear.
Find out some data set which highlights the above disadvantages. One sug-
gested solution of problem (2) is 2 ≤ B(P1 ) ≤ 6 to 3 ≤ B(P1 ) ≤ 6. Modify
the program accordingly and show the possible effects.
31. [Thinning: Holt et al. algorithm] Holt et al. had modified the Zhang and
Suen′s algorithm with the objective is to preserve the skeleton.
Definition: The edge function, f , of a pixel can be defined by considering a
neighboring 3 × 3 window which satisfies the following conditions:
(1) The pixel itself will be 1,
(2) Number of 1 of its 8-neighbor should be in between 2 and 6, and
(3) There should not contain more than one ‘01’ pattern of its 8-neighbors
in the clock-wise direction.
and the window is defined as
P9 P2 P3
P8 P1 P4 .
P7 P6 P5
First sub-iteration:
P1 := P1 ((not f (P1 )) + f (P4 )P2 P6 + f (P6 )P8 P4 + f (P4 ) f (P5 ) f (P6 ))
Second sub-iteration:
P1 := P1 ((not f (P1 )) + t01 (P1 ) + f (P6 )P8 P4 + f (P4 )P2 P6 + f (P4 ) f (P5 ) f (P6 ))
Here the effective window size is 4 × 4. Implement the above algorithm and
compare the results of the above thinning algorithms.
32. [Stair case elimination] The following conditional expression eliminates
the stair cases and also preserve the connectivity.
434 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

(a) Northward bias:


P1 := P1 (not (P2 ((P4 (not P3 )(not P7 )((not P8 )
+(not P6 ))) + P8 (not P9 )(not P5 )((not P4 ) +(not P6 ))))).
(b) Southward bias:
P1 := P1 (not (P6 ((P4 (not P3 )(not P7 )((not P8 )
+(not P2 ))) + P8 (not P9 )(not P5 )((not P4 ) +(not P2 ))))).
33. [Thinning: Chain′ s Algorithm] A binary template matching thinning algo-
rithm consists with 3 sets of templates as (1) thinning templates, (2) restor-
ing templates such as and (3) trimming templates. Here the window struc-
ture looks like:
P9 P2 P3 P13
P8 P1 P4 P14
P7 P6 P5 P15
P10 P11 P12 P16
where Pi′ s are pixel of the binary image.
0 0 0 0 1 x x 1 x x 1 0 x 0 0 0 0 x x 1 x x 1 1
1 1 1 0 1 1 1 1 1 1 1 0 1 1 0 0 1 1 0 1 1 1 1 0
x 1 x 0 1 x 0 0 0 x 1 0 x 1 x x 1 x 0 0 x x 0 0
(1) (2) (3) (4) (5) (6) (7) (8)
Thinning Templates

x x x x x 0 x
0 1 1 0 x 1 x
x x x x x 1 x
x 0 x
(9) (10)
Restoring Templates
0 0 0 0 0 x x 1 x x 0 0 0 0 0 0 0 0 0 0 1 1 0 0
0 1 0 0 1 1 0 1 0 1 1 0 0 1 0 0 1 0 0 1 0 0 1 0
x 1 x 0 0 x 0 0 0 x 0 0 1 0 0 0 0 1 0 0 0 0 0 0
(11) (12) (13) (14) (15) (16) (17) (18)
Trimming Templates (where x’s are don’t cares)

Implement this algorithm and compare with other thinning algorithms.


COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 435

34. Thinning algorithms by Zhang & Suen, Lu & Wang, and Holt et al. are basi-
cally template matching thinning algorithms. Here each deletion procedure
is represented by a set of conditions or a conditional expression that repre-
sents a set of thinning templates. Each algorithm is bounded by its window
size. Write a program for each thinning algorithm to count the number of
matched template (i.e., thinning templates) also calculate the probability of
matched templates in each case.
35. (a) Write a program to study the following.
(1) Apply a template matching thinning algorithm to a set of uniformly
distributed binary image of size n × n.

(2) Count the number of deleted elements from the binary image in
each cycle.
(3) Count the average number of deleted elements in each of the corre-
sponding cycle for a set of binary images.
(4) Repeat the above steps (1-3) for each of the template matching thin-
ning algorithm.
(5) Tabulate the results.
(6) Vary the size of the image (n × n) and repeat above steps.
(b) The above tabulated results is a decaying process. Is there any relation
between the number of cycles and the number of deletable elements (win-
dow size may be one of the parameter). If so, design the model.
2 +c)
[Hints: General form of the model f (t) = be−(wt+d(1+t) where, w =
window size; b, c, d are constants depends upon particular algorithm, and
t = number of cycle].
36. Can you design a good shape preserving template matching thinning al-
gorithm by extending the template size or any other way. Implement your
algorithm and measure the results.
436 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

37. Prepare a test data set (e.g., H, O, +, B etc.) for the thinning algorithms using
0 as background and 1 as foreground.
38. Generate a uniformly distributed binary image on a frame size n × m as fol-
lows:
for i := 1 to m do
for j := 1 to n do
begin
a := Random {0 <= a <= 1}
if a < 0.5 then B[i, j] := 0 else B[i, j] := 1;
end;

39. Generate a normally distributed binary image as follows:


(1) The binary image matrix B = [bi j ] ∀ i, j ∈ [0..n + 1]. Initially bi j =
0 ∀ i, j.
(2) We shall generate w (≪ n2 ) number of elements of 1.
(3) Initialize θ = θ0 , µ = µθ , σ = σθ .
(4) Generate a normally distributed random number, θ = N(θ , µ , σ )
for a seed of uniformly distributed random number θ = θ ×
V norm(µ , σ ) + θ0 .
(5) θ = Int(θ ), where Int(θ ) is the integer part of θ in degree.
(6) θ = θ mod 360.
(7) If θ is negative then θ = θ + 360.
(8) Select θ , to its nearest value of the set
{0o , 30o , 45o , 60o , 90o , 120o , 135o , 150o ,
180o , 210o , 225o , 240o , 270o , 300o , 315o , 330o }.
Also choose its corresponding position as shown in table given below:
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 437

7 6 5 4 3
x x x x x
8 x . . . x 2
9 x . . . x 1
10 x . . . x 16
x x x x x
11 12 13 14 15
Assume number 0 corresponds to the central element and pixel at position
3 (say) is corresponding to 45o .
Table 1: Angle and the corresponding position of pixels.
1 0o 5 90o 9 180o 13 270o
2 30o 6 120o 10 210o 14 300o
3 45o 7 135o 11 225o 15 315o
4 60o 8 150o 12 240o 16 330o
(9) Fill that position by 1 and also its 8-neighbors.
(10) θ0 = θ .
(11) Repeat the steps 4 to 10 until it generates w points.
Example:
The rational approximation of X = F −1 (U) for the standard normal (Odeh
and Evans 1974):
p0 + p1Y + p2Y 2 + p3Y 3 + p4Y 4
X =Y +
+ q1Y + q2Y 2 + q3Y 3 + q4Y 4
q0 p
where, Y = − log([1 −U]2 ) and
p0 = −0.322232431088, q0 = 0.099348462606,
p1 = −1, q1 = 0.588581570495,
p2 = −0.342242088547, q2 = 0.531103462366,
p3 = −0.0204231210245, q3 = 0.10353775285,
p4 = −0.0000453642210148, q4 = 0.0038560700634.
This approximation has a relative accuracy of about six decimal digits and
438 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

is valid for 0.5 < U < 1. The symmetry of the normal allows us to extend it
to 0 < U < 1 by the transformations U = 1 −U and X = −X.
40. A picture matrix f (i, j) is given. We have to construct a binary matrix S(i, j)
using a threshold and a gradient as described below:

(a) for each (i, j) compute the gradient norm by taking the average g(i, j)
of absolute values of the differences between f (i, j) and each of f (i +
1, j), f (i − 1, j), f (i, j + 1), f (i, j − 1). If g(i, j) exceeds a threshold H set
h(i, j) = 1 else h(i, j) = 0,
(b) from the histogram of the image h(i, j) × f (i, j), choose a threshold T
at a valley of the histogram. (If no such valley exists the method fails).
(c) Perform a threshold operation on f (i, j) with T to obtain S(i, j).

Where the auxiliary matrix h(i, j) contains the points of significant change
in brightness.
41. Generate a 4-connected and 8-connected uniformly distributed binary image
on a given frame of size m × n.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 439

Appendix
A part of a sample gray level image matrix M of size 64 × 64 is given below
in which row 1 looks as
31 09 00 01 00 00 00 01 00 01 01 00 00 00 00 00 01 00 00 01 01 01 01
02 01 01 01 01 02 01 01 02 01 02 01 11 17 17 17 17 16 16 16 16 16 16
16 16 11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Here M(1, 1) = 31, M(1, 2) = 09, M(1, 3) = 00, M(1, 4) = 01, etc. Similarly,
M(2, 1) = 24, M(2, 2) = 11, M(2, 3) = 01, M(2, 4) = 01, etc.
A part of Image matrix M:
31 09 00 01 00 00 00 01 00 01 01 00 00 00 00 00 01 00 00 01 01 01 01
02 01 01 01 01 02 01 01 02 01 02 01 11 17 17 17 17 16 16 16 16 16 16
16 16 11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
24 11 01 01 01 00 01 01 01 01 02 01 00 00 00 01 01 01 01 01 01 02 01
02 02 02 01 02 02 02 02 02 02 03 04 19 19 19 18 18 18 18 18 17 17 17
17 15 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
25 02 02 02 00 02 03 02 03 02 01 01 00 01 01 02 02 02 02 02 02 02 03
02 03 02 02 02 03 03 02 02 03 03 18 20 19 19 20 20 18 19 19 19 16 02
00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
27 17 02 02 01 02 02 03 02 02 02 01 01 01 01 01 02 04 04 04 04 03 03
03 03 03 03 03 03 03 03 03 04 17 21 20 17 08 18 15 09 06 09 14 15 08
02 00 01 01 00 00 00 00 00 00 00 00 00 03 05 05 07 10
28 19 03 02 01 02 02 03 02 02 02 01 01 01 01 02 02 04 04 04 04 03 04
04 03 03 03 03 03 04 03 04 16 15 13 09 07 03 03 02 02 01 01 02 04 01
00 01 01 01 00 00 00 00 00 00 00 00 07 13 13 12 12 12
28 22 02 01 01 02 02 02 02 01 02 01 02 02 01 02 02 04 04 05 04 04 04
04 04 03 03 03 04 03 03 13 21 07 05 04 06 04 02 03 02 02 02 02 01 01
01 01 01 01 00 00 00 00 00 00 04 11 13 13 13 13 12 11
29 00 02 01 01 01 02 02 01 01 01 01 02 02 02 02 02 03 04 05 05 04 04
04 04 03 03 03 04 03 06 19 11 05 05 06 09 04 03 04 03 04 04 03 02 02
01 01 01 00 00 00 00 00 04 11 13 13 13 12 12 12 11 11
29 25 01 01 01 01 01 02 03 03 03 02 02 02 02 02 02 04 04 04 05 05 04
04 04 03 03 04 03 04 04 04 03 05 05 06 04 02 04 02 02 03 03 02 02 01
01 01 00 00 00 01 06 11 12 14 13 13 13 12 12 12 11 10
29 26 03 01 01 02 01 01 01 01 01 01 01 02 02 02 03 04 04 04 05 05 04
04 04 03 03 04 03 03 03 03 05 05 04 03 02 02 01 01 01 01 01 01 01 01
02 00 00 01 07 13 14 12 12 12 12 12 13 12 12 12 11 10
29 27 21 08 01 01 01 01 01 01 02 01 01 02 02 02 04 04 04 03 04 05 04
03 04 04 03 03 03 03 04 03 03 02 02 01 01 01 00 00 00 00 00 00 00 01
01 03 10 14 14 15 14 12 09 12 11 11 11 12 12 12 11 10
30 28 22 22 16 05 01 01 01 01 01 01 01 02 02 02 03 04 04 04 05 04 03
440 CHAPTER 27. PROGRAMMING PROBLEMS ON IMAGE PROCESSING

04 04 03 03 03 05 05 04 03 02 02 01 01 01 01 01 01 00 01 01 00 00 01
11 14 15 15 15 13 13 13 07 11 11 11 11 12 12 12 11 10
29 28 22 22 22 22 16 03 01 01 01 01 01 01 02 02 03 03 03 04 03 04 03
03 03 03 02 03 04 04 03 02 02 02 02 09 07 02 01 01 06 15 05 00 00 04
15 15 14 14 14 14 13 09 09 10 11 10 11 12 11 12 11 10
29 28 21 22 22 22 23 21 13 01 01 01 02 01 02 02 03 03 03 03 03 03 03
04 03 06 19 07 03 03 02 02 08 18 18 17 16 13 14 17 18 18 05 00 01 14
15 14 14 14 13 13 13 11 07 11 11 11 11 12 12 12 11 10
29 28 22 22 21 21 22 22 22 19 10 02 02 02 02 02 03 03 03 03 03 03 02
03 02 22 23 22 17 08 05 15 21 22 21 20 19 20 19 18 18 17 02 00 12 15
14 14 14 14 13 13 13 13 07 10 12 12 11 12 12 12 11 11
Chapter 28
CASE STUDIES

In this chapter, different types of problems have been considered and discussed
in details. These problems may be termed as case studies. These are bigger
than programming assignments. It helps to the beginners to implement a com-
plete system.
CASE 1: GIS (GEOGRAPHIC INFORMATION SYSTEM)
The management of a map producing organization wants to computerize
their map producing system. In this context they are willing to design and im-
plement a Geographic Information System (GIS) with the following functions:
1. Capture spatial data (x − y coordinates),
2. Capture semantic data (text data),
3. Association between spatial and semantic data,
4. Representation of spatial and semantic data in the databases,
5. Map plotting with their associated semantic information, and
6. Online query support.

Examples of spatial data are state boundaries, district boundaries, rail-road


networks, forests etc.
Examples of semantic data are areas of states and districts, state populations,
percentage of literacy in districts, etc.

441
442 CHAPTER 28. CASE STUDIES

Develop a GIS package with the following modules


• Text data module;
• Graphical data module;
• Intermediate computation module; and
• Query processor.
The text data module includes provisions for entering fresh text data and
modification or deletion of existing text data. Examples of text data are: name
of a state, district, place; name of a state capital, district population, percent-
age of literacy etc. Data entry screens are to be create for this purpose which
incorporate various validation checking.
In the graphics data module, graphical information pertaining to district bor-
ders, place contours, border-junction points and point locations are updated. It
also allows the entry of fresh graphical data (x − y coordinates) and the modi-
fication/deletion of existing graphical data. The concept of junction point dig-
itization is to be incorporate in the system: each border has a start junction
point and an end junction point. A very important feature are to be incorpo-
rate in this module is the computation of the intersection of different layers
of data such as the association and dissociation of roads and places; here two
different kinds of data are from different layers if they are not available from
the same type of map. For each graphical data manipulation process, use two
separate window or divide the screen into two parts: dialogue area (window)
and a graphics area (window). The dialogue area is used for communicating
with the system.

CASE 2 : CANCER TREATMENT (HOSPITAL MANAGEMENT)


Suppose a cancer research and medical center provides different kinds of
treatment facilities for their patient. The payments should be done according
to their given bill to the party of the patient. The center maintains a logbook
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 443

for each patient. The authority of the center is preparing a bill according to
the corresponding logbook and their schedule of fees and charges. Most of
the patients admitted to the center for a longer period of time. Due to the
technological development and economic conditions of the country, the fees
and charges are changed frequently, so the authority of the center is changing
their fees and charges, that means, from a particular date those changes of fees
and charges are effective.
This cancer research and medical center also generates different kinds of re-
ports regarding cancer and cancer treatment in the country. In this connection
the authority of the center thought that they will maintain the whole system
(such as logbook, bill, inventory etc.) using computer.
You are required to design a computerized system for running the hospital
(cancer research center) effectively from the view point of administrations and
doctors. The system should contain the following modules: preparation of bills
for the patient, inventory of instruments, equipment and medicine, schedule of
duties of doctors and non-doctors etc.
A schedule of fees and charges of the center is given below:
Cancer Research and Medical Center
Schedule of fees and charges effect from 1/10/03 (Revised on 1/10/03 ex-
cept charges of Nuclear Medicine which was revised on 1/2/03)
444 CHAPTER 28. CASE STUDIES

General Cubicle Cabin


(Rs) (Rs) (Rs)
Registration fee 10.00 10.00 10.00
Ward rent 20.00 60.00 200.00
Operation
Punch biopsy OPD 20.00 – –
Minor biopsy LA 60.00 60.00 140.00
Minor biopsy GA 130.00 130.00 250.00
Endoscopy (including HP)
& DL Biopsy
1) LA 200.00 250.00 450.00
2) GA 300.00 300.00 550.00
Minor operation
(DIC, skin graphting etc.) 200.00 200.00 500.00
Major operation 600.00 700.00 1500.00
Special operation 1000.00 1000.00 2500.00
Radiotherapy
Ray charges (per exposure) 40.00 50.00 120.00
Nuclear Medicine
Thyroid uptake 75.00 100.00 150.00
Thyroid scan 100.00 150.00 200.00
Liver scan 125.00 150.00 250.00
Brain scan 125.00 150.00 250.00
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 445

General Cubicle Cabin


(Rs) (Rs) (Rs)
Spleen scan 125.00 150.00 250.00
Kidney scan 125.00 150.00 250.00
Bone scan (Regional) 150.00 200.00 300.00
Bone scan (whole body) 300.00 450.00 600.00
Heart (blood pool) 125.00 150.00 250.00
Renogram (scan+renogram) 150.00 200.00 300.00
T3-R1A 50.00 75.00 100.00
T4-R1A 50.00 75.00 100.00
TSH-R1A 50.00 75.00 100.00
RBC survival 150.00 200.00 300.00
Therapy (toxic goitre) 150.00 200.00 300.00
Polycythamia 150.00 200.00 300.00
Pathology
Routine blood 25.00 25.00 50.00
ESR 10.00 10.00 20.00
BTCT 10.00 10.00 20.00
Prothrombin time 30.00 30.00 60.00
Parasite 10.00 10.00 20.00
L.D. bodies etc. 60.00 60.00 110.00
Routine urine 10.00 10.00 20.00
Routine stool 10.00 10.00 20.00
Stool for occult blood 10.00 10.00 20.00
Biochemistry routine (S or U) 20.00 20.00 30.00
Biochemistry special each (except LFT) 30.00 30.00 50.00
LFT (liver function complete) 125.00 125.00 175.00
(for each test separately) 35.00 35.00 60.00
446 CHAPTER 28. CASE STUDIES

General Cubicle Cabin


(Rs) (Rs) (Rs)
Bilirubin (conjugated) 35.00 35.00 60.00
Total bilirubin 30.00 30.00 50.00
Total protein 30.00 30.00 50.00
Albomin-Globulin ratio 35.00 35.00 50.00
Alk phosphatese 35.00 35.00 50.00
SGOT 35.00 35.00 50.00
SGPT 35.00 35.00 50.00
FNABC 45.00 45.00 70.00
CSF cytology 20.00 20.00 40.00
Bence John’s Protein 15.00 15.00 25.00
Biochemical tests for CSF
-sugar/ protein/chloride 50.00 50.00 75.00
Electrolytes each 30.00 30.00 50.00
Histology tissue each 40.00 40.00 60.00
Histology full specimen 75.00 75.00 125.00
Australia antigen 125.00 125.00 175.00
V.D.R.L. 20.00 20.00 40.00
Blood grouping 10.00 10.00 25.00
Bleeding set – including all
sets and cross-matching tests 40.00 40.00 60.00
ABO Rh grouping 20.00 20.00 40.00
Cross matching 15.00 15.00 30.00
Pap test 20.00 20.00 40.00
Culture 25.00 25.00 40.00
AFB 20.00 20.00 40.00
CEA,AFP,HCG,ALFA PHETO Protein 350.00 350.00 700.00
(for each test seperately) 175.00 175.00 225.00
Immunoglobuline (Egg Igm IgA) 140.00 175.00 230.00
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 447

General Cubicle Cabin


(Rs) (Rs) (Rs)
Acid phosphate 40.00 40.00 60.00
Pathology
5’Nucleotidese 60.00 60.00 100.00
5’HIAA 60.00 60.00 100.00
VMA 110.00 110.00 150.00
CPK 60.00 60.00 100.00
CK Isozyme fraction 110.00 110.00 230.00
SRM 50.00 60.00 100.00
Protein electrophoresis 60.00 80.00 150.00
Biopoprotein electrophoresis 70.00 90.00 150.00
Bone marrow biopsy 60.00 60.00 110.00
Histopathology slide review
(each slide) 15.00 15.00 25.00
Type test 15.00 15.00 25.00
City guided biopsy 500.00 500.00 500.00
Diagnostic x-ray
Chest (each view) 45.00 60.00 100.00
Bones & joints 45.00 60.00 100.00
Spine (two view) 90.00 110.00 170.00
Any single x-ray 45.00 60.00 100.00
Cystogram 200.00 250.00 400.00
Special investigations
Cholecystography 250.00 300.00 450.00
Stomach and duodenum 260.00 350.00 500.00
Barium enema 260.00 350.00 500.00
GI Tract 350.00 400.00 600.00
IV Plography 325.00 370.00 500.00
Tomography 300.00 350.00 500.00
448 CHAPTER 28. CASE STUDIES

General Cubicle Cabin


(Rs) (Rs) (Rs)
Myelogram 350.00 400.00 600.00
uretherogram
sinogram 250.00 300.00 600.00
silogram
Barium swallow/oesophagus 150.00 150.00 225.00
Ba-metal stomach & duodunum
& follow through 400.00 400.00 550.00
Ba-Enemo (double contrast-air
contrast) 300.00 370.00 450.00
Mammography
Ultra-sound
lower abdomen 300.00 300.00 500.00
upper abdomen 300.00 300.00 500.00
whole abdomen 500.00 500.00 700.00
E.C.G. 40.00 75.00 125.00
Blood transfusion 30.00 30.00 30.00
Chemotherapy
(outdoor only) 30.00 – –

Note: Blood received from blood donation camp and other sources will be
administered free of charges to the patients of the center. But for bleeding set,
grouping and tests for drawing blood and administering to the patients, will
charge as stated above.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 449

CASE 3: STORE ACCOUNTING


In an educational institute, the store accounting system keep accounts for
different stored items which are useful to run the institute’s function properly.
This system should account the item receipt from the supplier and issued it
to different persons or departments or both. The items are either consumable
items or capital item. At the end of the financial year, an audit group checks
the system and it is connected with the financial accounting system. The store
administrator requires different reports at different times. You are required to
design a store accounting system which will be user friendly and menu driven.
During your design phase you will observe that the following functions are
necessary.
1.1 Create/update issue transactions.
1.2 Create/update receipt transactions.
1.3 Process issue transactions.
1.4 Process receipt transactions.
Also prints different reports
2.1 Print store ledger.
2.2 Print issuer’s name for an item.
2.3 Print suppliers’ name for an item.
2.4 Print all items for an issuer.
2.5 Print all items for all supplier.
2.6 Print all items for all issuers in a given range of time period.
2.7 Print items for all suppliers in a given range of time period.
Also you will find that the administrator changes the suppliers list, and it will
be easier if you choose an item codes, so you have to maintain a item code
and name file. The updation of this file is not usual but necessary. So you can
consider the following changes are privilege operations.
450 CHAPTER 28. CASE STUDIES

3.1 Update vendor file.


3.2 Update code-stock file.
3.3 Initialize/backup/restore files.
The processing of transactions is done in a particular sequence for that you
have to maintain a driver file which will store the status of transaction pro-
cessing. Also consider the power failure is a problem in the region. So you
have to maintain some other privilege operations such as
4.1 Change driver record.
4.2 Recovery on power failure.
In the following subsections describe the different function as stated above.
Create/update issue transactions
This module will captures data for issuing transactions, validates on item code,
issuer’s name, date, maximum issue attainable for an item. It creates a tempo-
rary file named as issue. This process is viewed as
1. Insert issue
2. Modify issue
In the insert issue mode you have to enter different issue transactions. The
entry done on a particular format for that you have to design a screen. Simi-
larly for modification you will be asked a relative record number (each item
becoming one record) followed by your designed issue modify screen. Note
that issue file is created only when no issue transactions are waiting to be
processed. However it simply appends when it finds some unprocessed trans-
actions. This helps you insert issue transactions over a period of time without
processing.
Once the issue transactions are processed the temporary file issue is made
disabled to prevent double processing. But it does not automatically be scratched.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 451

CASE 4 : PreSpell
Spell checking facility is an essential part of any word processor. In order to
have that facility an word processor must be equipped with a dictionary and an
efficient searching program to detect misspelled words. The following set of
rules help us to design an expert system. The rules are acquired from common
knowledge of English language.

Rule 1: To every rule there is at least one exception. Thus it is expected that
some of the rules will be violated by a minority of words. Hence a list of
exceptions have been compiled which is searched first. This set usually does
not contain more than 300 exception words.
Rule 2: Words containing any non-alphabetic character (except few special
characters in certain positions) are immediately detected.
Rule 3: There are no one letter or two letter words. In case of any conflict
Rule 1 is referred to.
Rule 4: All words must contain at least one vowel. For any conflict (e.g. with
words like my which contains semi vowels) Rule 1 is referred to.
Rule 5: All words must have one consonant. For any conflict (e.g. with
words like a or i which are one character valid words composed of non-
consonants) Rule 1 is referred to.
452 CHAPTER 28. CASE STUDIES

Table 1: Valid Letters Pairs


ABCDEFGHIJKLMNOPQRSTUVWXYZ
A .bcd efgh ijkl mnop qrst uvwx yz
B ab.d e..h ij.l .no. .rst uv.. y.
C a.c. e..h i.kl ..op qrst u... y.
D a..d e..h ij.l m.o. qrst uvw. y.
E abcd efgh ijkl mnop qrst uvwx yz
F a... efg. i..l ..o. .rst u... y.
G a... e.gh i..l .no. .rs. u... y.
H a... e... i.kl mnop .rst u... y.
I abcd e.gh ..kl mnop qrst uv.x yz
J a... e... i... ..o. ..s. u... ..
K a... e..h i.kl .no. .rs. u... y.
L abcd ef.. ijkl mnop .rst uv.. y.
M ab.. e... i..l mnop ..s. u... y.
N abcd efgh ijkl mnop qrst uvwx yz
O abcd efgh i.kl mnop qrst uvwx yz
P a... ef.h i..l .nop .rst u... y.
Q .... .... .... .... .... u... ..
R abcd efgh ijkl mnop qrst uvwx yz
S a.cd e..h ijkl mnop q.st u.w. y.
T a.c. e..h i..l ..o. .rst u.w. y.
U abcd efgh i.kl mnop qrst .vwx yz
V a... e... i..l ..o. .rs. uv.. y.
W abcd ef.h i.kl .no. .rst u..x y.
X a.c. ef.h i..l .nop ...t u... y.
Y a... e... ij.l ..op ..s. u..x .z
Z a... e.g. i..l ..o. .... u... yz
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 453

Table 2: Valid First Second Letters Pairs


ABCDEFGHIJKLMNOPQRSTUVWXYZ
A .bcd efg. i..l mnop qrst uvwx ..
B a... e... i..l .... .r.. uv.. y.
C a... e..h i..l ..o. .r.. u... y.
D a... e... i... ..o. .r.. u... y.
E a.cd .fg. i..l mn.p qrst uv.x y.
F a... e... i..l ..o. .r.. u... ..
G a... e..h i..l .no. .r.. u... y.
H a... e... i... ..o. .... u... y.
I ..cd ..g. ...l mno. .rst .... ..
J a... e... i... ..o. .... u... ..
K a... e... i..l .no. .... .... ..
L a... e... i... ..o. .... u... y.
M a... e... i... ..o. .... u... y.
N a... e... i... ..o. .... u... ..
O abcd .f.. ...l mn.p .rst uv.x ..
P a... e..h i..l ..o. .rs. u... y.
Q .... .... .... .... .... u... ..
R a... e..h i... ..o. .... u... ..
S a.c. e..h i.kl mnop q..t u.w. y.
T a... e..h i... ..o. .r.. u.w. y.
U .... .... ...l mn.p ..st .... ..
V a... e... i... ..o. .... u... ..
W a... e..h i... ..o. .r.. .... ..
X .... .... .... .... .... .... ..
Y a... e... .... ..o. .... .... ..
Z .... e... i... ..o. .... .... ..
454 CHAPTER 28. CASE STUDIES

Rule 6: A valid word should not contain any substring of length three of
identical letter. The consecutive non-occurrence of identical letters are also
applicable for substrings of length four, five etc.
Rule 7: No word can have a substring of vowels longer than three. According
to this rule beautiful is incorrectly spelled.
Rule 8: No word can have a substring of consonants longer than four.
Rule 9: Certain letter pairs can’t be the prefix of a valid word (e.g. Dploma
is spelt incorrect. Table 1 gives a complete list of such letter pairs.
Rule 10: Certain letter pairs can’t be a substring of a valid word. (e.g. azim-
futh is detected as misspelt due to the presence of substring mf which is not a
legal substring in any position of an English word) Table 2 gives a complete
list of such letter pairs.
Rule 11: If the Rule 1 does not reveal that the word is on the exception list,
and if the application of other rules (No.2-10) fails to screen out an error,
the word is spelt correct.
Chapter 29
LIST OF PROJECTS

A small set of project topics is being listed in this chapter. This set of project
may help to the students or teams to select a project in their area of interest.
The duration for the completion of the project is not sufficient with respect
to the course duration then the volume of the project works divides into sub-
projects and distribute to the class students or teams. Each team of 1, 2, or 3
students shall undertake one project on a topic of its choice. Each project is to
be completed in two phases. Choice of projects must be final and submitted
on or before some date d1 d1 .m1 m1 .y1 y1 (say).
Phase I: (To be submitted within 15 days after d1 d1 .m1 m1 .y1 y1 .)
• A detailed problem description along with all assumptions clearly
specified.
• A list of possible queries related to the problem (if database project).
• Entity-Relationship (E-R) diagram (if database project).
• Data-Flow-Diagram (DFD) .
• System flow chart etc.

Phase II: (Date of presentation to be notified later)


• Implement the system.
• Solve the queries and try to get the solutions on test data (if neces-
sary).
• Submit a project report comprising the outcomes of Phase I and
Phase II.

455
456 CHAPTER 29. LIST OF PROJECTS

A list of suggested topics for the project is given below.

1. Sequential circuit verification and synthesis.


2. Incorporating picture in conventional sets.
3. Synthesis of easily testable FSM-based controller.
4. Development of application specific integrated circuits (ASIC) designs for
various computer architecture and testability applications.
5. Design of a microprocessor based time sharing system with diagnostic and
self-test capabilities.
6. Development of algorithms for the design of logic circuits using an universal
(technology independent) model.
7. Design of an ASIC (application specific integrated circuits) chip for Image
processing applications.
8. Transformer design from the given input and output voltage specification.
9. Quantum circuit and logic gate.
10. Implementation of parallel algorithms on a network for multi-layer routing.
11. Optimization methods in high level synthesis of VLSI systems.
12. Design and application of VLSI structure built around cellular automata.
13. Application of genetic algorithm for CAD VLSI.
14. Financial accounting system.
15. Forecasting techniques.
16. Capital/share market and its analysis.
17. Develop a regional development information systems.
18. Design a Geographic Information System (GIS) which will generate maps
and answer different related questions.
19. Library management.
20. Banking operations.
21. Management of a travel agency.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 457

22. Academic administration of controller office of the university/institute.


23. Stores administration of the university/institute.
24. A hotel management system.
25. Passenger booking and reservation for South Eastern Railways.
26. An airline reservation system allowing for intermediate stops for flights.
27. A database for a car insurance company.
28. Hospital administration (indoor): admission/release of patients, allocation
of doctors, all surgical operations performed, assignment of nurses/other
staff to wards, ward occupancy etc.
29. A socioeconomic planning system for a country like India. India has a num-
ber of states. Some states are called Union Territories. Each state has a num-
ber of districts. Each district consists of number of blocks. All the states, dis-
tricts and blocks have headquarters. Blocks, districts and states have com-
mon information like population, area, number of villages, number of bank
branches, number of schools (primary and secondary), colleges and univer-
sities, etc. Some information are maintained at district and higher levels,
e.g. major crop with annual production, number of unemployed persons,
rainfall and temperature, etc. Further, there are information maintained at
the state level: budgeted figures, revenue collection, literacy etc. Note, for
example, population which is supposed to be available at block level on-
wards (as mentioned above) in some specific cases may be available only
for a district or even for a state only. Moreover, information is maintained
since independence.
30. A database based on the working of a company ‘Typico’. ‘Typico’ is a
wholesaler that buys goods from manufacturers, paying relatively low prices
because the quantities are large. A wholesaler such as Typico profits by sell-
458 CHAPTER 29. LIST OF PROJECTS

ing the goods at higher prices, but in smaller quantities, to retailers. These
retailers are the wholesaler’s customers.
Design and implement the database considering the following aspects:

• Receiving purchase orders from customers.


• Maintaining an inventory for the items which Typico supplies to cus-
tomers.
• Creating sales order after accepting a purchase order.
• Credit checking for each customer.
• Delivery and invoicing.
• Sales Order history.
• Purchase orders from Typico to suppliers.
• Receipt of goods.
• Accounting - accounts receivable and accounts payable, payment to sup-
pliers, the general ledger.
• Audit trails.

31. Personnel database.


32. Air-line/Railway reservation system.
33. Security issues in IBM personal computers (viruses, cures, protection, etc.).
34. Program testing.
35. Design of CASE tool for Objected Oriented Programming (OOP) environ-
ment.
36. Design of packages for object oriented databases.
37. A software engineering tool for parallel processing.
38. Design and implementation of functional programming language (with type
inferencing system).
39. A two years Post-Graduate Diploma in Management (PGDM) course have
been organized in 3 terms per year.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 459

(a) Design a grade processing system for that course and also take care
for the new batch where intake varied from year to year. In each term of
the first year, number and name of the courses are fixed for each student
but in the second year number and name of courses (compulsory, elec-
tive and optional) varies with term also the elective and optional varies
with students. (Assume: In the first year, first term: one compulsory non-
credit course if not pass then fail. In the second year, each term contains
compulsory ≤ 3, elective ≤ 6 and optional ≤ 3 courses).
(b) Design a system to prepare a prize list at the end of the PGDM course
under different conditions: (1) total score in a particular subject (say
BS: Behavioral Science, FI: Finance etc.) and (2) mixed subjects not all
courses (such as total in BS and FI or BS, FI and MK: Marketing etc.).
(c) Students profile for PGDM.
(d) Design a selection procedure for the candidates for PGDM course –
selection process goes through (1) formal admission test, (2) personal test,
(3) group discussion etc.

40. Design a specific survey questionnaires and implement the methodology for
the process of survey data. Try to generalize your program for the processing
of survey data.
41. Development of some software packages for process control applications.
42. Expert system for the snake identification and its therapy.
43. Design and implementation of visibility & shortest path algorithms for a
polygonal robot amidst polygonal obstacles.
44. Design and implementation of sequential and parallel geometric algorithms
for the hidden surface/line elimination problem in computer graphics.
45. Development of a graphic utility package.
46. Expert system for the Indian contract act.
460 CHAPTER 29. LIST OF PROJECTS

47. Expert system for the cropping pattern.


48. Expert system for the tax planner for a salaried employee.
49. Expert system for a doctor without a stethoscope.
50. Expert system for FERA act.
51. Expert system for Trouble shooting for IBM PC/XT/ATs.
52. Road map extraction from a satellite image.
53. Watermarking problems.
54. MRI image analysis.
55. Implement a MATLAB tool box for clustering algorithms.
56. Implement a MATLAB tool box for feature selection algorithms.
57. Online and off-line feature analysis.
58. Analysis of digital mammogram for breast cancer detection. (Hints: digital
mammography data are available in the internet).
59. Implement a package for the low level image segmentation in the low level
vision. This systems include different image processing operations such as
display image, filtering, edge detection, thinning, region detection, vector-
ization for the high level vision.
60. Development of a two phase region analyzer for computer vision applica-
tions.
61. Automatic visual inspection system for detecting faults in PCB’s.
62. OCR (Optical Character Reader) for converting scanner output to text files.
63. Design and implementation of an interface engine for recognition problems.
64. Intersections of polygons (unrestricted) and related problems.
65. Convex-hull computation.
66. Shape analysis using convex-hull.
67. Quad-tree : application in image processing.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 461

68. A distributed OS kernel for supporting resilient concurrent operations and


transaction processing.
69. Extending C to a concurrent programming language supporting dynamic
resource and access capability management.
70. Implementation of LISP functions.
71. Symbol table management for Pascal.
72. Sparse matrix operations, e.g. addition, multiplication, inverse.
73. Sorting algorithms - a comparative analysis.
74. Dynamic memory management .
75. Symbolic differentiation.
76. Operations (i.e. add, sub, mul, div) on generalized polynomials.
77. Hashing algorithms - a comparative analysis.
78. Dynamic hashing algorithms - a comparative analysis.
79. Graph search algorithms.
80. Implementation of MS-DOS directory structure.
81. Balanced search tree algorithms, e.g. AVL, 2-3 tree.
82. Multilevel index structure for files.
83. Secondary key retrieval.
84. String manipulation with application to word processing.
85. External sorting algorithms.
86. Variable length records - an implementation.
87. Hashed file organization - an implementation.
88. Experimental study of hashing algorithms.
89. Geometric hashing algorithm.
90. CD ROM driver.
91. Design and simulate the following biological neural networks in the the
cerebellum.
462 CHAPTER 29. LIST OF PROJECTS

(a) Limb premotor network.


(b) Eye premotor network.
(c) Conditioned reflexes network.
(d) Cerebellar regulation of the brainstem brust-generating network.

92. Implement multi-layer perceptron (MLP) and radial basis function (RBF)
algorithms for function approximation and their parameter choice.
93. Self-organization feature maps (SOFM) for clustering.
94. Implement winner-take-all (WTA) algorithms.
95. Implementation of numerical algorithms (root finding, differential equation
etc.) in using artificial neural networks (ANN).
96. A package for different random number generation (such as uniform – con-
tinuous and discrete, normal, beta, gamma etc.).
97. Numerical differentiation and integration of a given function.
98. Statistical mean computation using quantum computer.
99. Atmospheric temperature prediction.
100. Cloud velocity Estimation.
101. Design a computational methodology of numerical methods using quantum
computer.
102. Entropy measurement in information theory.
103. Face recognition system.
104. Fuzzy rule base system design.
105. Decision tree and its application.
106. Image compression techniques.
107. Finger print detection.
108. Traditional and color halftonning techniques and its analysis as an NP-
complete problem.
109. Implement different cluster validation techniques.
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 463

110. Design and analysis of social friendship problem.


111. Study of different immuno computing techniques.
112. Study of secondary structure of protein.
113. Recent trend in drug discovery problem.
114. Simulation of a gene model.
115. Recent trend in molecular computation for numerical methods.
116. Application of genetic algorithm (GA) in routing problem.
117. Design and implement a web page for a conference management system that
includes: (1) conference details, (2) paper processing – submission, review
process, report process, (3) registration, (4) accommodation etc.
118. Design and implement a cloud tracking problem.
119. Design and implement a vehicle tracking problem.
120. Detection of microcalcification from a digital mammogram.
121. Segmentation of micro-calcificattion from a digital mammogram.
122. Segmentation of medical image analysis such as CT scan, MRI images.
123. Implementation of traditional and fuzzy petri net system.
124. Design and implementation of a cryptographic system.
125. Design and implementation of a genetic programming (GP) tools box for
MATLAB.
126. Prediction of protein folding techniques.
127. Design and implementation of DNA sequencing and multi-sequencing prob-
lems.
References

1. Aho A.V., Sethi R. & Ullman J.D. Compilers: Principles, Techniques and Tools. Addison-Wesley Publishing Company.
2. Balagurusamy E. COBOL Programming: A Self-Study Text. Macmillan India Ltd., New Delhi.
3. Balagurusamy E., Sarma M.S. & Saikumar M.L. dBase III Plus a Guide and Workbook. Macmillan India Ltd., New Delhi.
4. Barkakati N. Object Oriented Programming in C++. Prentice Hall India.
5. BASIC by Microsoft.
6. Beck L.L. System Software an Introduction to Systems Programming. Addison-Wesley Publishing Company, New York.
7. Bidgoli H. Advanced LOTUS 1-2-3 with Application. Galgotia, N. Delhi.
8. Boillot M. Understanding Fortran 77 with Structured Problem Solving. Jaico Publishing House.
9. Das S. UNIX System V.4, Concepts and Applications. TMH Publishing Company Ltd., New Delhi.
10. Dhamdhere D.M. Systems Programming and Operating Systems. Tata McGraw-Hill Publishing Company Ltd., New Delhi.
11. Donovan J.J. Systems Programming. McGraw-Hill International Book Company.
12. Foley J.D., van Dam A., Feiner S.K. & Hughes J.F. Computer Graphics: Principles and Practice. Addison-Wesley Publishing
Company.
13. Folk M.J. & Zoellick B. File Structures. Addison-Wesley Publishing Company, New York.
14. Gargill T. C++ Programming Style. Addison-Wesley Publishing Company.
15. Gonzalez R.C. & Woods R.E. Digital Image Processing. Addison-Wesley Publishing Company.
16. Gottfried B.S. Theory and Problems of Programming with BASIC. McGraw Hill.
17. Gottfried B.S. Theory and Problems of Programming with Pascal. McGraw Hill.
18. Gottfried B.S. Theory and Problems of Programming with C. Tata McGraw-Hill.
19. Grover P.S. Programming with Structured COBOL. Macmillan India Ltd., New Delhi.
20. Heiny L. Advanced Graphics Programming using C/C++. John Wiley & Sons.
21. Holmes J. Object-oriented Compiler Construction. Prentice Hall, Englewood Cliffs.
22. Korth H.F. & Silberschatz A. Database System Concepts. MCGraw Hill.
23. Leavens A. Designing GUI Applications for Windows. BPB Publications.
24. Microsoft. GW-BASIC User’s Guide and User’s Reference.
25. Microsoft. MS Fortran Reference Manual.
26. Microsoft. MS Fortran Compiler: User’s Guide.
27. Microsoft. MS COBOL Reference Manual.
28. Microsoft. MS COBOL Compiler: User’s Guide.
29. Microsoft. Microsoft Macro Assembler.
30. Microsoft. MS C Compiler : User’s Guide.
31. Page. C.G. The Professional Programmers Guide to FORTRAN 77. Pitman.
32. Parker J.R. Practical Computer Vision Using C. John Wiley & Sons.
33. Roy M. K. & Ghosh Dastidar D. COBOL Programming. Tata McGraw Hill.
34. De Saram H. Programming in Micro-Prolog. Affiliated East-West Press.
35. Sharma K.D. Programming in Fortran IV. Affiliated East-West Press.
36. Shelley J. Essentials of FORTRAN 77. John Wiley & Sons.
37. Simpson A. Understanding dBASE IV 1.1. BPB Publications.
38. Smith N. E. Write Your Own Programming Language Using C++. BPB Publications.

465
466 References

39. Stevens R.T. & Watkins C.D. Advanced Graphics Programming in C and C++. BPB Publications.
40. Stroustrup B. The C++ Programming Language. Addison-Wesley Publishing Company.
41. Subramaniam N. Programming for Basic.
42. Swan T. Mastering Turbo Pascal.
43. Taylor P.H. 3D Graphics Programming in Windows. Addison-Wesley Publishing Company.
44. Tenenbaum A.M. & Augenstein M.J. Data Structures Using Pascal. Prentice Hall.
45. Tenenbaum A.M., Langsam Y. & Augenstein M.J. Data Structures Using C. Prentice Hall.
46. Townsend C. Introduction to Turbo Prolog.
47. Ulichney R. Digital Halftoning. The MIT Press, Cambridge.
48. Ullman J.D. Principles of Database Systems. Computer Science Press Inc.
Index

2 × 2 operator, 426, 428 Alphabetic order, 167, 169


3 × 3 operator, 426, 428 Alphabetical order, 232
3 × 3 pattern filling, 418 Alphabetically ordered, 262
5 × 5 pattern filling, 419 Amendments, 261
>>, 319 American National Standards Institute (ANSI), 7
π computation, 263 Amicable number, 197
4-connected, 438 Analysis, 1
8-connected, 438 ANN, 462
8-neighbors, 128 Annual rate, 132
ANSI X3JZ/76-01, 7
ABC analysis, 399
Arabic numerals, 162
Abu Jafar Muhammad ibn Musa al-Khowarizmi, 3
Arithmetic assignment statement, 98
Acceleration, 103
Arithmetic expressions, 270
Accept, 307
Arithmetic test, 252
Accuracy, 113
Array, 38
Action table, 306
Artificial neural networks, 462
Actual sale, 174
ASCII, 168, 187, 282, 460
Administrative overhead, 136
ASCII function, 168
Admission procedure, 344
ASIC, 456
Admission test, 138
Assembler, 292
Agricultural practices, 389
Assembly language, 296
Aircraft, 176
Assertion box, 4
Airline, 338, 457
Attack, 243
Airline reservation, 125, 371
Attending doctor, 390
Airlines reservation, 355
Automatic stamp venting machine, 355
alarm, 324
Average monthly sale, 136
Algebrical Method, 43
Average number of probes, 362
algorism, 3
AVL tree, 362
Algorithmic Method, 69
Algorithms, 2 B-tree, 285, 361
ALLOT, 179 Back to front, 201
Alpha-Beta Strategy, 246 Balanced search tree, 461

467
468 Index

Bank, 119, 132, 175, 261, 456 Bucket, 291


Bar chart, 239 Budget, 352
Base 10, 195 Building contractor, 107
Base B, 195 Bumper sale, 180
BASIC, 2, 6 Buyer, 173
Basic concept, 97
C, 2, 18, 277
BASIC Programming, 46, 71
C Programming, 53
BASIC+2, 7
C++, 2, 86
BASICA, 7
CAD VLSI, 456
Batting performances, 279
Calendar year, 172
Beats, 241
Cancellation request, 332
Beautifier, 288
Cancellations, 331
Beginners All-purpose Symbolic Instruction Code, 6
Cancer Research, 443
Benchmark, 292
Cancer research hospital, 387
Benchmark program, 292
Cancer Treatment, 442
Best Fit, 181
Car insurance, 457
Best fit, 295
Car insurance company, 388
Beta distribution, 409
Car travelling, 212
Bills, 134
Car-rental business, 379
Binarization, 429
Card trick, 235
Binary, 195
Cargo, 142
Binary coded form, 180
Carriage return, 297
Binary image, 425
Cartesian coordinates, 239
Binary tree, 357
Case studies, 441
Binary-search tree, 357
CASE tool, 458
Binomial coefficient, 112 Cash budgeting problem, 405
Binomial distribution, 409 casting, 107
Bisection, 265 Casting problem, 383
Bisection search, 168, 169 CAT into DOG, 233
Bishops, 243 Catalog, 167
Bit map, 298 CBR, 334
Black moves, 243 CCD, 415
Block allocated, 298 CD, 190
Board splitting game, 245 cd, 312
Boolean flag, 128 CD ROM driver, 461
Boolean matrix, 128, 188, 301 Cellar, 411
Boolean variables, 100 Cellular automata, 456
Break Even Analysis, 399 Centigrade, 109
Break-even chart, 401 Central reservation office, 331
Break-even volume, 402 Chained hashing algorithms, 411
Breast cancer, 460 Character string, 106
Broadcast, 190 Charge-Coupled-Device, 415
Bubble sort, 171, 273 Chebsyshev polynomial, 184
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 469

Chebyshev′ s operator, 428 Continuous tone image, 421


Checkmate, 243 Contour points, 430
Chess, 243 Contradiction-free, 3
Chess board, 243, 247 Conversion, 251
Chi-square distribution, 409 Convex-hull, 460
Child allowance, 131 COPY, 311
Chronological order, 390 Counterfeit coin, 129
Chunky wall paper, 238 cp, 322
Circles, 238 cpio, 323

Circular shape box, 6 Credit purchase, 340

Circular queue, 357 Credit-hour, 154

Cloud tracking, 463 Cricket match, 280

Cloud velocity, 462 Cricket-match, 279

Cluster validation, 462 Crimes, 158

Clustering, 460, 462 CRO, 331

COBOL, 2 cron, 324

COBOL Program, 89 Cropping pattern, 460

Coding system, 127 Crops, 339


Cross-assembler, 296
Collapsing rule, 361
Cross-word, 258
Color, 237
Cryptographic system, 463
Color halftonning, 462
Cryptography, 170
Commission, 164, 272
Cube root, 194
Compare two binary search trees, 285
Cumulative, 281
Compiler, 292
Cumulative expense file, 341
Compilers, 7
Current accounts, 261
Completeness, 3
Customer booking requisition, 334
Complex number, 261
Customer type, 133
Complex propositions, 279
Complex variable, 287 Data Flow Diagram, 332
Compressor, 101 Data processing, 171
Computational scheme, 2 Data structure, 357
Computer false floor, 102 Data-Flow-Diagram (DFD), 455
Computer vision, 415 Database, 371
Concatenation, 286 date(1), 323
Concentric circles, 241 Dbase Programming, 63
Conference management, 463 DBMS, 372
Connectivity, 430 Decimal, 195
Consequences, 254 Decision box, 4
Consistency check, 125 Decision making process, 280
Consistent, 3 Decision table, 347, 348
Constrained average method, 422 Decision table construction procedure, 349
Construction company, 372, 385 Decision tree, 462
Continued fraction, 266 Decision-making criterion, 347
470 Index

Definite Integration, 31 Dot matrix, 190


Definiteness, 3 Double hashing method, 362
Degree of a polynomial, 113 Driver for insurance, 354
Delete, 285 Driver routine, 307
demon, 324 Drug discovery, 463
Departmental library, 377 Dry spell, 124
Departmental stores, 371 Dynamic hashing, 461
Deposit, 178 Dynamic memory allocation, 285
Design, 1 Dynamic memory management, 461

Destination, 181 Dynamic threshold, 422

Detailed design, 1
Early Insertion Coalesced Hashing, 369
Deterministic finite automata, 301
Economical readable output, 259
DFD, 301, 332
Edge detection, 426, 427
Diamond shaped box, 4
Editing numbers, 202
Dictionary, 175
EICH, 369
Differential Equations, 32
Eigenvalues, 33
Differentiation, 30, 213, 266, 462
Eigenvectors, 33
Digital camera, 415
Electric supply, 134
Digital image processing, 415
Encoding, 281
Digital mammogram, 463
Encyclopedia, 167
Dimensionless head, 110
end of file, 297
Direct chaining, 367, 368
English sentence, 170
Direct threshold, 420
English test, 143
Directorie, 309
Enlarge, 425
Directory format, 297
Enlarging, 260
Disbursement, 405 Entity-Relationship (E-R) diagram, 371, 455
Discount, 133 Entrance fee, 352
Discount procedure, 133 Entropy, 429, 462
Discounting policy, 133 EOF, 297
Diseas, 340 Equipment specification, 338
Disjoint set, 361 Error distribution, 424
Disk format, 296 Error distribution method, 423
Disk Operating System, 309 Error message, 173
Diskette, 298 ESC sequence, 190
Dispatched, 337 Euclid’s method, 194
Dispersion, 429 Euclidean distance, 184
Distance chart, 254 Even number, 193
Distinctive pattern, 241 Examination results, 253
Division method, 365 Excel, 399
DNA sequencing, 463 Execution time, 290
Dock facility, 150 Expense sheet, 341
DOS, 309 Expert system, 459
Dot diffusion, 425 Expire date, 185
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 471

Expositive table, 348 Flowering Time, 413


External sorting, 461 Floyd and Steinberg’s error distribution, 424
Folded in half, 251
F-distribution, 409
Folding method, 366
Fabrication, 404
Folio number, 173
Face recognition, 462
Football league, 236, 248
Factorial, 194
Football tournament, 183
Fahrenheit, 109
Forecast, 174
Family tree structure, 309
Forecasting method, 174
Fare calculation handbook, 331
Forecasting techniques, 456
Farm, 339
Foreign monetary systems, 153
FAT, 294
Forest, 309
Feasibility study, 1
Formatting, 312
Feature analysis, 460
FORmula TRANslation, 10
Feature image, 429
FORTRAN, 2, 10, 269
Feature selection, 460
FORTRAN Programming, 49, 73
FERA, 460
Fortune telling, 242
Fermi-Dirac distribution, 209
FoxPro Programming, 63
Fibonacci number, 200, 201
FoxPro/dBASE Programming, 81
Fibonacci sequence, 105, 200
Frequency distribution, 416
File format, 297
Friendly number, 197
File names, 297
FSM-based controller, 456
File system, 296
Fun, 231
Film, 129
Function approximation, 462
Film show, 352
Function box, 4
Filter, 416
Fundamental operation, 275
Financial accounting, 456
Fuzzy petri net, 463
Financial supports, 352
Fuzzy rule base, 462
Finger print, 462
fwrite, 324
Finished goods, 136
Finiteness, 3 GA, 463
First fit, 295 Game, 291
Fixed image size, 409 Game tree, 247
Fixed-length record, 284 Games, 231
Flight, 177 Gamma distribution, 409
Floating point, 269 Gas dealer, 384
Floppy, 298 Gasoline, 149
Floppy file management, 309 Gene, 463
Flow Chart Method, 44, 68 Generalized error diffusion, 423
Flow Lines, 6 Generalized polynomials, 461
Flow-chart method, 347 Generalized program, 113
flow-charts, 2 Genetic algorithm, 456, 463
Flowchart, 3 Genetic programming, 463
Flowcharting, 4 Geographic Information System, 362, 386, 441, 456
472 Index

Geography quiz, 159 Hexagonal grids, 425


Geometric hashing, 461 HF(highly-fertiled), 389
Ghost images, 424 Hidden surface, 459
GIS, 362, 386, 441, 456 Hierarchical directory structure, 296
Goal, 183 Hierarchical file structure, 309
Goldbach’s conjecture, 199 High accuracy calculations, 202
Good morning, 185 High-low game, 232
Goodnight Hotel, 375 High-Low technique, 256
goto table, 306 Highest Common Factor, 194
GP, 463 Highest response ratio next, 295
GPA, 394 Highway code, 212
Grade point averages, 394 Histogram, 416
Grammar, 299 Hit parade, 190
Graph search, 461 Hoffman code, 180
Graphical information, 415 Horse race, 242
Graphically, 399 Hospital Management, 442
Graphics, 29, 231, 415 Hostel, 342
Graphics designer, 241 Hotel, 126
Graphics driver, 290 House, 237
Gray value, 415 HRRN, 295
Great Circle, 188
I/O operations, 6
Great Circle distance, 188
Identifiers, 299
Gross pay, 135
Identity card, 185
Gross salary, 131
Identity matrix, 33
Guesses, 234
Image compression, 462
GW BASIC, 7
Image file, 415
Halftonning, 418–423, 425 Image filtration algorithm, 416
Hangman, 160, 234 Image frame, 415
Hardback, 173 Image processing tools, 415
Harmony, 236 Imaginary roots, 110
Hash function, 166 Imagination, 259
Hash table, 165 Immuno computing, 463
Hashed file, 461 Implementation, 1, 2
Hashed table, 361 Incentive scheme, 136
Hashing, 461 Income tax, 131, 382
Hashing algorithm, 165 Incoming mail, 327
Hashing method, 165 Index, 167
HCF, 104, 194 Indian contract act, 459
Header block, 286 Information retrieval, 339
Health center, 390 Information theory, 462
Health Services, 340 Inorder, 360
Heap data structure, 357 Input card, 188
Hexadecimal number, 195 Input-output, 3
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 473

Insert, 285 Legal algebraic expression, 119


Installation, 2, 352 Legendere polynomial, 281
Insurance company, 351 Lexical analyzer, 299
Integration, 30, 272, 462 Lexicographic ordering, 107
Intensity, 415 Lexicographically, 359
Interpreters, 7 Library information, 328
Interrupt, 258 Library management, 456
Intersections of polygons, 460 Library procedure, 345
Inventory, 136 Library program, 113
Inventory table, 114 LICH, 368
Invoice log sheet, 338 Life, 244
Isotropic method, 428 Light year, 251
Line graphics, 239
Jail, 113 Linear equation, 110
Jarvis, Judice and Ninke’s error distribution, 424 Linear probes, 170
JAVA, 2 Linear search, 168, 169
JOB, 174 Link list, 357
Job descriptors, 295 Linkage editor, 292
John Conway’s Life game, 248 Linked list, 167
Josephus permutation, 359 Linking, 292
Josephus problem, 358 LISP, 461
Journals, 328 Literals, 36
Jump, 417 Living cell, 212
Loading, 183, 292
Kilogram (Kg), 109 Local Area Network, 341
Kilowatt-hours, 156 Local average intensity, 422
King, 243 Log table, 211
Knight tour, 242 Logarithmic equation, 213
Knights, 243 Logic paths, 4
Kurtosis, 429 Logical expression, 100
Logical operation, 128
Ladder-climbing, 232
Logical operator, 279
LAN, 341
Logical if statement, 271
Large factorials, 203
Long-term scheduling, 290
Large letters, 240
Longest decreasing subsequence, 281
Large numbers, 202
Longest word, 187
Late-insertion coalesced hashing, 368
Longitude, 188
Latitude, 188
Lowest factor, 200
Layout, 140
LR grammar, 306
LCM, 104, 195
LR parser, 307
League tables, 212
lseek, 321
Leap-year, 251
Lucky number, 197, 232
Least Common Factor, 195
Least square method, 113 Machine ideal time, 178
474 Index

Magazines, 328 Midterms, 152


Magic squares, 233, 242 Minimal spanning tree, 267
Magnetic disc, 6 Minimally perfect function, 165
Magnetic field, 415 MINIMAX, 246
Magnetic tape, 6 Minimum and maximum attack problem, 243
Mainframe, 7 Minimum coded text length, 180
Maintenance, 1 Minimum-cost spanning tree, 360
Mammogram, 460 MLP, 462
Management, 150 Modern Model, 402

Management consultancy, 389 Modulation, 421

Manuscripts, 328 Module leader (ML), 390

Market survey, 125, 262 Moire patterns, 240

Master File, 178 Molecular computation, 463

Master file, 396 MRI image, 460

Match, 236 MST, 267

Materials, 399 Muddled statement, 254

Materials specification, 338 Multi-cropping, 389

MATHEMATICA, 23, 57 Multi-layer perceptron, 462


Multilevel index structure, 461
Mathematica, 2
Multiplicative method, 365
Mathematical expressions, 103
Music, 236
Mathematical Methods, 43
MATLAB, 2, 20, 55
Narrative method, 347
Matrices, 33
Natural frequency, 209
MATrix LABoratory, 20
Natural number, 193
Matrix Operations, 33
Negotiated goal, 164
Mean, 273, 429 Net order value, 133
Median, 429 Newly born babies, 129
Medical Center, 443 Next fit, 295
Medical image, 463 NIM, 231
Medical images, 415 Noisy, 416
Memory management, 294 Non-recursive, 360
Memory manager, 295 Nonlinear Differential Equation, 32
Memory requirement, 290 Normal Distribution Table, 212
Merge sort, 256 Normalized digital image, 423
Merge two linked lists, 360 Normally distributed binary image, 436
Mersenne Primes, 198 Notebook Interfaces, 25
Mess accounts, 343 NP-complete, 462
Message revealed, 258 Number Bases, 195
Method of timing, 199 Number of probes, 169
Methodical function, 252 Number theory, 193
MF (moderately-fertile), 389 Numerical algorithms, 462
Microcalcification, 463 Numerical center, 201
Mid-square method, 366 Numerical computation, 401
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 475

Object modules, 294 Palindrome, 116, 257


Objected Oriented Programming, 458 Paper tape, 6
Objective test, 139 Paperback, 173
OCR, 460 Parabola, 239
Odd number, 193 Parallel algorithm, 456
Odd one out, 254 Parallel docks, 150
Odometer, 149 Parallel thinning algorithm, 430
on-line processing, 338 Parallelogram shaped boxes, 6
OOP, 458 Parser, 299
Opening balance, 178 Parsing table, 306
Operating environment, 317 PASCAL, 13
Operating system, 309 Pascal, 2
Operations, 37 PASCAL Programming, 51, 76
Operator, 147 Pascal’s triangle, 253
Operator precedence function, 301 Pass, 171
Operator precedence grammar, 301 Pass grades, 131
Operator precedence relations, 301 Password, 252, 257, 280
Operator precedence table, 301 Path name, 297
Operator symbols, 299
Pathology department, 387
Operators, 38
Patient billing, 342
Opponent player, 231
Patient’s Master file, 340
Optimal binary code, 180
Pattern, 128, 175
Optimal tour, 184
Pay cheque preparation, 148
Order dither technique, 421
Payroll program, 155
Order number, 133
PCB, 460
Order of magnitude, 198
Peak, 417
Order preserving, 366
pel, 415
Order value, 133
Pelmanism, 257
Order-entry system, 374
Pence, 109
Ordered minimal perfect hashing, 366
Pension rules, 119
Organisms, 248
Percentage error, 113
Organization hierarchy, 136
Perfect function, 165
OS, 312
Perfect hash function, 165
Output device, 298
Perfect number, 199
Outstanding bills, 343
Perfect squares, 193
Oval, 6
Perform numerical integration, 266
Overdrafts, 336
Permutation, 184
Overflow area, 167
Persistence, 195
Overhead Expenses, 402
Personal allowance, 131
P/V (Profit/Volume), 399 Personal status, 131
Packaged, 337 Petri net, 463
Pair of words, 186 Petrol filling station, 355
Paise, 109 pfd, 318
476 Index

Physical design, 1 Process symbol, 4


Picto-gram, 240 Process transaction, 340
Picture elements, 415 Processing time, 178
Pie chart, 239 Product line, 133
pigLatin, 261 Production rules, 299
Pixel, 190, 415 Products, 111
Pixel patterns, 241 Profit-volume chart, 402
Planning, 1 Profit/loss, 402
Playing card, 162 Program coding, 2
Playing cards, 235 Programming languages, 2
Point of discontinuity, 417 Programming Methods, 46
Pointer, 38 Project, 141, 455

Pointers, 282 Project leader (PL), 390

Poisson distribution, 409 Project oriented organization, 390

Poisson distribution table, 212 Projected profit-loss account, 406

Polar, 239 Projectile, 266

Police department, 158 Propositional formula, 279

poll, 324 Propositions, 278

Polynomial, 357 Protein folding, 463

Polynomial solution, 237 prune, 247

Positive integer, 196 Public hospital, 340

Postfix expression, 289 Public issue, 179

Pounds (lbs), 109 Puja fortnight, 180

Power series, 112 Punched card, 6

Powers of prime, 200 Punctuation mark, 143


Punctuation symbols, 299
Predefined Process, 6
Push and pull, 291
Prediction, 462
Preference number, 126
Quad-tree, 460
Premium, 351
Quadratic equation, 43
Preorder, 360
Quality conscious, 390
Preprocessor, 287
Quantum circuit, 456
PreSpell, 451
Quantum computer, 462
Pressure vessel, 101
Queen, 243
Prime factorization, 200
Questionnaire, 125, 262
Prime number, 198, 199
Queue, 291, 357
Prime number hash function, 367
queue, 325
Prime numbers, 254
Quick decision, 347
Prime Pair, 199
Quite amusing, 254
Printer device, 6
Quiz, 171
Printing head, 190
Quotient, 102
Priority, 290
Priority queue, 357 Radial basis function, 462
Process control, 459 Radians, 112
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 477

Radiation frequency, 209 Reserved words, 299


Radiological facilities, 341 Reverse order, 111
Radix tree, 359 Review process, 463
Rainfall, 124 Road map extraction, 460
Random delays, 298 Robert’s method, 426
Random generator, 295 Robot, 459
Random jump, 238 Rod, 107
Random letters, 233 Roman number, 197
Random noise, 416 Roman numeral, 196

Random number, 462 Roman numerals, 162, 197

Random selection, 257 Rooks, 243

Random walk, 238 Root directory, 309

Rankwise Projects, 142 Roots of number, 194

Raster image, 429 Rotation, 239

RBF, 462 Roughness, 110

Read-only protection mode, 283 Round robin scheduling, 319

Real root, 273 Rounded to nearest quarter hour, 135

Real roots, 110 Routing problem, 463


RRN, 286
Reconstruct the tree, 361
Rubbed out, 241
Record structure, 114
Rupees, 109
Recording company, 190
Rectangle numbers, 236
SADT, 339
Rectangular grid, 425
Sales orders, 327
Recursive function, 191, 281
Sales performance, 134, 164
Recursive program, 184
Sales representative, 164
Redistribution, 286 Salesman, 396
Reduce, 307 Salesperson, 184
Reduced numbers, 195 Sample gray level image, 439
Regional development information systems, 456 Satellite images, 415
Regula falsi, 265 Scanning devices, 415
Regular hexagon, 238 Scattering cross-section, 209
Regularization, 417 Scheduling algorithm, 290
Relative frequency, 180 Scheduling metric, 290
Relative Record Number, 286 Scheduling size, 291
Relatively prime, 104 Score, 133
Relocation, 292 Score computation, 416
Remainder, 102 Score-card, 279
Remote Connector, 6 Search for primes, 201
Repeated trials, 265 Search performance, 165
Replacement procedure, 284 Search scheme, 167
Report process, 463 Search sequentially, 169
Reservation Procedure, 331 Searching, 256, 286
Reservation request, 332 Searching method, 168
478 Index

Seed, 162 slip, 337


Seeds, 339 Smooth histogram, 416
Segmentation, 463 Snake identification, 459
Selection criteria, 347 Snake-swallowing, 232
Selection procedure, 343 Snakes and ladders game, 232
Selection process, 347 Sobel’s method, 426
Selection sort, 255 Social friendship, 463
Self-organization feature map, 462 Socioeconomic survey, 389
Seller, 173 SOFM, 462
Semi-perimeter, 109 Software engineering, 327
Sensitivity analysis, 408 Software Experts, 136
Separate chaining, 368 Solve Equation Symbolically, 31
Sequence set block, 285 Solve Equations Numerically, 32
Sequential circuit, 456 Sort, 106, 260, 396
Sequential file, 260 Sorted integer, 121
setitemer, 324 Sorting, 461
Shape analysis, 460 Space allocated, 165
shape preserving, 435 Space available, 165
Shapes, 260 Sparse Matrix, 358
Shapes of I/O operations, 6 Sparse matrix, 461
Share, 173 Specialists, 390
Share market, 456 Specification of rule, 347
Shareholder, 173 Speed-up, 409
Shares, 179 Spirals, 239
Sharper peak, 417 Splitting, 286
shell handle, 319 Spooler, 298
Shift, 307 Spurious picks, 417
Shilling, 109 Spurious valleys, 417
Ship traffic collects, 150 Square board, 245
Shipping area, 337 Square matrix, 107
Shortest word, 187 Square number, 187
Sieve of Eratosthenes, 254 Square root, 169, 194
Significant digits, 112 Squash, 239
Significant fields, 178 SSS∗ strategy, 246
Simulation technique, 294 Stack, 357
Simultaneous Equations, 32 Staff’s performance, 164
sine curve/wave, 240 Stair case elimination, 433
Single-field record, 172 Standard C library, 317
Skeleton, 430 Standard deviation, 273, 409, 429
Skewness, 429 Standard mess bills, 343
Skip size, 169 Standard output device, 298
sleep, 324 Standard value, 107
sleep library, 319 Statement of transactions, 132
COMPUTER PROGRAMMING PROBLEMS - R. PAL, S. PAL (Kindle edition) 479

Statistical distribution, 409 Tabulation, 205


Steady state, 291 Tapes, 190
Step-by-step, 2 tar, 323
Stevenson and Arce’s error distribution, 424 Taxable income, 131
Stock-taking, 403 Telephone billing, 339
Stopover, 177 Telephone index, 252
Storage location, 168 Temperature, 109
Store Accounting, 449 Template matching, 435
Stretch, 239 Terminal, 6
Structure of protein, 463 Terminators, 6
Structured Analysis and Design Technique, 339 Tessellations, 237
Structures, 36 Testing, 2
Stucki’s error distribution, 424 Theater hall, 129
Student’s records, 140 Thinking and braking distance, 212
Sub-directorie, 309 Thinning, 430, 432–434
Submission Cycle, 328 Thinning algorithm, 408
Subprogram, 107 Tide table, 212
Substring, 107 Time card, 134
Successful, 286
Time complexity, 365
Successful search, 362
Time sharing system, 456
Successive generations, 248
Token, 299
Supermarket, 148
Tools box, 463
Surcharge, 154
Trading company, 403
Survey question, 206
Traffic passing, 150
Swapped, 171
Transaction card, 114
Symbol table, 461
Transaction data, 178
Symbolic differentiation, 461
Transaction File, 178
Synchronization problem, 416
Transaction file, 396
Synonym handling method, 166
Transitive closure, 301
Syntax analyzer, 299
Transport operator, 181
Synthesis, 456
Transpose of matrix, 114
System software, 287
Travel agency, 456
System clock time, 290
Travel agent, 338
System design, 1
Travelling salesman, 132
System flow chart, 455
Tree structured directories, 296
System flow-chart, 327
Tree traversal, 358
System life cycle, 1
Trial period, 136
System time, 162
Trial-and-adjust, 265
System utilization, 294
Triangle, 109
t-distribution, 409 Triangle number, 187
Table printing, 205 Trigonometric equation, 213
Table slots, 165 Trouble shooting, 460
Tabular method, 348 Truck, 142
480 Index

Trucks, 181 Vessels, 151


Tuition fee, 154 Viruses, 458
TV receiver, 456 VISUAL BASIC, 7
Two-dimensional array, 114 Visual Basic, 2
Type setting, 264 Visual C, 2
Typing speed, 259 Visual information, 415
Typing test, 147 VLSI, 456
Vocabulary testing, 254
UF(unfertile), 389
Vowel search, 257
Unambiguous, 3
Undergraduate, 152 Wage rate, 149
Uniformly distributed binary image, 436 Waiting time, 290
Uniformly distributed random numbers, 115 Warshall, 301
Uninterrupted power supply, 352 Watermarking, 460
Union-Find, 361 Waves, 240
UNIX, 283 Web page, 463
Unix, 317 Weighting rule, 361
UNIX machine, 317 Wet spell, 124
UNIX systems, 319 White moves, 243
Unsubscripted variables, 271 Wild card, 312
Unsuccessful, 286 Winner-take-all, 462
Unsuccessful search, 362 Withdrawal, 178
Unutilized capacity, 181 Word Game, 159, 160
Upgrade, 352 Word game, 233
Upper case lettering, 187 Word hunt secretly game, 232
UPS, 352 Word processing system, 147
User satisfaction, 294 Word search, 257
utime, 323 Word squares, 234
Words and phrases, 259
Valley, 417
WORK-SHEET, 59
Variable length record, 461
Work-sheet, 399
Variable thresholding, 429
Work-Sheet Method, 79
Variable-length record, 284
Worst fit, 295
Variables, 34, 35
WTA, 462
Variance, 273
Vectors, 33
x-ray, 447
Vehicle, 263
Vehicle tracking, 463 Zhang and Suen’s algorithm, 430
verification, 456 zombie, 323
COMPUTER PROGRAMMING PROBLEMS
Computer Programming Problems is a reference book for the students
who wants to learn computer programming using any kind of programming
languages such as BASIC, FORTRAN, C, C++, etc. This book contains
sets of programming problems in various topic from mathematics, science
and technology to business.
This book is suitable for high school as well as undergraduate
students of computer science courses.

Key Features
• Presents conceptual and real-life problems
• Separate chapters for different areas
• Describes the problems in lucid manner with illustration
• Self-practice book

Ruma Pal completed her B.Sc. (Hons.), M.Sc. and Ph.D. from University
of Burdwan. She has contributed numerous papers to national and
international journals of repute.

Srimanta Pal completed his B.Sc. (Hons.) Mathematics from University of


Calcutta, B.Tech. (Hons.) Instrumentation and Electronics Engineering
and M.B.A. (Operations Research) from Jadavpur University, M.Tech.(Hons.)
Computer Science from Indian Statistical Institute and Ph.D. (Computer
Science and Engineering) from Indian Institute of Technology Kharagpur.
He also received FIE from The Institution of Engineers (India) and FIETE
from The Institution of Electronics and Telecommunication Engineers.
Dr. Pal has co-edited various issues and volumes in national and international
journals and conferences of repute. He has authored number of books with
different publishing houses like Oxford University Press, Springer, Elsivers,
World Scientific. His books are Neural Information Processing; Numerical
Methods: Principles, Analyses, and Algorithms; Mathematical Methods;
Systems Programming; Engineering Mathematics; Differential Equations; etc.

M-A-T-H
VALLEY
mathvalleypublication@gmail.com Price |100