edition
COMPUTER
PROGRAMMING
PROBLEMS
Ruma Pal
Srimanta Pal
MATH
VALLEY
COMPUTER PROGRAMMING
PROBLEMS
Kindle edition
Ruma Pal
Srimanta Pal
MATH
VALLEY
v
vi
MATH
VALLEY
Published in India by
Math Valley
mathvalleypublication@gmail.com
Copyright
c 2018 by Authors
vii
viii PREFACE
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 online devices.
Ruma Pal
July 18, 2018 Srimanta Pal
Contents
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
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Chapter 1
PROGRAMMING TOOLS AND TECHNIQUES
1.1 Introduction
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 Postimplementation 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
nonnumeric then we can write this scheme in a stepbystep fashion. These
stepbystep 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
alKhowarizmi 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
1.3 Flowchart
(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.
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
(2) BASIC is allpurpose: It is used for the following: (a) simple computa
tional work, (b) problem solving, (c) small business applications etc.
1.4.1 History
1.4.2 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 doubleprecision type declaration
character.
$ Dollar sign or string type declaration character.
! Exclamation point or singleprecision 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
1.5.1 History
1.5.2 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
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.256E3) 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 algollike block structured high
level computer programming languages with features that may support both
application and system programming.
1.6.1 History
1.6.2 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
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
1.7 C
1.7.1 History
1.7.2 Features
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 blockstructured.
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 bitwise 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 nway 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
1.8.1 History
1.8.2 Features
1.9 MATHEMATICA
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 today 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
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
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.4 Arithmetic
xˆy : power,
x : minus,
x/y : divide,
x y z or x*y*z : multiply,
x + y + z : add
In[1]:= 2 ˆ 100
Out[1]= 1267650600228229401496703205376
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}
Graphics
Function of one variable
In[1]:= Plot[Sin[Exp[x]], {x, 0, 4}];
Out[1]=
Out[1]=
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
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
In[1]:= result =
NDSolve[$\{y’’[t] + 0.1 y’[t] == Sin[y[t]],
COMPUTER PROGRAMMING PROBLEMS  R. PAL, S. PAL (Kindle edition) 33
Matrix Operations
The dot product of a matrix with its inverse gives the identity matrix.
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
(1) All builtin 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
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) 2dimensional 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
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
lefttoright termination but Pascal
does not use early termination crite
ria).
 or .OR. Boolean or operator (C evaluates left
toright termination but Pascal does
not use early termination criteria).
! not .NOT. Boolean not operator.
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 2way 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,n1,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
43
44 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES
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.
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*b4*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: ’,XRXI: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
#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*b4*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",XRXI);
}
}
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ˆ24*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’,XRXI);
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)}}
(g) WORKSHEET
A worksheet in Excel can be used to solve this quadratic equation. The work
sheet contains data as well as formula.
Suppose this worksheet 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.
Worksheet file name: QUARD.XLS
60 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES
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
**************************************
* 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
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
(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).
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
Programming Methods
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+finalmintests
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
Note: Endoffile 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
C ***************************************
C * FORTRAN program for Marks computation *
C ***************************************
Character*16 MaxName, Sname
74 CHAPTER 2. PROGRAMMING TWO PROBLEMS USING DIFFERENT LANGUAGES
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
Note: Endoffile 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
{***********************************************
* 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
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.
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:
Worksheet 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
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=CompositeMarksminimum_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=smmin;
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
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
}
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
FILECONTROL.
SELECT SCOREFILE ASSIGN TO DISK
ORGANIZATION IS SEQUENTIAL
ACCESS MODE IS SEQUENTIAL.
*******************************************
DATA DIVISION.
FILE SECTION.
FD SCOREFILE
LABEL RECORDS ARE STANDARD
VALUE OF FILEID IS ’SCORE.OUT’
DATA RECORD IS PRINTREC.
01 PRINTREC PIC X(60).
WORKINGSTORAGE SECTION.
01 MARKSREC.
05 MREGNO PIC X(6).
05 MNAME PIC X(16).
05 MTEST1 PIC 9(3)V9.
05 MTEST2 PIC 9(3)V9.
05 MTEST3 PIC 9(3)V9.
05 MFINAL PIC 9(3)V9.
01 MAXSCOREREC.
05 MXREGNO PIC X(6).
05 FILLER PIC X(2).
05 MXNAME PIC X(16).
05 FILLER PIC X(2).
05 MXTEST1 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 MXTEST2 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 MXTEST3 PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 MXFINAL PIC Z(3).9.
05 FILLER PIC X(2) VALUE SPACES.
05 MXSCORE PIC Z(3).9.
05 FILLER PIC X(7).
01 SCOREREC.
COMPUTER PROGRAMMING PROBLEMS  R. PAL, S. PAL (Kindle edition) 91
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
No errors or warnings
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>
<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
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 te−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.
(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
(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).
Cp
(2) = β,
Cv
1
(3) W = nR(T1 − T2 ),
β −1
(4) Cp −Cv = R/J, and
(5) T1 = 273 + t1 , T2 = 273 + t2
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
(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.
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 210 1545 5060 6570
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
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 semiperimeter (s) and area
(△) of the triangle, using the formulae
s = 12 (a + b + c) and △ = s(s − a)(s − b)(s − c).
p
(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?
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.
(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 + Byex−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 twodimensional 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 subprogram to find the length of a string.
39. Write a subprogram to copy a substring from a given string.
40. Write a subprogram 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
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 wellformed, while the sequence
(( ) ( ))) ( ) (( ) is not wellformed.
A sequence of open and closed parentheses is supplied to you as input. You
are required to determine if the sequence is wellformed.
(a) Draw the flowchart. (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 flowchart. (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
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 twodimensional 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 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
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. Flowchart 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 flowchart
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 flowchart 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.
Incometax 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 flowchart 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
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 flowchart 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 flowchart 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 RupeePaise form. Write a flowchart 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 flowchart, and (b) Write the program.
9. Each week the employees of a local manufacturing company turn in time
cards containing the following information:
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
flowchart, and (b) Write the program.
136 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 flowchart 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
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:
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 lefttoright 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 flowchart, 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 noninfinite 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 flowchart, and (b) Write the program.
Chapter 8
PROGRAMMING USING COMPLEX
CONDITIONS
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:
(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 onehalf
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:
cost per Km for each type of fuel (gas) for the entire period covered. Use
the following data (“P” is premium, “R” is regular):
(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 fillup 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:
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.
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 (MidI, MidII). 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
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 credithour up
through 15 credithours per quarter, with no additional charge beyond that
amount. Graduates are charged Rs.125 per credithour up through 12 cred
its, with no additional charge for more credits. If the student is an instate
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
outofstate 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
(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:
10. An electric utility has a variable billing rate per kilowatthour (KWH). The
rate is a function of the type of consumer and number of kilowatthours
used. There are three consumer types with these codes: C (Commercial), I
(Industrial) and R (Residential).
Each consumer category has its own rate per kilowatthour as a function of
the number of kilowatthours used per month as given in the table below:
COMPUTER PROGRAMMING PROBLEMS  R. PAL, S. PAL (Kindle edition) 157
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:
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 24hour
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
01 1 1
12 0 2
... ... ...
— — —
Total 5 7
COMPUTER PROGRAMMING PROBLEMS  R. PAL, S. PAL (Kindle edition) 159
(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.)
(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
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
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 Romanrepresented 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%.
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.
(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
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.
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
171
172 CHAPTER 9. ADVANCED PROGRAMMING PROBLEMS
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
(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 CalcuttaKolkata 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
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 flowchart 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).
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
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
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, 2years, 3years, 4years, 5years) 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
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
starts at column 1. Any blanks are at the right end of the string. No blanks
are interspersed among the nonblank characters. The second input line con
tains a similar string of nonblank 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 nonblank char
acters, i.e. move them to the left so that no blanks remain embedded among
the nonblank 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 keyboard. 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)
(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
(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.
1. Write a program which will take 2 number as input and output the following:
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) 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
(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
nonnumerical 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 20digit 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
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 counterkeeper 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
205
206 CHAPTER 12. PROGRAMMING FOR TABLE PRINTING
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 builtin Sine and Cosine functions, print a table comparing
these against your values.
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 subprograms for finding roots, compare your val
ues against those of the subprogram. 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 crosssection 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 FermiDirac 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
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
(a) Test the formula using known data (e.g., for a right angle triangle).
(b) Find, by making the computer do trialanderror testing for you, the
values of a, b and c for maximum if s = 24.
215
216 CHAPTER 13. PROGRAMMING GEOMETRICAL PROBLEMS
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 circumcircle.
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 coordinate (x, y) to an
angular coordinate system. (Where the angle between two axis is ω ).
13. Write a program to convert a 3D rectangular cartesian coordinate (x, y, z)
to a cylindrical and a spherical coordinate 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 nonplanner 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 cocircle.
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 halfplane 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
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.
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 nD.
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
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 leapyear
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 leapyears.
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 (hourhand and minutehand) 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 12hour indicated clock.
18. Write a program to compute the time when the angle between the two hands
is θ o for a 24hour 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 workstudy
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:
(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:
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.
(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.
231
232 CHAPTER 15. PROGRAMMING FOR COMPUTER GAMES
3. [Highlow game] The HighLow 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 ladderclimbing or snakeswallowing.
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]
example, any letter in position x could be used before or after that in po
sition A. Threeletter 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.
(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).
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.
(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.
(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
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:
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.
(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 motorways  as seen from the motorway. 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 userdefined 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 rubbingout 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
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.]
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
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
(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
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 leapyear” or “not a leapyear”.
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
(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 twovariable 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 twovariable 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:
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 2dimensional character
array of size 3 × 500. The data could be built up over weeks/months if the
program is resaved 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 onevariable 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
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 4letter 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 5letter and 6letter palindromes.
(d) Write a generalized program for palindrome checking.
(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 6letter 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 squarearea 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 twodimensional (2D) 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.
Nonkey 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 flowchart 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 flowchart 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 subheadings and the total number of such students at the
bottom of the list.
π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 flowchart
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 flowcharts 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 trialandadjust 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
(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
269
270 CHAPTER 17. PROBLEM SET FOR FORTRAN
(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)
(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.
(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.
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
(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.
(2) Use different output field width I110 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.
26. Consider the following input data, input format and output format.
Input Data Input Format Output Format
12345E2 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
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.
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 cricketmatch was held between two teams A and B in which
one of the two teams had won. The complete scorecard 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
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 to open this file and read that stored string for dis
play.
18. Write a program and test the following: Try to set the readonly 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
(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 fixedlength record
file using a replacement procedure.
27. Write a program so that it can delete and add records to a variablelength
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
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 messbill for each course sorted in the roll numberwise. The charges for
breakfast, lunch and dinner is to be input through keyboard.
30. Write a program to search a key in a Btree.
31. Write an interactive program that allows user to find, insert and delete keys
from a Btree.
32. Write a Btree program for string keys (not only single characters).
33. Write a program that builds a Btree 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 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:
287
288 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE
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. [LongTerm 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 reallife 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
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 MSDOS 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
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 crossassembler 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
CTRLC, 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
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<LStatement>end.
3. <Lstatement> ::= <LStatement> <Statement>; 
<Statement>;;
300 CHAPTER 19. PROGRAMMING PROBLEMS FOR SYSTEM SOFTWARE
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
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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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,
+ 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
+ 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
..
.
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 subdirectories of the root directory are created
by users. The following gives you a hierarchical structure to be created in
floppy disk.
ROOT
@
@
@
@
@
@@
PERSONAL OFFICIAL
309
310 CHAPTER 20. PRACTICE PROBLEMS FOR DOS
ROOT
@
@
@
@
@
@@
PERSONAL OFFICIAL
ACCOUNT ACCOUNT
Dear Sir,
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 wellknown 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
27. Floppy1 contains 30 executable files and Floppy2 contains 45 batch files
with same other files. Write a batch file to delete all executable files from
floppy1 and all batch files from floppy2 on a single floppy drive system.
28. A floppy has the following directory and subdirectory structure.
last
letter current
future
newyear
diary
oldyear
ROOT
self
appo
office
self
misl buy
gift
(letter, diary, gift etc. all are subdirectories containing files and/or sub
directories)
Write a DOS batch file to clean all subdirectories 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.
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
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)
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>.
(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 subdirectories, it sends the names of these sub
directories to the parent process.
(3) The parent, on receiving the path names of the subdirectories, cre
ates new child processes (subject to the maximum limit n as specified by
the user), one for each subdirectory, 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 subdirectories 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.
of voting, between 10 AM and 5PM, any faculty member may cast one vote
by giving the command vote <voterid> <candidateid> where <voter
id> and ¡candidateid¿ 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:
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 readwrite 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 userread 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:
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
#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 setuserID.
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 timeofday 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.
2. Prepare the systems flowchart 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
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.
(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
Validinvoice 
(1)
&%
BOOK
6
PURCHASE ORDERS
(2) '$
ADD
 
SALE TO
Customerdetails BALANCE
Customerdetails
&%
(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) '$
Paidinvoice Determine Taxtotal 
&%
tax
DestinationName  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 online.
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.
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 setup 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
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
online processing system on the DFD.
(3) Describe how the online processing system will work. Your answer
should not exceed 100 words (1015 lines).
13. ABC is an international trade corporation. Customer orders are received via
mail, phone, telex, email 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:
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:
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
(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 doubleseated). 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, icecream 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 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 coursewise 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.
One can program the above activities using a set of decisionmaking 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 flowchart 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.
Let c1 , c2 , c3 are the three conditions and vi j are values then the expositive
table used to represent the rules for decisionmaking 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
(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.
(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
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.
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
1. Implement a circular queue (Q) using an array of fixed size. Write the
CreateQ, AddQ, DeleteQ, EmptyQ 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 binarysearch 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 levelbylevel 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 levelbylevel 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 worstcase.
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 Englishlanguage 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 nonrecursive 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 minimumcost 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 minimumcost 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 minimumcost spanning tree of each part, then connect them with the
minimumlength 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 UnionFind 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 keyfield has k bytes (the value of the pri
mary keyfield 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 Btree 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 interrelationship.
For administrative purposes, the country is divided into a number of zones
(e.g., S, NE etc.), which are nonoverlapping in area. Each zone consists of
a few states (once again nonoverlapping 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
(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
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:
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
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]
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
(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 entityrelationship (ER) 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 oneone and which are manyone. 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
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
(3) Balance,
(4) Credit limit, and
(5) Discount.
b) For each order:
(1) Order number (unique);
(2) Heading information, i.e. customer number, shipto 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 entityrelationship 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
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.
• 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 carowner 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
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
• 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.
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 entityrelationship (ER) 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 nonoverlapping in area. Each zone consists of a
few states (once again nonoverlapping 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
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:
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 ER 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 nonagricultural income
also. A village has three types of lands defined as HF(highlyfertiled), MF
(moderatelyfertile) 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
monocropping or multicropping (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 ER 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 parttime. Similar records are kept for both the types.
However, a regular employee gets a monthly salary for which basicsalary is
kept in the record, whereas for a parttime one a consolidated allowance is
paid and recorded. An employee is identified by his employee number. His
name, address, dateofbirth and dateofjoining 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 parttime specialists.
For each attending doctor his field of specialization is recorded. Besides
this, a doctor is treated like any other parttime 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 ER 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
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
118 Last Name 6065 Pin Code
19 First Initial 6671 Date Subscription
Ends (Numeric)
20 Middle Initial 7277 Account Number
(Numeric)
4150 Town/City 78 Sex Code (Alpha
betic)
5159 State 7980 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 callletters 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 keyfields, nonkey
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 615
Publisher 5160
thor’s last
Year published 6164
name
Cost (9999V99) 6570
Second 1625
Edition 7175
author’s last
Catalogue number 7680
name
Title of 2650
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
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 flowchart 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
399
400 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET
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 breakeven chart showing the breakeven point. If the selling price
is reduced to Rs.18 per unit, what will be the new breakeven 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
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 stocktaking 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.)
Workinprogress 3,800 2,500
Materials 22,000 15,000
Finished stock 17,000 32,000
404 CHAPTER 26. SOLVE PROBLEMS USING WORKSHEET
(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.
Longterm 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 = Speedup 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 speedup
values with the number of processor for a fixed image size and visaversa.
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) Chisquare 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
16. The successful (CN ) and unsuccessful (CN′ ) search performance (without cel
lar) for different chained hashing algorithms are given below:
(3) EarlyInsertion
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 nonnegative solution to the equation
1
e−y + y = .
b
(4) VariedInsertion
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
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
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 (ChargeCoupledDevice) 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 Xray, 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., onetoone 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
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)
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)
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
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
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,j1] := A[i+1,j1] + 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(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
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
Second subiteration
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 (clockwise)
sequence P2 , P3 , · · · , P9 , P2 of 8neighbors of P1 .
B(P1 ) = Number of 1’s among the 8neighbors 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 subiteration: P1 := P1 (not f (P1 ) + (P4 ∗ P6 (P2 + P8 ))).
Second subiteration: 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 drawbacks 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 8neighbor should be in between 2 and 6, and
(3) There should not contain more than one ‘01’ pattern of its 8neighbors
in the clockwise direction.
and the window is defined as
P9 P2 P3
P8 P1 P4 .
P7 P6 P5
First subiteration:
P1 := P1 ((not f (P1 )) + f (P4 )P2 P6 + f (P6 )P8 P4 + f (P4 ) f (P5 ) f (P6 ))
Second subiteration:
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
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)
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 (13) 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;
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 8neighbors.
(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 4connected and 8connected 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.
441
442 CHAPTER 28. CASE STUDIES
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 nondoctors 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
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 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 nonalphabetic 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
Rule 6: A valid word should not contain any substring of length three of
identical letter. The consecutive nonoccurrence 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.210) 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).
• EntityRelationship (ER) diagram (if database project).
• DataFlowDiagram (DFD) .
• System flow chart etc.
455
456 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:
(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
92. Implement multilayer perceptron (MLP) and radial basis function (RBF)
algorithms for function approximation and their parameter choice.
93. Selforganization feature maps (SOFM) for clustering.
94. Implement winnertakeall (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
1. Aho A.V., Sethi R. & Ullman J.D. Compilers: Principles, Techniques and Tools. AddisonWesley Publishing Company.
2. Balagurusamy E. COBOL Programming: A SelfStudy 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. AddisonWesley Publishing Company, New York.
7. Bidgoli H. Advanced LOTUS 123 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 McGrawHill Publishing Company Ltd., New Delhi.
11. Donovan J.J. Systems Programming. McGrawHill International Book Company.
12. Foley J.D., van Dam A., Feiner S.K. & Hughes J.F. Computer Graphics: Principles and Practice. AddisonWesley Publishing
Company.
13. Folk M.J. & Zoellick B. File Structures. AddisonWesley Publishing Company, New York.
14. Gargill T. C++ Programming Style. AddisonWesley Publishing Company.
15. Gonzalez R.C. & Woods R.E. Digital Image Processing. AddisonWesley 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 McGrawHill.
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. Objectoriented 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. GWBASIC 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 MicroProlog. Affiliated EastWest Press.
35. Sharma K.D. Programming in Fortran IV. Affiliated EastWest 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. AddisonWesley Publishing Company.
41. Subramaniam N. Programming for Basic.
42. Swan T. Mastering Turbo Pascal.
43. Taylor P.H. 3D Graphics Programming in Windows. AddisonWesley 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
467
468 Index
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 EntityRelationship (ER) 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
Key Features
• Presents conceptual and reallife problems
• Separate chapters for different areas
• Describes the problems in lucid manner with illustration
• Selfpractice 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.
MATH
VALLEY
mathvalleypublication@gmail.com Price 100