0% found this document useful (0 votes)
18 views22 pages

Introduction To Algorithms and Programming Concepts

This document discusses algorithms and their key features. It begins by defining an algorithm as an effective procedure for solving a problem in a finite number of steps. It then discusses the different ways algorithms can be represented, including step-form, pseudocode, flowcharts, and Nassi-Schneiderman. The key features of algorithms are identified as sequence, decision, and repetition. Sequence means each step is executed in order, decision incorporates if/then conditional logic, and repetition allows steps to be repeated through loops.

Uploaded by

Four Ayes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
18 views22 pages

Introduction To Algorithms and Programming Concepts

This document discusses algorithms and their key features. It begins by defining an algorithm as an effective procedure for solving a problem in a finite number of steps. It then discusses the different ways algorithms can be represented, including step-form, pseudocode, flowcharts, and Nassi-Schneiderman. The key features of algorithms are identified as sequence, decision, and repetition. Sequence means each step is executed in order, decision incorporates if/then conditional logic, and repetition allows steps to be repeated through loops.

Uploaded by

Four Ayes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

114 Computer Fundamentals and Programming in C

c
h
Introduction to Algorithms a
p
and Programming t

Concepts e
r 7

LEARNING
OBJECTIVES
After studying this chapter, the readers will be able to

∑ explain algorithms and the key features of an algorithm— ∑ explain the concept of tracing the correctness of an
sequence, decision, and repetition algorithm
∑ learn the different ways of stating algorithms—step-form, ∑ discuss the method of implementing an algorithm in a
flowchart, etc. program
∑ define variables, types of variables, and naming ∑ explain structural programming and the process of
conventions for variables programming
∑ decide a strategy for designing algorithms

7.1 Algorithms It is effective, which means that an answer is found and it


has a finite number of steps. A well-designed algorithm will
To solve any problem a plan is needed. This plan is a proce- always provide an answer; it may not be the desired answer
dure to solve the problem in question. The procedure has to but there will be an answer. It may be that the answer is that
be based on definite reasoning and logic to obtain a result. there is no answer. A well-designed algorithm is also guaran-
How can such plans be formed? The following sections dis- teed to terminate.
cuss the various ways a procedure-wise plan can be made to
solve any problem. 7.1.2  Different Ways of Stating Algorithms
Algorithms may be represented in various ways. There are
7.1.1  What is an Algorithm?
four ways of stating algorithms.
Computer scientist Niklaus Wirth stated that These are as follows:
Program = Algorithms + Data
∑ Step-form
An algorithm is a part of the plan for the computer pro-
gram. In fact, an algorithm is ‘an effective procedure for ∑ Pseudo-code
solving a problem in a finite number of steps’. ∑ Flowchart
Introduction to Algorithms and Programming Concepts 115
∑ Nassi-Schneiderman ∑ Repetition (also known as iteration or looping)
In the step-form representation, the procedure of solving Therefore, an algorithm can be stated using three basic
a problem is stated with written statements. Each statement constructs: sequence, decision, and repetition.
solves a part of the problem and these together complete the Sequence
solution. The step-form uses just normal language to define
Sequence means that each step or process in the algorithm is
each procedure. Every statement, that defines an action, is
executed in the specified order. In the above example, each
logically related to the preceding statement. This algorithm process must be in the proper place otherwise the algorithm
has been discussed in the following section with the help of will fail.
an example.
The decision constructs—if ... then, if ... then ...
The pseudo-code is a written form representation of the
else...
algorithm. However, it differs from the step form as it uses a
restricted vocabulary to define its action of solving the prob- In algorithms the outcome of a decision is either true or false;
lem. One problem with human language is that it can seem there is no state in between. The outcome of the decision is
based on some condition that can only result in a true or false
to be imprecise. But the pseudo-code, which is in human lan-
value. For example,
guage, tends toward more precision by using a limited vo-
cabulary. if today is Friday then collect pay
Flowchart and Nassi-Schneiderman are graphically orient- is a decision and the decision takes the general form:
ed representation forms. They use symbols and language to if proposition then process
represent sequence, decision, and repetition actions. Only the A proposition, in this sense, is a statement, which can only
flowchart method of representing the problem solution has be true or false. It is either true that ‘today is Friday’ or it is
been explained with several examples. The Nassi-Schneider- false that ‘today is not Friday’. It can not be both true and
man technique is beyond the scope of this book. false. If the proposition is true, then the process or procedure
that follows the then is executed. The decision can also be
note stated as:
∑ An algorithm is an effective procedure for solving a problem if proposition
in a finite number of steps. then process1
∑ A program is composed of algorithm and data.
else process2
∑ The four common ways of representing an algorithm are the
step-form, pseudo-code, flowchart, and Nassi-Schneiderman. This is the if … then … else … form of the decision.
This means that if the proposition is true then execute pro-
cess1, else, or otherwise, execute process2.
7.1.3  Key Features of an Algorithm and the Step- The first form of the decision if proposition then process
form has a null else, that is, there is no else.
Here is an example of an algorithm, for making a pot of tea. The repetition constructs—repeat and while
1. If the kettle does not contain water, then fill the kettle. Repetition can be implemented using constructs like the re-
2. Plug the kettle into the power point and switch it on. peat loop, while loop, and if.. then .. goto .. loop.
3. If the teapot is not empty, then empty the teapot. The Repeat loop is used to iterate or repeat a process or
4. Place tea leaves in the teapot. sequence of processes until some condition becomes true. It
has the general form:
5. If the water in the kettle is not boiling, then go to step 5.
Repeat
6. Switch off the kettle.
Process1
7. Pour water from the kettle into the teapot. Process2
It can be seen that the algorithm has a number of steps and ..............
that some steps (steps 1, 3, and 5) involve decision-making ………..
and one step (step 5 in this case) involves repetition, in this ProcessN
case the process of waiting for the kettle to boil. Until proposition
From this example, it is evident that algorithms show these Here is an example.
three features: Repeat
∑ Sequence (also known as process) Fill water in kettle
∑ Decision (also known as selection) Until kettle is full
116 Computer Fundamentals and Programming in C

The process is ‘Fill water in kettle,’ the proposition is known, nor can the designer do an analysis beforehand to
‘kettle is full’. find it out. The analysis of algorithms for their likelihood of
The Repeat loop does some processing before testing the termination is called termination analysis.
state of the proposition. Correctness
What would happen if in the above example the kettle is
already full? If the kettle is already full at the start of the Re- The prepared algorithm needs to be verified for its correct-
peat loop, then filling more water will lead to an overflow. ness. Correctness means how easily its logic can be argued to
This is a drawback of the Repeat construct. satisfy the algorithm’s primary goal. This requires the algo-
In such a case the while loop is more appropriate. The rithm to be made in such a way that all the elements in it are
above example with the while loop is shown as follows: traceable to the requirements.
while kettle is not full Correctness requires that all the components like the data
fill water in kettle structures, modules, external interfaces, and module inter-
Since the decision about the kettle being full or not is connections are completely specified.
made before filling water, the possibility of an overflow is In other words, correctness is the degree to which an algo-
eliminated. The while loop finds out whether some condition rithm performs its specified function. The most common mea-
is true before repeating a process or a sequence of processes. sure of correctness is defects per Kilo Lines of Code (KLOC)
If the condition is false, the process or the sequence of that implements the algorithm, where defect is defined as the
processes is not executed. The general form of while loop is: verified lack of conformance to requirements.
while proposition
begin
note
Process 1 ∑ The key features of an algorithm are sequence, selection,
Process 2 and repetition.
……….. ∑ The stepwise form has sequence, selection, and repeti-
………... tion constructs.
Process N ∑ Termination means the action of closing. A well-designed al-
end gorithm has a termination.
The if .. then goto .. is also used to repeat a process or ∑ Correctness of algorithm means how easily its logic can be
argued to meet the algorithm’s primary goal.
a sequence of processes until the given proposition is false.
In the kettle example, this construct would be implemented
as follows: 7.1.4  What are Variables?
1. Fill some water in kettle So long, the elements of algorithm have been discussed. But a
2. if kettle not full then goto 1 program comprises of algorithm and data. Therefore, it is now
So long as the proposition ‘kettle not full’ is true the pro- necessary to understand the concept of data. It is known that
cess, ‘fill some water in kettle’ is repeated. The general form data is a symbolic representation of value and that programs
of if .. then goto .. is: set the context that gives data a proper meaning. In programs,
Process1 data is transformed into information. The question is, how is
Process2 data represented in programs?
………. Almost every algorithm contains data and usually the data
………. is ‘contained’ in what is called a variable. The variable is a
ProcessN
container for a value that may vary during the execution of
if proposition then goto Process1
the program. For example, in the tea-making algorithm, the
Termination level of water in the kettle is a variable, the temperature of
The definition of algorithm cannot be restricted to proce- the water is a variable, and the quantity of tea leaves is also a
dures that eventually finish. Algorithms might also include variable.
procedures that could run forever without stopping. Such a Each variable in a program is given a name, for example,
procedure has been called a computational method by Knuth ∑ Water_Level
or calculation procedure or algorithm by Kleene. However,
∑ Water_Temperature
Kleene notes that such a method must eventually exhibit
∑ Tea_Leaves_Quantity
‘some object.’ Minsky (1967) makes the observation that, if
an algorithm has not terminated, then how can the follow- and at any given time the value, which is represented by Wa-
ing question be answered: “Will it terminate with the correct ter_Level, for instance, may be different to its value at some
answer?” Thus the answer is: undecidable. It can never be other time. The statement
Introduction to Algorithms and Programming Concepts 117
if the kettle does not contain water then fill the kettle The algorithms and programs can benefit from using nam-
could also be written as ing conventions for processes too.
if Water_Level is 0 then fill the kettle
or note
if Water_Level = 0 then fill the kettle ∑ Data is a symbolic representation of value.
At some point Water_Level will be the maximum value, ∑ A variable, which has a name, is a container for a value
whatever that is, and the kettle will be full. that may vary during the execution of the program.

Variables and data types


The data used in algorithms can be of different types. The 7.1.5  Subroutines
simplest types of data that an algorithm might use are A simple program is a combination of statements that are
∑ numeric data, e.g., 12, 11.45, 901, etc. implemented in a sequential order. A statement block is a
∑ alphabetic or character data such as ‘A’, ‘Z’, or ‘This is group of statements. Such a program is shown in Fig. 7.1(a).
alphabetic’ There might be a specific block of statement, which is also
known as a procedure, that is run several times at different
∑ logical data, that is, propositions with true/false values
points in the implementation sequence of the larger program.
Naming of variables This is shown in Fig.7.1(b). Here, this specific block of state-
One should always try to choose meaningful names for vari- ment is named ‘procedure X’. In this example program, the
ables in algorithms to improve the readability of the algo- ‘procedure X’ is written twice in this example. This enhances
rithm or program. This is particularly important in large and the size of the program. Since this particular procedure is re-
complex programs. quired to be run at two specific points in the implementa-
In the tea-making algorithm, plain English was used. It has tion sequence of the larger program, it may be treated as a
been shown how variable names may be used for some of the separate entity and not included in the main program. In fact,
algorithm variables. In Table 7.1, the right-hand column con- this procedure may be called whenever required as shown in
tains variable names which are shorter than the original and Fig.7.1(c). Such a procedure is known as a subroutine.
do not hide the meaning of the original phrase. Underscores
have been given to indicate that the words belong together Start Start Start

and represent a variable.


Statement Statement Statement
1 1 1 Subroutine
Table 7.1  Algorithm using variable names

Algorithm in plain Algorithm using variable Statement Procedure Statement Procedure


English names 2 X 2 X
1. If the kettle does not 1. If kettle_empty then fill the
contain water, then fill the kettle. Statement Statement Statement
kettle. 3 2 3

2. Plug the kettle into the 2. Plug the kettle into the
Statement Procedure Statement
power point and switch it power point and switch it 4 X 4
on. on.
3. If the teapot is not empty, 3. If teapot_not_empty then   
then empty the teapot. empty the teapot.
4. Place tea leaves in the 4. Place tea leaves in the Statement Statement Statement
N N N
teapot. teapot.
5. If the water in the kettle is 5. If water_not_boiling then Call
End End End
not boiling then go to go to step 5. Return
step 5. (a) A structure (b) A structure (c) A structure
of a simple of a program of a program
6. Switch off the kettle. 6. Switch off the kettle. program with repeated using a
procedures subroutine
7. Pour water from the kettle 7. Pour water from the kettle
into the teapot. into the teapot. Fig. 7.1  Program structures

There are no hard and fast rules about how variables Therefore, a subroutine, also known as procedure, method
should be named but there are many conventions. It is a good or function, is a portion of instruction that is invoked from
idea to adopt a conventional way of naming variables. within a larger program to perform a specific task. At the
118 Computer Fundamentals and Programming in C

same time the subroutine is relatively independent of the re- 4. The arithmetic operators that will be used in the expres-
maining statements of the larger program. The subroutine be- sions are
haves in much the same way as a program that is used as one (i) ‘←’ ….Assignment (the left-hand side of ‘←’ should
step in a larger program. A subroutine is often written so that always be a single variable)
it can be started (“called”) several times and/or from several Example: The expression x ← 6 means that a
places during a single execution of the program, including value 6 is assigned to the variable x. In terms of
from other subroutines, and then branch back (return) to the memory storage, it means a value of 6 is stored at
next instruction after the “call”, once the subroutine’s task is a location in memory which is allocated to the vari-
done. Thus, such subroutines are invoked with a CALL state- able x.
ment with or without passing of parameters from the calling (ii) ‘+’….. Addition
program. The subroutine works on the parameters if given to
Example: The expression z ← x + y means the
it, otherwise it works out the results and gives out the result
value contained in variable x and the value con-
by itself and returns to the calling program or pass the results
tained in variable y is added and the resulting value
to the calling program before returning to it.
obtained is assigned to the variable z.
The technique of writing subroutine has some distinct
advantages. The subroutine reduces duplication of block (iii) ‘–’….. Subtraction
of statements within a program, enables reuse of the block Example: The expression z ← x – y means the
of statements that forms the subroutine across multiple pro- value contained in variable y is subtracted from the
grams, decomposes a complex task into simpler steps, di- value contained in variable x and the resulting value
vides a large programming task among various programmers obtained is assigned to the variable z
or various stages of a project and hides implementation de- (iv) ‘*’….. Multiplication
tails from users. Example: Consider the following expressions writ-
However, there are some disadvantages in using subrou- ten in sequence:
tines. The starting or invocation of a subroutine requires some x←5
computational overhead in the call mechanism itself. The sub- y←6
routine requires some well-defined housekeeping techniques at z← x*y
its entry and exit from it. The result of the multiplication between x and y is
30. This value is therefore assigned to z.
note (v) ‘/’….. Division
∑ A subroutine is a logical collection of instructions that is in- Example: The following expressions written in se-
voked from within a larger program to perform a specific task. quence illustrates the meaning of the division opera-
∑ The subroutine is relatively independent of the remain- tor :
ing statements of the program that invokes it. x ← 10
∑ A subroutine can be invoked several times from several y←6
places during a single execution of the invoking program.
z ← x/y
∑ After completing the specific task, a subroutine returns
to the point of invocation in the larger program.
The quotient of the division between x and y is 1
and the remainder is 4. When such an operator is
used the quotient is taken as the result whereas the
Some examples on developing algorithms using
remainder is rejected. So here the result obtained
step-form
from the expression x/y is 1 and this is assigned to z.
For illustrating the step-form the following conventions are
5. In propositions, the commonly used relational operators
assumed:
will include
1. Each algorithm will be logically enclosed by two state-
(i) ‘>’ ….. Greater than
ments START and STOP.
Example: The expression x > y means if the value
2. To accept data from user, the INPUT or READ state-
contained in x is larger than that in y then the out-
ments are to be used.
come of the expression is true, which will be taken
3. To display any user message or the content in a variable, as 1. Otherwise, if the outcome is false then it would
PRINT statement will be used. Note that the message be taken as 0.
will be enclosed within quotes.
(ii) ‘<=’ …..Less than or equal to
4. There are several steps in an algorithm. Each step results
in an action. The steps are to be acted upon sequentially Example: The expression x <= y implies that if the
in the order they are arranged or directed. value held in x is either less than or equal to the
Introduction to Algorithms and Programming Concepts 119
value held in y then the outcome of the expression (ii) ‘OR’ …… Disjunction
is true and so it will be taken as 1. The outcome of an expression is true or 1 when any-
But if the outcome of the relational expression is one of the propositions OR-ed is true otherwise it is
false then it is taken as 0. false or 0.
(iii) ‘<’ …… Less than Example:  Consider the expressions
Example: Here the expression x < y implies that x←2
if the value held in x is less than that held in y then y←1
the relational expression is true, which is taken as 1, x = 2 OR y = 0
otherwise the expression is false and hence will be Here, the proposition ‘x = 2’ is true since x holds 2
taken as 0. while the proposition ‘y = 0’ is untrue or false. Hence
(iv) ‘=’ …… Equality the third expression may be represented as ‘true’ OR
Example: The expression x = y means that if the ‘false’ the outcome for which is true or 1.
value in x and that in y are same then this relation- (iii) ‘NOT’ …… Negation
al expression is true and hence the outcome is 1 If outcome of a proposition is ‘true’, it becomes
otherwise the outcome is false or 0. ‘false’ when negated or NOT-ed.
(v) ‘>=’ …… Greater than or equal to Example:  Consider the expression
Example: The expression x >= y implies that if x←2
the value in x is larger or equal to that in y then NOT x = 2
the outcome of the expression is true or 1, other- The proposition ‘x = 2’ is ‘true’ as x contains the
wise it is false or 0. value 2. But the second expression negates this by
(vi) ‘!=’ …… Non- equality the logical operator NOT which gives an outcome
Example: The expression x != y means that if ‘false’.
the value contained in x is not equal to the value
contained in y then the outcome of the expression Examples
is true or 1, otherwise it is false or 0.
1. Write the algorithm for finding the sum of any two numbers.
Note:  The ‘equal to (=)’ operator is used both for as-
signment as well as equality specification. When used in Solution Let the two numbers be A and B and let their sum be
proposition, it specifies equality otherwise assignment. To equal to C. Then, the desired algorithm is given as follows:
differentiate ‘assignment’ from ‘equality’ left arrow (←) 1. START
may be used. For example, a ←b is an assignment but a = 2. PRINT “ENTER TWO NUMBERS”
b is a proposition for checking the equality. 3. INPUT A, B Add values assigned
4. C ¨ A + B to A and B and as-
6. The most commonly used logical operators will be sign this value to C
5. PRINT C
AND, OR and NOT. These operators are used to specify
6. STOP
multiple test conditions forming composite proposition.
Explanation  The first step is the starting point of the algorithm.The
These are
next step requests the programmer to enter the two numbers that have
(i) ‘AND’…… Conjunction to be added. Step 3 takes in the two numbers given by the program-
The outcome of an expression is true or 1 when both mer and keeps them in variables A and B. The fourth step adds the
the propositions AND-ed are true otherwise it is two numbers and assigns the resulting value to the variable C.The fifth
false or 0. step prints the result stored in C on the output device. The sixth step
Example:  Consider the expressions terminates the procedure.
x←2 2. Write the algorithm for determining the remainder of a division opera-
y←1 tion where the dividend and divisor are both integers.
x = 2 AND y = 0 Solution Let N and D be the dividend and divisor, respectively. As-

In the above expression the proposition ‘x = 2’ is sume Q to be the quotient, which is an integer, and R to be the remain-
true because the value in x is 2. Similarly, the propo- der. The algorithm for the given problem is as follows.
sition ‘y = 0’ is untrue as y holds 1 and therefore 1. START
this proposition is false or 0. Thus, the above expres- 2. PRINT “ENTER DIVIDEND”

sion may be represented as ‘true’ AND ‘false’ the 3. INPUT N


4. PRINT “ENTER DIVISOR”
outcome for which is false or 0.
120 Computer Fundamentals and Programming in C

5. INPUT D 5. IF B > A THEN


6. Q ¨ N/D (Integer division) PRINT “B IS GREATER THAN A”
7. R ¨ N – Q * D 6. IF A = B THEN
Only integer value PRINT “BOTH ARE EQUAL”
8. PRINT R
is obtained and 7. STOP
9. STOP remainder ignored
Explanation The first step indicates the starting point of the algorithm.
Explanation The first step indicates the starting point of the algorithm. The next step prints a message asking for the entry of the two num-
The next step asks the programmer to enter the dividend value. The bers. In step 3 the numbers entered are kept in the variables A and
third step keeps the dividend value in the variable N. Step 4 asks for the B. In steps 4, 5 and 6, the values in A, B and C are compared with
divisor value to be entered. This is kept in the variable D. In step 6, the the IF ...THEN construct. The relevant message is printed whenever
value in N is divided by that in D. Since both the numbers are integers,
the proposition between IF and THEN is found to agree otherwise the
the result is an integer. This value is assigned to Q. Any remainder in
next step is acted upon. But in any case one of the message would be
this step is ignored. In step 7, the remainder is computed by subtracting
printed because at least one of the propositions would be true. Step 7
the product of the integer quotient and the integer divisor from integer
dividend N. The computed value of the remainder is an integer here and terminates the procedure.
obviously less than the divisor. The remainder value is assigned to the 5. Write an algorithm to check whether a number given by the user is odd
variable R. This value is printed on an output device in step 8. Step 9 or even.
terminates the algorithm.
Solution Let the number to be checked be represented by N. The num-
3. Construct the algorithm for interchanging the numeric values of two ber N is divided by 2 to give an integer quotient, denoted by Q. If the
variables. remainder, designated as R, is zero, N is even; otherwise N is odd. This
Solution Let the two variables be A and B. Consider C to be a third
logic has been applied in the following algorithm.
1. START
variable that is used to store the value of one of the variables during the
2. PRINT “ENTER THE NUMBER”
process of interchanging the values. 3. INPUT N
The algorithm for the given problem is as follows. 4. Q ¨ N/2 (Integer division)
1. START 5. R ¨ N — Q * 2
6. IF R = 0 THEN
2. PRINT “ENTER THE VALUE OF A & B”
PRINT “N IS EVEN”
3. INPUT A, B 7. IF R != 0 THEN
4. C ¨ A A B PRINT “N IS ODD”
step 5
5. A ¨ B 8. STOP
6. B ¨ C step 4 step 6
Explanation The primary aim here is to find out whether the remainder

7. PRINT A, B after the division of the number with 2 is zero or not. If the number is
C
8. END even the remainder after the division will be zero. If it is odd, the remain-
Explanation Like the previous examples, the first step indicates the der after the division will not be zero. So by testing the remainder it is
starting point of the algorithm. The second step is an output message possible to determine whether the number is even or odd.
asking for the two values to be entered. Step 3 puts these values into The first step indicates the starting point of the algorithm while the
the variables A and B. Now, the value in variable A is copied to variable next prints a message asking for the entry of the number. In step 3,
C in step 4. In fact the value in A is saved in C. In step 5 the value in the number is kept in the variable N. N is divided by 2 in step 4. This
variable B is assigned to variable A. This means a copy of the value in B operation being an integer division, the result is an integer. This result
is put in A. Next, in step 6 the value in C, saved in it in the earlier step 4
is assigned to Q. Any remainder that occurs is ignored. Now in step 5,
is copied into B. In step 7 the values in A and B are printed on an output
the result Q is multiplied by 2 which obviously produces an integer that
device. Step 8 terminates the procedure.
is either less than the value in N or equal to it. Hence in step 5 the dif-
4. Write an algorithm that compares two numbers and prints either the ference between N and Q * 2 gives the remainder. This remainder value
message identifying the greater number or the message stating that is then checked in step 6 and step 7 to print out that it is either even or
both numbers are equal. odd respectively. Step 8 just terminates the procedure.
Solution This example demonstrates how the process of selection or
6. Print the largest number among three numbers.
decision making is implemented in an algorithm using the step-form.
Here, two variables, A and B, are assumed to represent the two num- Solution Let the three numbers be represented by A, B, and C. There
bers that are being compared. The algorithm for this problem is given can be three ways of solving the problem. The three algorithms, with
as follows. some differences, are given below.
1. START 1. START
2. PRINT “ENTER TWO NUMBERS” 2. PRINT “ENTER THREE NUMBERS”
3. INPUT A, B 3. INPUT A, B, C
4. IF A > B THEN 4. IF A >= B AND B >= C
PRINT “A IS GREATER THAN B” THEN PRINT A
Introduction to Algorithms and Programming Concepts 121
5. IF B >= C AND C >= A action1 is implemented otherwise if it is false action2 is implemented.
THEN PRINT B Now, action1 and action2 may be either plain statements like PRINT X
ELSE
or INPUT X or another “IF p2 THEN action3 ELSE action4” construct,
PRINT C
6. STOP were p2 is a proposition. This means that a second “IF p1 THEN ac-
tion1 ELSE action2” construct can be interposed within the first “IF p1
Explanation To find the largest among the three numbers A, B and C,
THEN action1 ELSE action2” construct. Such an implementation is
A is compared with B to determine whether A is larger than or equal to
known as “nested” if construct.
B. At the same time it is also determined whether B is larger than or
Step 4 implements the nested if construct. First the proposition
equal to C. If both these propositions are true then the number A is the
largest otherwise A is not the largest. Step 4 applies this logic and prints “A > B ”is checked to find whether it is true or false. If true, the propo-
A. sition “A > C ” is verified and if this is found to be true, the value in A
If A is not the largest number as found by the logic in step 4, then is printed otherwise C is printed. But if the first proposition “A > B” is
the logic stated in step 5 is applied. Here again, two propositions are found to be false then the next proposition that is checked is “B > C”.
compared. In one, B is compared with C and in the other C is compared At this point if this proposition is true then the value in B is printed
with A. If both these propositions are true then B is printed as the larg- whereas if it is false C is printed.
est otherwise C is printed as the largest. 7. Take three sides of a triangle as input and check whether the triangle
Steps 1, 2, 3 and 6 needs no mention as it has been used in earlier
can be drawn or not. If possible, classify the triangle as equilateral,
examples.
isosceles, or scalene.
Or
This algorithm uses a variable MAX to store the largest number. Solution Let the length of three sides of the triangle be represented
1. START by A, B, and C. Two alternative algorithms for solving the problem are
2. PRINT “ENTER THREE NUMBERS” given, with explanations after each step, as follows:
3. INPUT A, B, C 1. START
4. MAX ¨ A Step 1 starts the procedure.
5. IF B > MAX THEN MAX ¨ B 2. PRINT “ENTER LENGTH OF THREE SIDES OF A
6. IF C > MAX THEN MAX ¨ C
TRIANGLE”
7. PRINT MAX
Step 2 outputs a message asking for the entry of the lengths
8. STOP
for each side of the triangle.
Explanation This algorithm differs from the previous one. After the 3. INPUT A, B, C
numbers are stored in the variables A, B and C, the value of any one Step 3 reads the values for the lengths that has been entered and
of these is assigned to a variable MAX. This is done in step 4. In step assigns them to A, B and C.
5, the value assigned to MAX is compared with that assigned to B and 4. IF A + B > C AND B + C > A AND A + C > B THEN
if the value in B is larger only then it’s value is assigned to MAX oth- PRINT “TRIANGLE CAN BE DRAWN”
erwise it remains unchanged. In step 6, the proposition “ IF C > MAX ELSE
” is true then the value in C is assigned to MAX. On the other hand, if  PRINT “TRIANGLE CANNOT BE DRAWN”: GOTO 6
the proposition is false then the value in MAX remains unchanged. So
It is well known that in a triangle, the summation of lengths of
at the end of step 6, the value in MAX is the largest among the three
any two sides is always greater than the length of the third side.
numbers. Step 1 is the beginning step while step 8 is the terminating
This is checked in step 4. So for a triangle all the propositions
one for this algorithm.
“A + B > C ”, “ B + C > A ” and “ A + C > B ” must be true. In such a
Or case, with the lengths of the three sides, that has been entered, a trian-
Here, the algorithm uses a nested if construct. gle can be formed. Thus, the message “TRIANGLE CAN BE DRAWN”
1. START is printed and the next step 5 is executed. But if any one of the above
2. PRINT “ENTER THREE NUMBERS” three propositions is not true then the message “TRIANGLE CANNOT
3. INPUT A, B, C BE DRAWN” is printed and so no classification is required. Thus in such
4. IF A > B THEN a case the algorithm is terminated in step 6.
IF A > C THEN 5. IF A = B AND B = C THEN
PRINT A PRINT “EQUILATERAL”
ELSE
ELSE
PRINT C
ELSE IF B > C THEN IF A != B AND B != C AND C !=A THEN
PRINT B PRINT “SCALENE”
ELSE ELSE
PRINT C PRINT “ISOSCELES”
5. STOP After it has been found in step 4 that a triangle can be drawn,
Explanation Here, the nested if construct is used. The construct “IF p1
this step is executed. To find whether the triangle is an “EQUILAT-
THEN action1 ELSE action2” decides if the proposition “ p1” is true then ERAL” triangle the propositions “A = B” and “B = C” are checked.
122 Computer Fundamentals and Programming in C

If both of these are true, then the message “EQUILATERAL” is  3. INPUT N
printed which means that the triangle is an equilateral triangle. On  4. IF N > 0 AND N <= 50 THEN
the other hand if any or both the propositions “A = B” and “B = PRINT “F”
 5. IF N > 50 AND N <= 60 THEN
C” are found to be untrue then the propositions “A != B” and “B
PRINT “C”
!= C” and “C !=A” are checked. If none of the sides are equal to
 6. IF N > 60 AND N <= 70 THEN
each other then all these propositions are found to be true and so PRINT “B”
the message “SCALENE” will be printed. But if these propositions  7. IF N > 70 AND N <= 80 THEN
“A != B” and “B != C” and “C !=A” are false then the triangle is PRINT “A”
obviously an isosceles triangle and hence the message “ISOSCELES”  8. IF N > 80 AND N <= 90 THEN
is printed. PRINT “E”
 9. IF N > 90 AND N <= 100 THEN
6. STOP
PRINT “O”
The procedure terminates here.
10. STOP
Or
This algorithm differs from the previous one and applies an alternate 9. Construct an algorithm for incrementing the value of a variable that
way to test whether a triangle can be drawn with the given sides and starts with an initial value of 1 and stops when the value becomes 5.
also identify its type. Solution This problem illustrates the use of iteration or loop construct.
1. START Let the variable be represented by C. The algorithm for the said prob-
2. PRINT “ENTER THE LENGTH OF 3 SIDES OF A TRIANGLE” lem is given as follows.
3. INPUT A, B, C
1. START
4. IF A + B > C AND B + C > A AND C + A > B
2. C ¨ 1
THEN
3. WHILE C <= 5
PRINT “TRIANGLE CAN BE DRAWN”
4. BEGIN While loop construct
ELSE
5. PRINT C for looping till C is
PRINT “TRIANGLE CANNOT BE DRAWN”
6. C ¨ C + 1 greater than 5
: GO TO 8
7. END
5. IF A = B AND B = C THEN
PRINT “EQUILATERAL TRIANGLE” 8. STOP
: GO TO 8
6. IF A = B OR B = C OR C = A THEN 10. Write an algorithm for the addition of N given numbers.
PRINT “ISOSCELES TRIANGLE”
: GO TO 8 Solution Let the sum of N given numbers be represented by S. Each
7. PRINT “SCALENE TRIANGLE” time a number is given as input, let it is assigned to the variable A. The
8. STOP algorithm using the loop construct ‘if … then goto …’ is used as follows:
Having followed the explanations given with each of the earlier examples, 1. START
2. PRINT “HOW MANY NUMBERS?”
the reader has already understood how the stepwise method represents
3. INPUT N
the algorithm with suitable statements. 4. S ¨ 0
In a similar way the following example exhibits the stepwise rep- 5. C ¨ 1
resentation of algorithms for various problems using the stepwise 6. PRINT “ENTER NUMBER”
method. 7. INPUT A
8. S ¨ S + A
8. In an academic institution, grades have to be printed for students who
9. C ¨ C + 1
appeared in the final exam. The criteria for allocating the grades against 10. IF C <= N THEN GOTO 6
the percentage of total marks obtained are as follows. 11. PRINT S
12. STOP
Marks Grade Marks Grade
11. Develop the algorithm for finding the sum of the series 1 + 2 + 3 + 4 +
91–100 O 61–70 B … up to N terms.
81–90 E 51–60 C
Solution Let the sum of the series be represented by S and the num-
71–80 A <= 50 F ber of terms by N. The algorithm for computing the sum is given as
The percentage of total marks obtained by each student in the final follows.
exam is to be given as input to get a printout of the grade the student is  
1. START
awarded.  2. PRINT “HOW MANY TERMS?”
 3. INPUT N
Solution The percentage of marks obtained by a student is repre-

 4. S ¨ 0
sented by N. The algorithm for the given problem is as follows.  5. C ¨ 1
  1. START  6. S ¨ S + C
 2. PRINT  7. C ¨ C + 1
“ENTER THE OBTAINED PERCENTAGE MARKS”  8. IF C <= N THEN GOTO 6
Introduction to Algorithms and Programming Concepts 123
 9. PRINT S  
1. START
10. STOP  2. PRINT “ENTER THE NUMBER OF TERMS”
12. Write an algorithm for determining the sum of the series 2 + 4 + 8 + …   3. INPUT N
 4. C ¨ 1
up to N.
 5. T ¨ 1
Solution Let the sum of the series be represented by S and the num-  6. T1 ¨ 0
ber of terms in the series by N. The algorithm for this problem is given  7. T2 ¨ 1
as follows.  8. PRINT T

1. START  9. T ¨ T1 + T2
 2. PRINT “ENTER THE VALUE OF N” 10. C ¨ C + 1
 3. INPUT N 11. T1 ¨ T2
 4. S ¨ 0 12. T2 ¨ T
 5. C ¨ 2 13. IF C <= N THEN GOTO 8
 6. S ¨ S + C 14. STOP
 7. C ¨ C * 2 2 3 4
 8. IF C <= N THEN GOTO STEP 6 16. Write an algorithm to find the sum of the series 1 + x + x + x + x + …
 9. PRINT S up to N terms.
10. STOP
Solution
13. Write an algorithm to find out whether a given number is a prime num-  1. START
ber or not.  2. PRINT “HOW MANY TERMS”
Solution The algorithm for checking whether a given number is a  3. INPUT N
prime number or not is as follows.  4. PRINT “ENTER VALUE OF X”
 5. INPUT X
1. START
2. PRINT “ENTER THE NUMBER”  6. T ¨ 1
3. INPUT N  7. C ¨ 1
4. IF N = 2 THEN  8. S ¨ 0
PRINT “CO-PRIME” GOTO STEP 12  9. S ¨ S + T
5. D ¨ 2 10. C ¨ C + 1
6. Q ¨ N/D (Integer division) 11. T ¨ T * X
7. R ¨ N – Q*D 12. IF C <= N THEN GOTO 9
 8. IF R = 0 THEN GOTO STEP 11 13. PRINT S
 9. D ¨ D + 1 14. STOP
10. IF D <= N/2 THEN GOTO STEP 6
17. Write the algorithm for computing the sum of digits in a number.
11. IF R = 0 THEN
PRINT “NOT PRIME” Solution
ELSE  
1. START
PRINT “PRIME”  2. PRINT “ENTER THE NUMBER”
12. STOP  3. INPUT N
14. Write an algorithm for calculating the factorial of a given number N.  4. S ¨ 0
 5. Q ¨ N/10 (Integer division)
Solution The algorithm for finding the factorial of number N is as fol-  6. R ¨ N – Q * 10
lows.  7. S ¨ S + R
 1. START  8. N ¨ Q
 2. PRINT “ENTER THE NUMBER”  9. IF N > 0 THEN GOTO 5
 3. INPUT N 10. PRINT S
 4. F ¨ 1 11. STOP
 5. C ¨ 1
18. Write an algorithm to find the largest number among a list of numbers.
 6. WHILE C <= N
  7. BEGIN
While loop construct
Solution The largest number can be found using the following algo-
8. F ¨ F * C for looping till C is rithm.
 9. C ¨ C + 1 greater than N  
1. START
   
10. END  2. PRINT “ENTER,
11. PRINT F TOTAL COUNT OF NUMBERS IN LIST”
12. STOP  3. INPUT N
 4. C ¨ 0
15. Write an algorithm to print the Fibonacci series up to N terms.  5. PRINT “ENTER FIRST NUMBER”
Solution The Fibonacci series consisting of the following terms 1, 1, 2,  6. INPUT A
3, 5, 8, 13, … is generated using the following algorithm.  7. C ¨ C + 1
124 Computer Fundamentals and Programming in C

 8. MAX ¨ A Although there is no standard for pseudo-code, it is gener-


 9. PRINT “ENTER NEXT NUMBER” ally quite easy to read and use. For instance, a sample pseu-
10. INPUT B do-code is written as follows:
11. C ¨ C + 1 dowhile kettle_empty
12. IF B > MAX THEN Add_Water_To_Kettle
MAX ¨ B
end dowhile
13. IF C <= N THEN GOTO STEP 9
As can be seen, it is a precise statement of a while loop.
14. PRINT MAX
15. STOP Flowcharts
19. Write an algorithm to check whether a given number is an Armstrong A flowchart depicts appropriate steps to be followed in order
number or not. An Armstrong number is one in which the sum of the to arrive at the solution to a problem. It is a program design
cube of each of the digits equals that number. tool which is used before writing the actual program. Flow-
3 3 charts are generally developed in the early stages of formu-
Solution  If a number 153 is considered, the required sum is (1 + 5 +
3 lating solutions to problems.
3 ), i.e., 153. This shows that the number is an Armstrong number. The
A flowchart comprises a set of standard shaped boxes that
algorithm to check whether 153 is an Armstrong number or not, is given
are interconnected by flow lines. Flow lines have arrows to
as follows.
 1. START
indicate the direction of the flow of control between the box-
 2. PRINT “ENTER THE NUMBER” es. The activity to be performed is written within the boxes
 3. INPUT N in English. In addition, there are connector symbols that are
 4. M ¨ N used to indicate that the flow of control continues elsewhere,
 5. S ¨ 0 for example, the next page.
 6. Q ¨ N/10 (Integer division) Flowcharts facilitate communication between program-
 7. R ¨ N – Q * 10 mers users and business persons. These flowcharts play a vital
 8. S ¨ S + R * R * R role in the programming of a problem and are quite helpful in
 9. N ¨ Q understanding the logic of complicated and lengthy problems.
10. IF N > 0 THEN GOTO STEP 6
Once the flowchart is drawn, it becomes easy to write the
11. IF S = M THEN
program in any high-level language. Often flowcharts
PRINT “THE NUMBER IS ARMSTRONG”
are helpful in explaining the program to others. Hence, a
ELSE PRINT “THE NUMBER IS NOT ARMSTRONG”
12. STOP
flowchart is a must for better documentation of a complex
2
program.
20. Write an algorithm for computing the sum of the series 1 + x + x /2!
3 4
+ x /3! + x /4! + … up to N terms. Standards for flowcharts  The following standards should
be adhered to while drawing flow charts.
Solution
 1. START ∑ Flowcharts must be drawn on white, unlined 8½¢¢ × 11¢¢
 2. PRINT “ENTER NUMBER OF TERMS” paper, on one side only.
 3. INPUT N ∑ Flowcharts start on the top of the page and flow down and
 4. PRINT “ENTER A NUMBER”
to the right.
 5. INPUT X
 6. T ¨ 1
∑ Only standard flowcharting symbols should be used.
 7. S ¨ 0 ∑ A template to draw the final version of flowchart should be
 8. C ¨ 1 used.
 9. S ¨ S + T ∑ The contents of each symbol should be printed legibly.
10. T ¨ T * X/C
∑ English should be used in flowcharts, not programming
11. C ¨ C + 1
language.
12. IF C <= N THEN GO TO STEP 9
13. PRINT S ∑ The flowchart for each subroutine, if any, must appear on
14. STOP a separate page. Each subroutine begins with a terminal
symbol with the subroutine name and a terminal symbol
Pseudo-code labeled return at the end.
Like step-form, Pseudo-code is a written statement of an al- ∑ Draw arrows between symbols with a straight edge and use
gorithm using a restricted and well-defined vocabulary. It is arrowheads to indicate the direction of the logic flow.
similar to a 3GL, and for many programmers and program
Guidelines for drawing a flowchart  Flowcharts are usu-
designers it is the preferred way to state algorithms and pro- ally drawn using standard symbols; however, some special
gram specifications. symbols can also be developed when required. Some stan-
Introduction to Algorithms and Programming Concepts 125
dard symbols frequently required for flowcharting many ∑ Only one flow line is used in conjunction with a terminal
computer programs are shown in Fig.7.2. symbol.

START STOP
Start or end of the program or A magnetic tape
flowchart

∑ The writing within standard symbols should be brief. If


A magnetic disk necessary, the annotation symbol can be used to describe
Computational steps or processing
data or computational steps more clearly.
function of a program

Connects remote portions This is a top secret data


of the flowchart not on the
Input entry or output display same page
operation
∑ If the flowchart becomes complex, connector symbols
should be used to reduce the number of flow lines. The in-
Flow lines
tersection of flow lines should be avoided to make the flow-
A decision-making and branching chart a more effective and better way of communication.
operation that has two alternatives

∑ The validity of the flowchart should be tested by passing


Add comments or furnish simple test data through it.
clarifications
Connects remote parts of the ∑ A sequence of steps or processes that are executed in a
flowchart on the same page particular order is shown using process symbols connect-
Display
ed with flow lines. One flow line enters the first process
while one flow line emerges from the last process in the
Fig. 7.2  Flowchart symbols sequence.
The following are some guidelines in flowcharting.
∑ In drawing a proper flowchart, all necessary requirements First process in sequence
should be listed out in a logical order.
∑ There should be a logical start and stop to the flowchart.
∑ The flowchart should be clear, neat, and easy to follow.
There should be no ambiguity in understanding the flow-
chart. Last process in sequence
∑ The usual direction of the flow of a procedure or system is
from left to right or top to bottom.
∑ Only one flow line should emerge from a process symbol. ∑ Selection of a process or step is depicted by the decision
making and process symbols. Only one input indicated by
one incoming flow line and one or more output flowing
out of this structure exists. The decision symbol and the
or process symbols are connected by flow lines.

true false
∑ Only one flow line should enter a decision symbol, but two
or three flow lines, one for each possible answer, can leave
the decision symbol.
process1 process2

false

true
126 Computer Fundamentals and Programming in C

∑ Iteration or looping is depicted by a combination of pro- note


cess and decision symbols placed in proper order. Here
∑ A flowchart comprises a set of standard shaped boxes that
flow lines are used to connect the symbols and depict input are interconnected by flow lines to represent an algorithm.
and output to this structure. ∑ There should be a logical start and stop to the flowchart.
∑ The usual direction of the flow of a procedure or system
is from left to right or top to bottom.
START
∑ The intersection of flow lines should be avoided.
∑ Flowcharts facilitate communication between program-
mers and users.

Process 1 Flowcharting examples  A few examples on flowcharting


are presented for a proper understanding of the technique.
This will help the student in the program development pro-
cess at a later stage.
Process Y
Process X
Examples

21. Draw a flowchart to find the sum of the first 50 natural numbers.
False
Decision
Solution

START

True
SUM = 0

Advantages of using flowcharts N=0

Communication  Flowcharts are a better way of communi-


N = N+1
cating the logic of a system to all concerned.
Effective analysis  With the help of flowcharts, problems SUM = SUM+N
can be analysed more effectively.
Proper documentation  Program flowcharts serve as a NO IS
good program documentation needed for various purposes. N = 50?

Efficient coding  Flowcharts act as a guide or blueprint dur- YES


ing the systems analysis and program development phase. PRINT SUM

Proper debugging  Flowcharts help in the debugging pro- STOP


cess.
Efficient program maintenance  The maintenance of an 22. Draw a flowchart to find the largest of three numbers A, B,
operating program becomes easy with the help of a flowchart. and C.
Limitations of using flowcharts Solution

Complex logic  Sometimes, the program logic is quite com- START

plicated. In such a case, a flowchart becomes complex and


READ A,B,C
clumsy.
Alterations and modifications  If alterations are required, IS B>C?
NO
IS A>B?
YES
IS A>C?
the flowchart may need to be redrawn completely.
YES
YES

NO NO

Reproduction  Since the flowchart symbols cannot be PRINT B PRINT C PRINT A


typed in, the reproduction of a flowchart becomes a problem.
Loss of objective  The essentials of what has to be done can
easily be lost in the technical details of how it is to be done. STOP
Introduction to Algorithms and Programming Concepts 127
23. Draw a flowchart for computing factorial N (N!) where Solution
N! = 1 × 2 × 3 × … × N.
Solution START

START INPUT SALARY


OF AN EMPLOYEE

READ N
IS
SALARY>=5000
NO YES
T=1
F=1 BONUS =
BONUS = 250
0.05*SALARY

F=F*T
PRINT BONUS

NO IS
T=T+1
T>N? STOP

YES
Step 1: START Step 5: Calculate Bonus = 250
PRINT F Step 2: Read salary of Step 6: Print Bonus
an employee
Step 3: IF salary is greater than Step 7: STOP
or equal to 5,000 THEN
END Step 4 ELSE Step 5
Step 4: Calculate
Bonus = 0.05 * Salary
Go to Step 6
24. Draw a flowchart for calculating the simple interest using the formula
SI = (P * T * R)/100, where P denotes the principal amount, T time, and
R rate of interest. Also, show the algorithm in step-form. 26. Prepare a flowchart to read the marks of a student and classify them
into different grades. If the marks secured are greater than or equal to
Solution
90, the student is awarded Grade A; if they are greater than or equal
to 80 but less than 90, Grade B is awarded; if they are greater than or
START Step 1: START equal to 65 but less than 80, Grade C is awarded; otherwise Grade D is
awarded.
Solution
INPUT
P, T, R Step 2: Read P, T, R START

READ MARKS

CALCULATE
YES ARE NO
I = P*T*R Step 3: Calculate I=P*R*T/100
MARKS≥90
100

GRADE = A YES ARE NO


MARKS≥80

PRINT VALUE FOR I Step 4: PRINT I GRADE = B YES ARE NO


MARKS>65

GRADE = C GRADE = D
STOP Step 5: STOP

25. The XYZ Construction Company plans to give a 5% year-end bonus to


PRINT GRADE
each of its employees earning Rs 5,000 or more per year, and a fixed
bonus of Rs 250 to all other employees. Draw a flowchart and write the
STOP
step-form algorithm for printing the bonus of any employee.
128 Computer Fundamentals and Programming in C

27. Draw a flowchart to find the roots of a quadratic equation. 7.1.6 Strategy for Designing Algorithms
Solution Now that the meaning of algorithm and data has been un-
derstood, strategies can be devised for designing algorithms.
START The following is a useful strategy.
Investigation step
READ A,B,C
1. Identify the outputs needed.
D=B*B–4*A*C This includes the form in which the outputs have to be
presented. At the same time, it has to be determined at
what intervals and with what precision the output data
NO IS YES needs to be given to the user.
D>0
2. Identify the input variables available.
NO YES
IS D = 0
REAL1=(–B+SQRT(D))/(2*A)
REAL2=(–B–SQRT(D))/(2*A)
This activity considers the specific inputs available
for this problem, the form in which the input variables
REAL1=–B/2*A would be available, the availability of inputs at different
REAL2=–B/2*A
intervals, the ways in which the input would be fed to
the transforming process.
PRINT
“COMPLEX
PRINT A,B,C
REAL1,
PRINT A,B,C
REAL1,
3. Identify the major decisions and conditions.
ROOTS” REAL2 REAL2 This activity looks into the conditions imposed by the
need identified and the limitations of the environment in
which the algorithm has to be implemented.
STOP 4. Identify the processes required to transform inputs into
required outputs.
28. Draw a flowchart for printing the sum of even terms contained within the This activity identifies the various types of procedures
numbers 0 to 20. needed to manipulate the inputs, within the bounding
Solution conditions and the limitations mentioned in step 3, to
produce the needed outputs.
START 5. Identify the environment available.
This activity determines the kind of users and the type of
SUM=0 computing machines and software available for imple-
menting the solution through the processes considered
COUNT=1 in steps.
Top–down development step
NO IS COUNT YES 1. Devise the overall problem solution by identifying the
AN EVEN major components of the system.
NUMBER?
SUM=SUM+COUNT The goal is to divide the problem solution into manage-
able small pieces that can be solved separately.
2. Verify the feasibility of breaking up the overall problem
COUNT=COUNT+1 solution.
The basic idea here is to check that though each small
IS NO piece of solution procedure are independent, they are
COUNT>20
not entirely independent of each other, as they together
YES form the whole solution to the problem. In fact, the dif-
B ferent pieces of solution procedures have to cooperate
and communicate in order to solve the larger problem.
PRINT SUM Stepwise refinement
1. Work out each and every detail for each small piece of
STOP manageable solution procedure.
Introduction to Algorithms and Programming Concepts 129
Every input and output dealt with and the transformation 7.1.7  Tracing an Algorithm to Depict Logic
algorithms implemented in each small piece of solution
procedure, which is also known as process, is detailed. An algorithm is a collection of some procedural steps that
Even the interfacing details between each small proce- have some precedence relation between them. Certain pro-
dure are worked out. cedures may have to be performed before some others are
2. Decompose any solution procedure into further small- performed. Decision procedures may also be involved to
er pieces and iterate until the desired level of detail is choose whether some procedures arranged one after other are
achieved. to be executed in the given order or skipped or implemented
Every small piece of solution procedure detailed in step repetitively on fulfillment of conditions arising out of some
1 is checked once again. If necessary any of these may preceding manipulations. Hence, an algorithm is a collec-
be further broken up into still smaller pieces of solution tion of procedures that results in providing a solution to a
procedure till it can no more be divided into meaningful problem. Tracing an algorithm primarily involves tracking
procedure. the outcome of every procedure in the order they are placed.
3. Group processes together which have some commonality. Tracking in turn means verifying every procedure one by one
Some small processes may have to interface with a com- to determine and confirm the corresponding result that is to
mon upper level process. Such processes may be grouped be obtained. This in turn can be traced to offer an overall
together if required. output from the implementation of the algorithm as a whole.
4. Group variables together which have some appropriate Consider Example 26 given in this chapter for the purpose
commonality. of tracing the algorithm to correctly depict the logic of the
Certain variables of same type may be dealt as elements solution. Here at the start, the “mark obtained by a student
of a group. in a subject” is accepted as input to the algorithm. This pro-
5. Test each small procedure for its detail and correctness cedure is determined to be essential and alright. In the next
and its interfacing with the other small procedures. step, the marks entered is compared with 90. As given, if the
Walk through each of the small procedures to determine mark is greater than 90, then the mark obtained is categorized
whether it satisfies the primary requirements and would as Grade A and printed, otherwise it is be further compared.
deliver the appropriate outputs. Also, suitable tests have Well, this part of the algorithm matches with the requirement
to be carried out to verify the interfacing between vari- and therefore this part of the logic is correct.
ous procedures. Hence, the top-down approach starts For the case of further comparison, the mark is again com-
with a big and hazy goal. It breaks the big goal into pared with 80 and if it is greater, then Grade B is printed. Oth-
smaller components. These components are themselves erwise, if the mark is less than 80, then further comparison
broken down into smaller parts. This strategy continues
is carried out. This part of the logic satisfies the requirement
until the designer reaches the stage where he or she has
of the problem. In the next step of comparison, the mark is
concrete steps that can actually be carried out.
compared with 65. If the mark is lesser than 65, Grade C is
It has to be noted that the top-down approach does not printed, otherwise Grade D is printed. Here also, the flow-
actually take into account any existing equipment,
chart depicts that the correct logic has been implemented.
people, or processes. It begins with a “clean slate” and
The above method shows how the logic of an algorithm,
obtains the optimal solution. The top-down approach is
planned and represented by a tool like the flowchart, can be
most appropriate for large and complex projects where
verified for its correctness. This technique, also referred to as
there is no existing equipment to worry about. How-
ever, it may be costly because, sometimes, the existing deskcheck or dry run, can also be used for algorithms repre-
equipments may not fit into the new plan and it has to sented by tools other than the flowchart.
be replaced. However, if the existing equipments can be 7.1.8  Specification for Converting Algorithms
made to fit into the new plan with very less effort, it
into Programs
would be beneficial to use it and save cost.
By now, the method of formulating an algorithm has been
note understood. Once the algorithm, for solution of a problem, is
∑ Investigation phase determines the requirements for the
formed and represented using any of the tools like step-form
problem solution. or flowchart or pseudo code, etc., it has to be transformed
∑ The top-down development phase plans out the way the into some programming language code. This means that a
solution has to be done by breaking it into smaller mod- program, in a programming language, has to be written to
ules and establishing a logical connection among them. represent the algorithm that provides a solution to a problem.
∑ The step-wise refinement further decomposes the modules, Hence, the general procedure to convert an algorithm into
defines the procedure in it and verifies the correctness of it. a program is given as follows:
130 Computer Fundamentals and Programming in C

Code the algorithm into a program—Understand the syntax Pseudocode C language code
and control structures used in the language that has been se-
LOOP { while(1) {
lected and write the equivalent program instructions based
EXIT LOOP break;
upon the algorithm that was created. Each statement in an al-
gorithm may require one or more lines of programming code. IF (conditions) { if (conditions) {
ELSE IF (conditions) { else if (conditions) {
Desk-check the program—Check the program code by em-
ploying the desk-check method and make sure that the sam- ELSE { else
ple data selected produces the expected output. INPUT a scanf(“%d”,&a);

Evaluate and modify, if necessary, the program—Based on OUTPUT “Value of a:” a printf(“Value of a: %d”,a);
the outcome of desk-checking the program, make program + - * / % + - * / %
code changes, if necessary, or make changes to the original = ==
algorithm, if need be. <— =
Do not reinvent the wheel—If the design code already exists, != !=
modify it, do not remake it. AND &&
OR ||
Note
NOT !
∑ An algorithm can be traced by verifying every procedure
one by one to determine and confirm the corresponding
result that is to be obtained. To demonstrate the procedure of conversion from an algo-
∑ The general procedure to convert an algorithm into a pro-
rithm to a program in C, an example is given below.
gram is to code the algorithm using a suitable program-
ming language, check the program code by employing Problem statement: Write the algorithm and the correspond-
the desk-check method and finally evaluate and modify ing program in C for adding two integer numbers and print-
the program, if needed. ing the result.
Solution
Because the reader has not yet been introduced to the ba- Algorithm
sics of the C language, the reader has to accept the use of 1. START
certain instructions like #include <stdio.h>, int main(), 2. PRINT “ENTER TWO NUMBERS”
printf(), scanf(), and return without much explanation at 3. INPUT A, B
4. R = A + B
this stage in the example program being demonstrated below. 5. PRINT “RESULT =”
However, on a very preliminary level, the general form 6. PRINT R
of a C program and the use of some of the necessary C 7. STOP.
language instructions are explained briefly as follows: Program in C
1. All C programs start with: int main( )
#include <stdio.h> {
int main ()   int A, B;
 {   printf(“\n ENTER TWO NUMBERS:”);
2. In C, all variables must be declared before using them. So  scanf(“%d%d”,&A,&B);
  R = A + B;
the line next to the two instruction lines and{, given in step 1   printf(“\n RESULT = ”);
above should be any variable declarations that is needed.  printf(“%d”,R);
For example, if a variable called “a” is supposed to store   return 0;
an integer, then it is declared as follows: }
int a;
3. Here, scanf() is used for inputting data to the C program 7.2 Structured Programming Concept
and printf() is used to output data on the monitor screen.
In 1968, computer scientist Edsger Dijkstra of Netherlands
4. The C program has to be terminated with a statement giv-
published a letter to the editor in the journal of the Associa-
en below:
tion of Computing Machinery with the title ‘GoTo statement
return 0;
 } considered harmful’. goto is a command available in most
Here is an example showing how to convert some programming languages to transfer a control to a particular
pseudocode statements into C language statements: statement. For three decades, Dijkstra had been crusading for
Introduction to Algorithms and Programming Concepts 131
a better way of programming—a systematic way to organize There are two essential ideas in top-down analysis:
programs—called structured programming. ∑ subdivision of a problem
Structured programming has been called a revolution in
∑ hierarchy of tasks
programming and is considered as one of the most impor-
tant advancements in software in the past two decades. Both Subdivision of a problem means breaking a big problem
academic and industrial professionals are inclined towards into two or more smaller problems. Therefore, to solve the
big problem, first these smaller problems have to be solved.
the philosophy and techniques of structured programming.
Top-down analysis does not simply divide a problem into
Today, it can be safely said that virtually all software devel-
two or more smaller problems. It goes further than that. Each
opers acknowledge the merits of the structured programming
of these smaller problems is further subdivided. This process
approach and use it in software development.
continues downwards, creating a hierarchy of tasks, from one
There is no standard definition of structured programs
level to the next, until no further break up is possible.
available but it is often thought to be programming without The four basic steps to top-down analysis are as follows:
the use of a goto statement. Indeed, structured programming Step 1: Define the complete scope of the problem to deter-
does discourage the frequent use of goto but there is more to mine the basic requirement for its solution. Three factors
it than that. must be considered in the definition of a programming prob-
Structured programming is: lem.
∑ concerned with improving the programming process Input  What data is required to be processed by the program?
through better organization of programs and better pro-
Process  What must be done with the input data? What type
gramming notation to facilitate correct and clear descrip-
of processing is required?
tion of data and control structure.
∑ concerned with improved programming languages and or- Output  What information should the program produce? In
ganized programming techniques which should be under- what form should it be presented?
standable and therefore, more easily modifiable and suit- Step 2: Based on the definition of the problem, divide the
able for documentation. problem into two or more separate parts.
∑ more economical to run because good organization and no- Step 3: Carefully define the scope of each of these separate
tation make it easier for an optimizing compiler to under- tasks and subdivide them further, if necessary, into two or
stand the program logic. more smaller tasks.
∑ more correct and therefore more easily debugged, because Step 4: Repeat step 3. Every step at the lowest level de-
general correctness theorems dealing with structures can scribes a simple task, which cannot be broken further.
be applied to prove the correctness of programs. 7.2.2 Modular Programming
Structured programming can be defined as a Modular programming is a program that is divided into logi-
∑ top–down analysis for program solving cally independent smaller sections, which can be written sepa-
∑ modularization for program structure and organization rately. These sections, being separate and independent units,
∑ structured code for individual modules are called modules.
∑ A module consists of a series of program instructions or
7.2.1 Top–Down Analysis statements in some programming language.
A program is a collection of instructions in a particular ∑ A module is clearly terminated by some special markers
language that is prepared to solve a specific problem. For required by the syntax of the language. For example, a BA-
larger programs, developing a solution can be very com- SIC language subroutine is terminated by the return state-
plicated. From where should it start? Where should it ment.
terminate? Top-down analysis is a method of problem ∑ A module as a whole has a unique name.
solving and problem analysis. The essential idea is to sub-
∑ A module has only one entry point to which control is trans-
divide a large problem into several smaller tasks or parts for
ferred from the outside and only one exit point from which
ease of analysis.
control is returned to the calling module.
Top-down analysis, therefore, simplifies or reduces the
complexity of the process of problem solving. It is not lim- The following are some of the advantages of modular pro-
ited by the type of program. Top-down analysis is a general gramming.
method for attending to any problem. It provides a strategy ∑ Complex programs may be divided into simpler and more
that has to be followed for solving all problems. manageable elements.
132 Computer Fundamentals and Programming in C

∑ Simultaneous coding of different modules by several pro- WEND


PRINT G
grammers is possible.
ELSE
∑ A library of modules may be created, and these modules PRINT “INVALID INPUT”
may be used in other programs as and when needed. END
∑ The location of program errors may be traced to a particu- Now if there is no normal break of control flow, gotos
lar module; thus, debugging and maintenance may be sim- are inevitable in unstructured languages but they can be and
plified. should be always avoided while using structured programs
except in unavoidable situations.
7.2.3  Structured Code
After the top-down analysis and design of the modular struc- 7.2.4 The Process of Programming
ture, the third and final phase of structured programming in- The job of a programmer is not just writing program instruc-
volves the use of structured code. Structured programming is tions. The programmer does several other additional jobs to
a method of coding, i.e., writing a program that produces a create a working program. There are some logical and se-
well-organized module. quential job steps which the programmer has to follow to
A high-level language supports several control statements, make the program operational.
also called structured control statements or structured code, These are as follows:
to produce a well-organized structured module. These control
statements represent conditional and repetitive type of execu- 1. Understand the problem to be solved
tions. Each programming language has different syntax for 2. Think and design the solution logic
these statements. 3. Write the program in the chosen programming lan-
In C, the if and case statements are examples of condi- guage
tional execution whereas for, while, and do...while state- 4. Translate the program to machine code
ments represent repetitive execution. In BASIC, for-next
5. Test the program with sample data
and while-wend are examples of repetitive execution. Let us
consider the goto statement of BASIC, which is a simple but 6. Put the program into operation
not a structured control statement. The goto statement can The first job of the programmer is to understand the prob-
break the normal flow of the program and transfer control to lem. To do that the requirements of the problem should be
any arbitrary point in a program. A module that does not have clearly defined. And for this, the programmer may have to in-
a normal flow control is unorganized and unreadable. teract with the user to know the needs of the user. Thus this
The following example is a demonstration of a program us- phase of the job determines the ‘what to’ of the task.
ing several goto statements. Note that at line numbers 20, 60, The next job is to develop the logic of solving the prob-
and 80, the normal flow control is broken. For example, from lem. Different solution logics are designed and the order in
line number 60, control goes back to line 40 instead of line 70 which these are to be used in the program are defined. Hence,
in case value of (R – G) is less than 0.001. this phase of the job specifies the ‘how to’ of the task.
10 INPUT X Once the logics are developed, the third phase of the job is
20 IF X < 0 THEN GOTO 90 to write the program using a chosen programming language.
30 G = X/2
The rules of the programming language have to be observed
40 R = X/G
50 G = (R + G)/2 while writing the program instructions.
60 IF ABS(R - G) < 0.001 THEN GOTO 40 The computer recognizes and works with 1’s and 0’s.
70 PRINT G Hence program instructions have to be converted to 1’s and
80 GOTO 100
0’s for the computer to execute it. Thus, after the program is
90 PRINT “INVALID INPUT”
100 END written, it is translated to the machine code, which is in 1’s
and 0’s with the help of a translating program.
The structured version of this program using while-wend
Now, the program is tested with dummy data. Errors in
statement is given below.
the programming logic are detected during this phase and are
INPUT X removed by making necessary changes in either the logic or
IF X > 0
the program instructions.
THEN
G = X/2 The last phase is to make the program operational. This
R = X/G means, the program is put to actual use. Errors occurring in
WHILE ABS (R – G) < 0.001 this phase are rectified to finally make the program work to
R = X/G
the user’s satisfaction.
G = (R + G)/2
Introduction to Algorithms and Programming Concepts 133
note
∑ Structured programming involves top–down analysis for program solving, modularization of program structure and organizing struc-
tured code for individual module.
∑ Top-down analysis breaks the whole problem into smaller logical tasks and defines the hierarchical link between the tasks.
∑ Modularization of program structure means making the small logical tasks into independent program modules that carries out
the desired tasks.
∑ Structured coding is structured programming which consists of writing a program that produces a well-organized module.

Summary
An algorithm is a statement about how a problem will be solved and almost Generally the design strategy consists of three stages. The first stage
every algorithm exhibits the same features. There are many ways of stating is investigation activity followed by the top-down development approach
algorithms; three of them have been mentioned here. These are step-form, stage and eventually a stepwise refinement process. Once the design
pseudo code, and flowchart method. Of these flowchart is a pictorial way of strategy is decided the algorithm designed is traced to determine whether
representing the algorithm. Here, the START and STOP are represented it represents the logic. Eventually, the designed and checked, algorithm is
by an ellipse-like figure, , decision construct by the rhombus-like transformed into a program.
figure, , the processes by rectangles, and input/out- A program is a sequence of instructions and the process of writing a
put by parallelograms, . Lines and arrows connect these blocks. program is called programming. Nowadays, structured programming tech-
Every useful algorithm uses data, which might vary during the course of nique is used to develop a program in a high-level programming language.
the algorithm. To design algorithms, it is a good idea to develop and use
a design strategy.

Key Terms

Algorithm  An algorithm specifies a procedure for solving a problem in a the computer responds directly
finite number of steps. Portability of language  A programming language that is not machine
Correctness  Correctness means how easily its logic can be argued to dependent and can be used in any computer.
meet the algorithm’s primary goal. Program  A set of logically related instructions arranged in a sequence
Data  It is a symbolic representation of value. that directs the computer in solving a problem.
Debug  It means to search and remove errors in a program. Programming language  A language composed of a set of instructions
High-level programming language  A language similar to human lan- understandable by the programmer.
guages that makes it easy for a programmer to write programs and identify Programming  It is a process of writing a program.
and correct errors in them. Termination  It denotes closure of a procedure.
Investigation step  It is a step to determine the input, output and pro- Top-down analysis  It means breaking up a problem solution into small-
cessing requirements of a problem. er modules and defininig their interconnections to provide the total solution
Low-level programming language  Closer to the native language of the to a problem.
computer, which is 1’s and 0’s. Variable  It is a container or storage location for storing a value that may
Machine language  Machine language is a language that provides in- or may not vary during the execution of the program.
structions in the form of binary numbers consisting of 1’s and 0’s to which

Frequently asked questions

1.  What is a programming language? understand only machine language, which is a low-level language in which
A programming language is an artificial formalism in which algorithms can data is represented by binary digits.
be expressed. More formally, a computer program is a sequence of instruc- 2.  What is a token?
tions that is used to operate a computer to produce a specific result.
A token is any word or symbol that has meaning in the language, such as
  A programming language is the communication bridge between a pro-
a keyword (reserved word) such as if or while. The tokens are parsed or
grammer and computer. A programming language allows a programmer to
grouped according to the rules of the language.
create sets of executable instructions called programs that the computer
can understand. This communication bridge is needed because computers 3.  What is a variable?
134 Computer Fundamentals and Programming in C

A variable is a name given to the location of computer memory that holds clear description of data and control structure.
the relevant data. Each variable has a data type, which might be number,   Structured programming also saves time as without modularity, the code
character, string, a collection of data elements (such as an array), a data that is used multiple times needs to be written every time it is used. On the
record, or some special type defined by the programmer. other hand, modular programs need one to call a subroutine (or function)
with that code to get the same result in a structured program.
4.  What is Spaghetti code?
  Structured programming encourages stepwise refinement, a program
Non-modular code is normally referred to as spaghetti code. It is named so
design process described by Niklaus Wirth. This is a top-down approach
because it produces a disorganized computer program using many GOTO
in which the stages of processing are first described in high-level terms,
statements.
and then gradually worked out in their details, much like the writing of an
5.  What is structured programming? outline for a book.
Structured programming is a style of programming designed to make pro-   The disadvantages of structured programming include the following:
grams more comprehensible and programming errors less frequent. This   Firstly, error control may be harder to manage. Managing modifications
technique of programming enforces a logical structure on the program be- may also be difficult.
ing written to make it more efficient and easier to understand and modify. It
  Secondly, debugging efforts can be hindered because the problem code
usually includes the following characteristics:
will look right and even perform correctly in one part of the program but not
Block structure  The statements in the program must be organized into in another.
functional groups. It emphasizes clear logic.
7.  What is a pseudocode?
Avoidance of jumps  A lot of GOTO statements makes the programs
more error-prone. Structured programming uses less of these statements. Pseudocode is an informal description of a sequence of steps for solving
Therefore it is also known as ‘GOTO less programming’. a problem. It is an outline of a computer program, written in a mixture of
a programming language and English. Writing pseudocodes is one of the
Modularity  It is a common idea that structuring the program makes it
best ways to plan a computer program.
easier for us to understand and therefore easier for teams of developers to
work simultaneously on the same program.   The advantage of having pseudocodes is that it allows the program-
mer to concentrate on how the program works while ignoring the details
6.  What are the advantages and disadvantages of structured pro- of the language. By reducing the number of things the programmer must
gramming? think about at once, this technique effectively amplifies the programmer’s
Structured programming provides options to develop well-organized codes intelligence.
which can be easily modified and documented.
8.  What is top-down programming?
Modularity is closely associated with structured programming. The
Top-down programming is a technique of programming that first defines
main idea is to structure the program into functional groups. As a result,
the overall outlines of the program and then fills in the details.
it becomes easier for us to understand and therefore easier for teams of
  This approach is usually the best way to write complicated programs.
developers to work simultaneously on the same program.
Detailed decisions are postponed until the requirements of the large pro-
  Another advantage of structured programming is that it reduces com-
gram are known; this is better than making the detailed decisions early and
plexity. Modularity allows the programmer to tackle problems in a logical
then forcing the major program strategy to conform to them. Each part of
fashion. This improves the programming process through better organiza-
the program (called a module) can be written and tested independently.
tion of programs and better programming notations to facilitate correct and

exercises
1. What do you mean by structured programming? State the properties The number of terms to be printed should be given by the user.
of structured programming. (d) Convert an integer number in decimal to its binary equivalent.
2. What is top-down analysis? Describe the steps involved in top-down (e) Find the prime factors of a number given by the user.
analysis.
(f) Check whether a number given by the user is a Krishnamurty
3. What is a structured code? number or not. A Krishnamurty number is one for which the sum
4. What is an algorithm? of the factorials of its digits equals the number. For example, 145
5. Write down an algorithm that describes making a telephone call. Can is a Krishnamurty number.
it be done without using control statements? (g) Print the second largest number of a list of numbers given by the
6. Write algorithms to do the following: user.
(a) Check whether a year given by the user is a leap year or not. (h) Print the sum of the following series:
(b) Given an integer number in seconds as input, print the equiva- 2 4
(i) 1 - x + x + up to n terms where n is given by the user
lent time in hours, minutes, and seconds as output. The recom- 2! 4!
mended output format is something like: 1 1
7,322 seconds is equivalent to 2 hours 2 minutes 2 seconds. (ii) 1 - + - ◊◊◊◊◊ up to n terms where n is given by the
2 3
(c) Print the numbers that do not appear in the Fibonacci series. user
Introduction to Algorithms and Programming Concepts 135
1 1 Item Number:     345612
(iii) 1 + + + ◊◊◊◊◊ up to n terms where n is given by the Number Ordered: 1
2! 3!
user Number On Hand: 31
7. By considering the algorithmic language that has been taught, answer Price of Each:  19.95
the following: Weight of Each: 3
Shipping Zone:  A
(a) Show clearly the steps of evaluating the following expressions:
Total Cost:  30.95
3
(i) x – y + 12 * + k ^ x where x = 2, y = 6, k = 5 After all the purchases are finished, print two lines stating the
6
total number of purchases and the total cost of all purchases.
(ii) a AND b OR (m < n) where a = true, b = false, m = 7, 9. Fill in the blanks.
n=9
(i) A program flowchart indicates the __________ to be
(b) State whether each of the following is correct or wrong. Correct performed and the __________ in which they occur.
the error(s) where applicable.
(ii) A program flowchart is generally read from __________ to
(i) The expression (‘35’ = ‘035’) is true. __________.
(ii) x1 x2 * 4 value (iii) Flowcharting symbols are connected together by means of
(iii) INPUT K, Y – Z __________.
8. Write an algorithm as well as draw a flowchart for the following: (iv) A decision symbol may be used in determining the __________
Input or __________ of two data items.
∑ the item ID number (v) __________ are used to join remote portions of a flowchart.
∑ the Number On Hand (vi) __________ connectors are used when a flowchart ends on one
∑ the Price per item page and begins again on another page.
∑ the Weight per item in kg (vii) A __________ symbol is used at the beginning and end of a
∑ the Number Ordered flowchart.
∑ the Shipping Zone (1 letter, indicating the distance to the (viii) The flowchart is one of the best ways of __________ a pro-
purchaser) gram.
Processing (ix) To construct a flowchart, one must adhere to prescribed sym-
The program will read each line from the user and calculate the bols provided by the __________.
following: (x) The programmer uses a __________ to aid him in drawing flow-
Total Weight = Weight Per Item * Number Ordered chart symbols.
Weight Cost = 3.40 + Total Weight / 5.0 10. Define a flowchart. What is its use?
Shipping cost is calculated as follows: 11. Are there any limitations of a flowchart?
If Shipping Zone is ‘A’ 12. Draw a flowchart to read a number given in units of length and print
Then Shipping Cost is 3.00 out the area of a circle of that radius. Assume that the value of pi
If Shipping Zone is ‘B’
is 3.14159. The output should take the form: The area of a circle of
radius __________ units is __________ units.
Then Shipping Cost = 5.50
13. Draw a flowchart to read a number N and print all its divisors.
If Shipping Zone is ‘C’
14. Draw a flowchart for computing the sum of the digits of any given
Then Shipping Cost = 8.75
number.
Otherwise Shipping Cost is 12.60
15. Draw a flowchart to find the sum of N odd numbers.
Handling Charges = 4.00, a constant
16. Draw a flowchart to compute the sum of squares of integers from 1 to
New Number On Hand = Number On Hand Number Ordered 50.
Discount is calculated as follows: 17. Write a program to read two integers with the following significance.
If New Number On Hand < 0 The first integer value represents a time of day on a 24-hour clock, so
Then Discount = 5.00 that 1245 represents quarter to one mid-day.
Else Discount = 0 The second integer represents a time duration in a similar way, so that
Here the purchaser is being given a discount if the item has to 345 represents three hours and 45 minutes.
be repeat ordered. Total cost is calculated as follows: This duration is to be added to the first time and the result printed out
Total Cost in the same notation, in this case 1630 which is the time 3 hours and
= Price of Each * Number Ordered + 45 minutes after 1245.
  Handling Charge + Weight Cost +
Typical output might be: start time is 1415. Duration is 50. End time is
  Shipping Cost – Discount
1505.
For each purchase, print out the information about the purchase
in a format approximately like this:

You might also like