Introduction To Algorithms and Programming Concepts
Introduction To Algorithms and Programming Concepts
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
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.
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”
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
START STOP
Start or end of the program or A magnetic tape
flowchart
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
21. Draw a flowchart to find the sum of the first 50 natural numbers.
False
Decision
Solution
START
True
SUM = 0
NO NO
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 = C GRADE = D
STOP Step 5: STOP
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
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
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: