introduction to pseudocodes & algorithms
introduction to pseudocodes & algorithms
Algorithms, Flowcharts,
Pseudocode Programs
5.1 INTRODUCTION
An algorithm is a step-by-step list of instructions for solving a particular problem.
EX A M PLE 5.1 The First National Bank wants to calculate and record the INTEREST on a home mortgage for
a certain customer. Assuming that the BALANCE of the mortgage and the RA TE of interest appear in the
customer’s record, a suitable algorithm follows:
STEP 1. Obtain NAME, BALANCE, RA TE from customer’s record.
STEP 2. Calculate: INTEREST = BALANCE x RATE.
STEP 3. Record customer’s NAME and INTEREST in the interest file.
Here a r e c o r d means a collection of related data items, e.g. data on a given customer, and a f i le is a collection of
similar records.
There are two ways of presenting an algorithm other than by means of a numbered list of
instructions. One way, the most popular, is by a flowchart, in which the essential steps of the
algorithm are pictured by boxes of various geometrical shapes and the flow of data between steps is
indicated by arrows, or flowlines. Figure 5-1 is a flowchart of the algorithm of Example 5.1. Al
though the flowchart may seem redundant in this case, it is frequently an indispensable tool in
formulating complex types of algorithms.
Another way of presenting an algorithm is to write it in pseudocode language, to be discussed at
the end of this chapter.
Suppose now that we want to execute an algorithm using an electronic computer. This can be
done by translating the algorithm (from its flowchart or pseudocode form) into a computer program
F ig. 5-1
95
96 A L G O R IT H M S , F L O W C H A R T S , P S E U D O C O D E P R O G R A M S [C H A P . 5
Source Object
program program
Program
written Translation Machine-
in language
high-level by compiler instructions
language
Fig. 5-2
Each programming language has its own character set which includes the 10 digits, the 26 letters,
and special characters (see Section 2.6). This character set, together with the syntax of the language,
is used to write a program. Whatever the language, however, the notions of variable-names and
constants apply.
Variable-Names
The term variable in computer terminology normally means (i) a storage location in the memory
of the computer reserved for a specific data item. Alternately, a variable may mean (ii) the data
item itself that is stored in the corresponding storage location. Each variable (in either sense) in a
computer program is supplied a name or label, called a data-name or variable-name. Normally,
one chooses names so that they indicate the kind of data item they represent. For example, RATE
could be chosen to denote the hourly rate of pay for an employee in a company. One may then
speak of the “variable RA TE,” or the “storage location RA TE,” or the “address R A TE.” Note that
the value of RA TE [sense (ii)] may change during the execution of the program. For example, RATE
may be $8.25, $9.00, $9. 75, . . . , depending on the particular employee.
Each programming language has its own rules for forming variable-names, e.g. they cannot
exceed two characters in BASIC, or six characters in FORTRAN. Variable-names generally are
formed from alphameric characters, with the first character always alphabetic. Furthermore, certain
words (e.g. DATA, STOP, IF, LET in BASIC) have a special meaning in the language and hence
cannot be chosen as variable-names. These are called reserved words in the language.
Constants
A constant in a computer program is an item of data that does not change during the execution
of the program. Constants are sometimes called literals. There are basically two kinds of constants,
which appear in almost every prQgramming language.
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 97
Terminal Symbol
The oval symbol is used to indicate the beginning or end of an algorithm by
respectively. Clearly, a flowchart can contain only one Start symbol; however, it can contain more
98 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
Symbol Name
O Terminal
/ 7 Input/Output
Process
« o Decision
o Connector
(3 D Preparation
Fig. 5-3
than one Stop symbol, since the algorithm may contain alternative branches. Sometimes we omit
the Start and/or Stop symbols if it is clear where the algorithm begins and/or ends.
This symbol is also used to indicate a pause in the algorithm; e.g. it may be necessary to change
the forms in an output printer. Hence the symbol may sometimes be labeled with “ Pause.”
j Read A, B, C, D
to indicate that data are to be inputted into the memory locations A, B, C, and D, in that order.
Observe that the input statement begins with the word “ Read” and is followed by variable-names
separated by commas. Similarly,
j W rite X, Y, Z
7
indicates that the data in the memory locations X, Y, Z are to be outputted. The output statement
begins with the word “W rite” and also is followed by variable-names separated by commas. We can
also output messages by including the message in single quotation marks; e.g.
Process Symbol
The rectangle symbol is used to indicate a processing operation. This can be an assignment
statement, defined below, or it can be a macroinstruction, whose programming language translation
would otherwise require an entire list of computer statements; e.g.
are macroinstructions.
The assignment statement has the form
That is, only a variable-name can appear on the left side of the equals sign, = , but any arithmetic
expression involving variables, constants, and arithmetic operations can appear on the right side of
the equals sign. (Arithmetic expressions include individual variables or constants as special cases.)
Another acceptable form for an assignment statement is
EXAMPLE 5.2
(a) Suppose that we want to add the numbers (numeric constants) A, B and C. We could not write
A + B+ C
since the sum must be placed in a definite memory location. We can write
SUM = A + B + C
which directs that the result of the additions be stored in the memory location SUM. We could not write
A *f B + C = SUM
since only a variable-name may appear on the left side of the assignment statement.
(b) Suppose we want to increase the value of the variable K by 1. We might accomplish this by writing
K=K +1
100 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
Note first that this is not a mathematical statement, for K does not in fact equal K + 1. However, as an
assignment statement, it tells the computer to add 1 to the number currently in storage location K and then
to assign the sum back to location K. The net effect is to increase the value stored at K by 1.
EXAMPLE 5.3 Figure 5-4 is a flowchart for finding the sum S, the average A, and the product P of three
numbers X, Y, and Z. Observe that three assignment statements are put into one process symbol. Observe
also that the heads of the arrows are omitted, since the direction of the flow is obviously from top to bottom.
f S tart j
j Read X, Y. Z j
S=X+Y+Z
A = S/3
P = XxYxZ
Write S, A,
^ Stop ^
Fig. 5-4
Decision Symbol
One of the powerful properties of a computer is its ability to decide whether or not two field
values are equal, and, if they are unequal, to decide which is the larger. That is, the computer can
determine the truth value of a statement involving one of the six mathematical relations symbolized
in Table 5-1. In practice, the computer is presented not with a true/false statement, but with a
question having a “Yes” or “No” answer; e.g.
Is A = B? Is K < 25? Is SALES > $5000?
The computer can also be programmed to answer questions which involve one or more of the logical
connectives “and,” “or,” and “not,” or questions to which there are more than two possible answers;
e.g.
Is X ^ 50 and Y < 75? Is D positive, negative, or zero?
Table 5-1
Symbol Meaning
= Equals
* Not equal
< Less than
< Less than or equal
> Greater than
> G reater than or equal
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 10 1
With each question, the computer can be programmed to take a different course of action depending
on the answer. A step in an algorithm or program that leads to more than one possible continuation
is called a decision.
The diamond-shaped symbol is used to indicate a decision. The question is placed inside the
symbol, and each alternative answer to the question is used to label the exit arrow which leads to the
appropriate next step of the algorithm. We note that the decision symbol is the only symbol that
may have more than one exit.
EXAMPLE 5.4 Figure 5-5 shows a flowchart which reads two numbers, A and B, and prints them in decreasing
order, after assigning the larger number to BIG and the smaller number to SMALL. Observe the two arrows
leaving the decision “Is A < B ? ” , one labeled “no” and the other labeled “yes.” For notational convenience,
the word “Is” will frequently be omitted from questions.
Fig. 5-5
EXAMPLE 5.5 (Quadratic Equation). Recall that the solutions of the quadratic equation
a x 2 + bx +c=0
where a ¥ 0, are given by the quadratic formula
-b ± yJb1- 4ac
X = --------2a--------
The quantity D = b2-4ac is called the discriminant of the equation. If D is negative, then there are no real
solutions. If D = 0, then there is only one (double) real solution, x = - b/2a. If D is positive, the formula
gives two distinct real solutions. Figure 5-6 is a flowchart which inputs the coefficients A, B, C of a quadratic
equation, and outputs the real solutions, if any. Observe that there are three exits to the question “Sign of
D ?” , each leading to a different output.
102 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
Connector Symbol
A flowchart that is long and complex may require more than one sheet of paper, which means that
certain flowlines cannot be drawn; or the flowchart may contain crossing flowlines that could cause
confusion. The connector symbol, a small circle, is used to remedy such situations. Specifically, one
assumes that a flowline exists between any pair of identically labeled connector symbols such that the
flow is out of the flowchart at one of the connectors (exit connector) and into the flowchart at the other
connector (entry connector). For each connector label, there is a unique entry connector, but one or
more exit connectors. Figure 5-25 is a flowchart that uses connectors.
Preparation Symbol
This symbol indicates the preparation for some procedure by initializing certain variables.
Many programmers indicate a preparation by means of the process symbol. We use the preparation
symbol in Section 5.5.
5.4 LOOPS
Suppose that we want to read data from a record, process the data, and output the results. The
flowchart of such a procedure appears in Fig. 5-7(a). Now suppose that we want to repeat this
procedure for every record in the file. Such a repetitive operation is called a loop, with the handling
of each record constituting one cycle or iteration. One might picture a loop by drawing an arrow
from the last step of the procedure back to the first step, as in Fig. 5-7(b), but this would indicate no
mechanism for exiting from the loop. A means of controlling a loop will now be discussed, and
another way in Section 5.5.
(а)
Fig. 5-8
104 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
End-of-File Record
Normally a data processing system uses a record with special data at the end of each file. This is
called an end-of-file (EOF) record or a trailer record. Accordingly, after a record has been read,
the computer may be asked one of the following equivalent questions:
The loop of Fig. 5-7(b) may be controlled by such a decision, as shown in Fig. 5-8. It is clear that
cycling now ends when all records have been read and processed.
Counters
In order to count the number of records processed by the flowchart of Fig. 5-8, we might initially
set a variable, say COUNT, equal to zero, and then increase COUNT by 1 every time a record is
processed; we would output the value of COUNT upon leaving the loop. It is clear from Fig. 5-9
that the final value of COUNT will be exactly equal to the number of records that have been
processed. A variable like COUNT is called a counter. Observe that the counter required an
initialization as a preparation for the loop; hence we used the preparation symbol in Fig. 5-9.
Accumulators
Suppose that a company wants to find its total weekly payroll, i.e. the sum of all its employees’
salaries as listed in the personnel file. If there are only three employees, with salaries X, Y, Z, then
it is clear that the sum S can be found by use of the assignment statement
S = X + Y+ Z
as in Example 5.3. On the other hand, with many employees, we find the sum of the salaries as in Fig.
5-10. That is, we choose a variable, say SUM, and initially set
SUM = 0
we are able to add the salaries to SUM one after the other as they are inputted from the records.
Clearly, the final value of SUM upon leaving the loop will be the sum of all the salaries. A
variable like SUM is called an accumulator, for obvious reasons. Observe that the accumulator
SUM required an initialization as a preparation for summing the salaries; hence the use of the prepa
ration symbol.
Fig. 5-10
106 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
DO Loops
Figure S-U (a) shows a loop whereby a certain procedure is executed exactly N times, the value
of N being a fixed positive integer. The loop involves a variable K, essentially a counter. Initially
we set
If the answer is “No,” the procedure is repeated. After N cycles an answer of “Yes” is obtained,
and we exit from the loop. This type of loop occurs so often that it is given a name, DO loop, and a
shorthand flowchart notation, Fig. 5-11(6). The variable K is called the index of the DO loop, and
the procedure which is iterated is called the body of the loop.
Fig. 5-11
In Fig. 5-11(6), the initial value of the index and its increment are both 1. This is not a necessary
restriction. If, instead, a statement such as
«
Do K = 2 to 10
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 107
is used, then 2 will be the initial value, 10 the limit value, and 3 the increment. Thus, we first
execute the loop with K = 2. Then we increment K by 3, and execute the loop with K = 5. Again
we increment K by 3, and execute the loop with K = 8 . However, the next time we increment K by
3, we get 11, which exceeds the limit value 10, and so we exit from the loop. DO loops of this more
general type are often required when the index K also figures in the body of the loop.
EXAMPLE 5.6 Find the positive odd integers, along with their squares, that do not exceed N, where N is an integer
greater than 1 which is inputted into the program.
Figure 5-12(a) is the flowchart of a suitable program. Observe that the initial value of K is 1, the increment
is 2, and the test value is N. The equivalent D O loop appears in Fig. 5-12(£).
Conditions. However, instead of arrows or flowlines to indicate the logic of an algorithm, the
pseudocode program uses three types of organization: (i) sequence logic, (ii) selection logic, and (iii)
iteration logic.
Sequence Logic
Under this logic, the instructions in a pseudocode program are executed in order, from the top to
the bottom (see Fig. 5-13). Although it is not necessary to have a Start statement or Stop statement
(since the program begins at the top and ends at the bottom), we frequently signal the completion of
a pseudocode program by writing END at the bottom of the program. For example, a pseudocode
program equivalent to the flowchart of Fig. 5-1 might appear as follows:
Sometimes we begin the program with a title, e.g. here “Calculating Interest.”
Pseudocode Program
P ro cess A
P ro c e ss B
Flowchart Equivalent
Selection Logic
This logic employs a number of structures, called IF-structures, each of which is essentially a
selection of one out of several alternatives. Each such structure begins with a statement of the form
IF condition
ENDIF
C H A P . 5] A L G O R IT H M S , F L O W C H A R T S , P S E U D O C O D E P R O G R A M S 109
The condition in the beginning statement can usually be paraphrased as a question with a “Yes” or
“No” answer.
Single alternative. The appropriate structure is called an IF T H E N structure -, its logic is illus
trated in Fig. 5-14. That is, IF the condition holds, THEN procedure A, the coding of which may
involve one or more statements, is executed; otherwise procedure A is skipped, and control transfers
to the first statement following the EN DIF statement.
Pseudocode Program
IF condition
[Procedure A]
EN D IF
Flowchart Equivalent
EXAMPLE 5.7 T h e fo llo w in g p se u d o c o d e program , w hich calcu lates an e m p lo y e e ’s W A G E S giv en his h ourly
R A T E o f pay and th e n u m b er o f H O U R S w ork ed , u se s an IF T H E N structure:
read N A M E , R A T E , H O U R S
W AGES = HOURS x RATE
IF H O U R S > 4 0
W A G E S = W A G E S + (H O U R S - 40) x 0.5 x R A T E
E N D IF
w rite N A M E , W A G E S
END
Double alternative. An IF TH E N E LSE structure is used for decisions involving two distinct
alternatives. Its logic appears in Fig. 5-15. Observe that an ELSE statement separates two
procedures. As indicated by the flowchart, IF the condition holds, THEN procedure A (above the
ELSE statement) is executed; ELSE procedure B (below the ELSE statement) is executed.
110 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
IF condition
{Procedure A|
ELSE
\Procedure 0j
ENDIF
Fig.
EXAMPLE 5.8 Following is a pseudocode program for Example 5.4 (whose flowchart appears in Fig. 5.5).
read A, B
IF A < B
BIG = B
SMALL = A
ELSE
BIG = A
SMALL = B
ENDIF
write BIG, SMALL
END
Again observe how the procedure blocks are indented for easier reading.
EL SE IF condition
betw een the IF and EL SE statem ents. O bserve that only on e o f the procedures w ill be execu ted ,
th e on e that follow s the first condition which h olds. If none o f the conditions h olds, then the procedure
follow ing the EL SE statem ent is executed. If this procedure is em pty, then the EL SE statem ent itself
m ay be om itted. (S ee Problem 5.46.)
EXAMPLE 5.9 Following is a pseudocode program for Example 5.5 (flowcharted in Fig. 5 -6 ).
read A, B, C
D = B *-4x A x C
IF D > 0
Xl = (-B + VDV(2xA)
X2 = (-B - VD)/(2 x A)
write XI, X2
ELSEIF D = 0
X = —B/(2 x A)
write 'UNIQUE SOLUTION1, X
ELSE
write'NO REAL SOLUTIONS'
ENDIF
END
Again observe the indented procedure blocks.
Pseudocode Program Flowchart Equivalent
IF condition (I)
[Procedure A i\
ELSEIF condition(2)
lProcedure A 2]
ELSEIF conditioner! )
[Procedure A m]
ELSE
[Procedure B J
ENDIF
Iteration Logic
This logic refers to structures involving loops, of which there are three types. One type, already
flowcharted in Section 5.5, begins with a DO statement, which has the form
DO K = 1 to N or DO K = INV to ENDV by INCR
Another type begins with a DOW HILE statement, which has the form
DOW HILE condition
and the third type begins with a DOUNTIL statement, which has the form
DOUNTIL condition
All three types end with the statement ENDDO, which indicates the end of the loop.
The form and logic of the DO structure appears in Fig. 5-17. Here, K is called the index of the
loop, INV the initial value, ENDV the end value or test value, and INCR the increment (By
convention, the “by INCR” may be omitted from the DO statement when INCR = 1.) Observe that
the body of the loop is executed first with K = INV, the initial value. After each cycle, K is incremented
by INCR and tested against ENDV. The cycling ends as soon as K exceeds ENDV. The flowchart in
Fig. 5-17 assumes that INCR is positive; if INCR is negative, so that K decreases in value, then the cycling
ends as soon as K < E N D V . [See Problem 5.16(d).]
read N
D O K = 1 to N by 2
L = K2
w rite K, L
ENDDO
END
The form and logic of the DOW HILE structure appears in Fig. 5-18, and that of the DOUNTIL
structure in Fig. 5-19. Since these structures are loops, there must be a statement before the
structure that initializes the condition which controls the loop, and there must be a statement in the
body of the loop that changes the condition, in order that looping may eventually cease. Looping
continues in the DOW HILE loop until the condition is not met, whereas looping continues in the
DOUNTIL loop until the condition is met. This is a minor difference, since one can always impose
the negation of the underlying condition. More significant is the fact that the condition in the
DOWHILE c o n d it io n
[ P rocedu re 1
(body of loop) J
ENDDO
f
Fig. 5-18. DOWHILE Structure
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 113
DOUNTIL c o n d it io n
T P ro ced u re 1
L(body of loop)]
ENDO
Fig. 5-19.
DOW HILE loop is tested at the beginning of the loop, whereas the condition in the DOUNTIL loop
is tested at the end of the loop. Therefore, the body of the DOUNTIL loop is always executed at
least once, but the body of the DOW HILE loop need not be executed at all.
EXAMPLE 5.11 Either of the following pseudocode programs will accomplish the task of Example 5.6 (see Fig.
5-12).
read N read N
K= 1 K= 1
DOW HILE K < N DOUNTIL K > N
L = K2 L = K2
write K, L write K, L
K= K+ 2 K= K+2
ENDDO ENDDO
END END
Observe that the programs are identical, except that the conditions controlling the loops are the negations of
each other.
EXAMPLE 5.12 Suppose that a company’s personnel file contains the names and ages of all its employees, and
that the company wants a list of all its employees who are under 30 years of age. The following pseudocode
program accomplishes this task:
read NAME, A G E from record
DOUNTIL End of File
IF A G E < 3 0
write NAME
ENDIF
read NAME, A G E from next record
ENDDO
END
Observe that the first read statement initializes the condition controlling the loop, and the second read state
ment changes the condition. Observe also the double indenting, one for the DO-structure and one for the
IF-structure contained inside the loop. (We assume implicitly that the file contains data for at least one
employee; otherwise we would need to use the DOW HILE loop.)
programming languages that are very similar to the above-given pseudocode structures. Thus the
pseudocode expression of an algorithm fits in nicely with structured programming techniques.
Remark 2 : To “code” normally means to translate an algorithm into a well-defined program
ming language. Pseudocode, like flowcharts, may be used to help write programs in almost any
programming language. In other words, pseudocode programs (like flowcharts) are essentially
language-independent.
Solved Problems
5.2 What is meant by the source program and the object program in computer programming?
The s o u r c e p r o g r a m refers to the original program, written in a high-level language. Translated into
machine-language instructions, the source program becomes the o b j e c t p r o g r a m .
5.3 The different programming languages use different character sets. (True or false.)
True. Although all programming-language character sets include the 10 digits and the 26 letters,
they normally include different selections of special characters.
5.4 Which of the following are acceptable variable-names (a) in BASIC? (b) in FORTRAN?
(i) X (iii) RA TE (v) 4H (vii) A (ix) K*
(ii) X2 (iv) INTEREST (vi) X/B (viii) A9 (x) A G E
(a) (i), (ii), (vii), and (viii). Variable-names in BASIC are either a single letter or a letter followed by a
digit.
(b ) (i), (ii), (iii), (vii), (viii), and (x). A variable-name in FORTRAN consists of one to six alphameric
characters, with the first character being a letter.
5.6 In a parenthesis-free arithmetic expression, the strengths of the operations determine the order in
which they are performed. In BASIC (or in FORTRAN, with ** instead of f ), the symbols for
the five fundamental operations and their strengths are as follows:
Strongest: f exponentiation
Next-strongest: * multiplication / division
Weakest: + addition - subtraction
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 115
Within an equal-strength group, the operations are to be carried out from left to right. The
strength order is overridden if parentheses are introduced in the BASIC formula; then, the
expression(s) in parentheses is (are) evaluated (following the strength order) before anything
else. Give BASIC formulas for
(/>) x 3 - 4 x 2 + 7x + 6 (d )
Note first that only capital letters can be used and that all expressions must be typed on one line.
(«) X f2+2*X *Y +Y t2
(b) X f3 —4*Xf2+7*X+6
(c) A+(B+C)/(2*D)
(4) A/B—C|2/(3*A )
5.7 Referring to Problem 5.6, evaluate each of the following BASIC expressions:
(a) 3+2*6-12/3 (c) 4 *3f2/2-2f3+ l
(b) (3+2)*(6-12)/3 (d) (4*3)t2/2t(3+l)
(a ) First, 2*6 = 12 and 12/3 = 4, giving
3 + 1 2 -4
Then, 3 + 12 = 15, and, finally, 15 - 4 = 11.
(b ) First, 3 + 2 = 5 and 6 - 1 2 = - 6 , giving
5*(-6)/3
Then, 5*(-6) = -3 0 , and, finally, (-30)/3 = -1 0 .
(c) First, 3f2 * 9 and 2 |3 = 8, giving
4*9/2-8+ l
Then, 4*9 = 36 and 36/2 = 18, giving 1 8 - 8 + 1 . Next, 18 - 8 = 10, and, finally, 10 + 1 = 11.
(<d ) First, 4*3 = 12 and 3 + 1 = 4, giving
12t2/2|4
Then 12f2 = 144 and 2 |4 = 16, which yields 144/16. Finally, 144/16 = 9.
FLOWCHARTS
5.8 A file of incoming freshmen contains, among other data, each student’s NAM E and SCORE
on an entrance examination. Draw a flowchart which will list the names of those students
with perfect scores of 10 0 .
Figure 5-20 is such a flowchart. There are two decisions, one which tests if SCORE = 100 and one
which tests for End of File.
5.9 Each record in a student file contains, among other data, the student’s W EIGHT. Draw a
flowchart which finds the average weight of the students.
Figure 5-21 is the flowchart. Note the need for an accumulator, SUM, to add the weights of the
students, and a counter, N, to enumerate the students. The average weight, MEAN, is the final SUM
divided by the final N.
116 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
5.10 Each record in a student file contains, among other data, the student’s HEIGHT. Draw a
flowchart which finds the height of the tallest student.
Figure 5-22 is such a flowchart. Observe that each time we read a new HEIGHT, we compare
it to the variable TALL. If the new H EIG H T exceeds TALL, then we reset TALL equal to the new
HEIGHT. Thus, at any given moment, TALL contains the height of the tallest student processed up to
that point. Accordingly, TALL will contain the height of the tallest student(s) when all the student
records have been processed. We also initially assign TALL = 0 to begin the process.
Fig. 5-23
118 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
5.11 The amounts of annual dues to a professional association are given in Table 5-2. Draw a
flowchart with input SALARY and output DUES.
Table 5-2
Figure 5-23 gives such a flowchart. Of the two decisions, the first asks if the salary exceeds $30 000
and the second asks if the salary exceeds $20 000 (but does not exceed $30 000).
(a) (b )
Fig. 5-24
(a) The statement A = B assigns the current value of B, which is 10, to A. Hence the value of A is
changed to 10. The statement B = A assigns the current value of A, which is 10, to B. Hence the
value of B remains at 10. Thus the output is 10 and 10; the values of A and B are not inter
changed by the two statements.
(b ) Here the values of A and B become interchanged. Specifically, TEMP = A assigns the original
value of A to the “temporary” location TEMP, i.e. TEMP = 5. Now A = B assigns the value of B
to A; so A = 10. Finally, B = TEMP assigns the original value of A, which is stored in TEMP, to
B; so B = 5. Thus the values of A and B are interchanged, and the output is 10 and 5.
5.13 Trace the values of A and B through the flowchart of Fig. 5-25 to find the outputs given the
inputs ( a ) A = 10, B = 5; ( b ) A = 3, B = 5; (c) A = 5, B = 10.
(a ) Since A = 10, B = 5, the answer to “A < B ?” is “No” ; hence A = A2 + B is executed, giving
A = 102 + 5 = 100 + 5 = 105
Then B = B + 5 x A i s executed, giving
B = 5 + 5 x 105 = 5 + 525 = 530
Hence the output is A = 105, B = 530.
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 119
Fig. 5*25
(b) Since A = 3, B = 5, the answer to “A < B?” is “Yes” ; hence A = A + 2 x B i s executed, giving
A = 3 + 2 x 5 = 3 + 1 0 = 13
The answer to “A < 20?” is also “Yes” ; so B = B + 10 is executed, yielding
B = 5 +10 = 15
Hence the output is A = 13, B = 15.
(c) Since A = 5, B = 10, the answer to “A < B?” is “Yes” ; hence A = A + 2 x B i s executed, giving
A = 5 + 2 x l 0 = 5 + 20 = 25
Now the answer to “A < 20?” is “No” ; s o B = B + 5 x A i s executed, yielding
B = 10 + 5 x 2 5 = 10+ 125= 135
Hence the output is A = 25, B = 135.
5.14 Find the outputs of the flowchart in Fig. 5-26, assuming the inputs (a) X = 2, Y » 5; (6 ) X = 2,
Y = 12.
Note first that there are three connectors labeled A, two labeled B, and three labeled C. As required,
there is only one entrance connector for each label.
(a ) Since X = 2, Y = 5, the answer to “X < 10?” is “Yes” ; hence X = X + Y is executed, giving
X = 2+5 = 7
The answer to “Y < 10?” is also “Yes” ; hence Y = Y + X is executed, giving
120 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
Y = 5 + 7 = 12
Then Z = X + Y yields
Z = 7 + 12 = 19
Thus the output is Z = 19.
Fig. 5-26
(b) Since X = 2, Y = 12, the answer to “X < 10?” is “Yes” ; hence X = X + Y is executed, yielding
X = 2 + 12 = 14
The answer to “Y < 1 0 ? ” is “No” ; hence, by way of connector A, we go to the statement
Y = Y + 5. This gives
Y = 12 + 5 = 17
The answer to “Y < 20?” is “Yes” ; hence X = X + 10 is executed, giving
X = 14+10 = 24
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 12 1
The answer to “X < 20?” is “No” ; hence, by way of connector C, we go to Y = Y + X. This gives
Y = 17 + 2 4 =41
Then Z = X + Y yields
Z = 24 + 41 = 65
Thus the output is Z = 65.
DO LOOPS
5.15 Draw a flowchart having a DO loop, which inputs a positive integer N and outputs
(a) i +1 + i +l + . . . +l (b )
(a) Figure 5-27(a) is such a flowchart. Observe that the index K also is involved in the body of the
loop. The accumulator SUM is used to add up the 1/K for K = 1 to N.
(b) Figure 5-27(6) is such a flowchart. Here we need to multiply 1/K by (-1 )K+1 to make sure that the
even values of K contribute negative summands.
L Read N / / Read N /
C SUM = 0 \ / SUM = 0 \
^ i
< Do K = 1 to N j---------- D o K - 1 t o N y
I__________ I_____________
Fig. 5-27
5.16 Find the number of cycles, and the value of K for each cycle, for DO loops headed by:
(a) Do K = 1 to 10 by 2 (c) Do K = 5 to 3 by 4
(b ) Do K = 5 to 20 by 4 (d ) Do K = 15 to 5 b y - 4
(a) The initial value for K is K = 1. Then K is increased by 2 each time, giving odd values for K. But
10 is the end value; hence the loop is executed for
K =1 K=3 K=5 K= 7 K= 9
or 5 times [unless there is an abnormal exit, as discussed in Problem 5.17(6)].
122 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
Fig. 5-28
(a) The header statement indicates that the loop is to be executed five times, for K = 1 ,3 ,5 ,7 ,9 . As
the answer to “K = 6?” is “No” for all five values of K, SUM = SUM + K is in fact executed five
times. We have:
(1) For K = 1, SUM = 0 + 1 = 1. (4) For K = 7, SUM = 9 + 7 =16.
(2) For K = 3 , S U M= 1 + 3 = 4. (5) For K = 9, SUM = 16 + 9 = 25.
(3) For K = 5, SUM = 4 + 5 = 9.
W e now exit from the loop to “Write SUM” ; hence the output is 25. This is a case of n o r m a l e x it ,
since all cycles indicated by the header statement were completed.
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 123
(ft) The header statement again indicates that the loop is to be executed five times, for K = 1, 3, 5 ,7 , 9.
The answer to “K = 7?” is “No” for the first three values of K; hence SUM = SUM + K is executed
for these values of K:
(1) For K = 1, SUM = 0 + 1 = 1 .
(2) For K = 3, SUM = 1 + 3 = 4.
(3) For K = 5, SUM = 4 + 5 = 9.
But, at the beginning of the fourth cycle of the loop, the answer to “K = 7?” is “Yes” ; hence, by
Fig. 5-28(ft), we exit from the loop to “Write SUM.” Thus, the output is 9, the last value of
SUM. This is a case of a b n o r m a l e x i t , since not all cycles indicated by the header statement were
completed.
PSEUDOCODE PROGRAMS
5.18 A salesman’s commission is 5% of his total weekly sales, with an extra $100 if the sales exceed
$10 000. Write a pseudocode program which identifies a salesman and calculates his COM
MISSION.
read NAME, SALES
COMMISSION = 0.05 x SALES
IF SALES > 1 0 000
COMMISSION = COMMISSION + 100
ENDIF
Write NAME, COMMISSION
END
Observe that an IFTHEN structure is used.
5.19 Refer to Table 5-2. (a) Write a pseudocode program which inputs NAME, SALARY and
outputs NAME, DUES. (Compare with Problem 5.11.) (ft) Repeat (a) if, in addition to
Table 5-2, there is a ceiling of $400 placed on dues.
(a) read NAME, SALARY
IF SALARY > 3 0 000
DUES = 250 + 0.015 x (SALARY - 30 000)
ELSEIF SALARY > 20 000
DUES = 150 + 0.01 x (SALARY - 20 000)
ELSE
DUES = 150
ENDIF
write NAME, DUES
END
An ELSEIF structure is used because there are three alternatives.
(ft) read NAME, SALARY
IF SALARY > 30 000
DUES = 250 + 0.015 x (SALARY - 30 000)
IF DUES >400
DUES = 400
ENDIF
ELSEIF SALARY > 20 000
DUES = 150 + 0.01 x (SALARY - 20 000)
ELSE
D U E S = 150
ENDIF
write NAME, DUES
END
Observe the embedded IFTHEN structure in the first alternative, which limits dues to $400.
124 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
5.21 Write a pseudocode program for the algorithm in Fig. 5-20, which finds the average weight for
a list of students.
SUM = 0
N= 0
read W EIGHT
DOUNTIL End of File
SUM = SUM + WEIGHT
N = N+1
read next W EIGHT
ENDDO
MEAN = SUM/N
write MEAN
END
The first read statement, which initializes the condition controlling the DOUNTIL structure, appears
before the structure; the second read statement, which changes the condition, appears within the
structure.
/
5.22 Referring to Problem 5.8, write a pseudocode program which lists the names of those students
with perfect scores of 100, and also finds the number N of such students.
Again we need two read statements, one initializing the condition controlling the loop and the other
changing the condition.
N= 0
read NAME, SCORE
DOUNTIL End of File
IF SCORE =100
write NAME
N=N+1
ENDIF
read next NAME, SCORE
ENDDO
write N
END
Observe that N is used as a counter to enumerate the students who score 100. Because an IFTHEN
structure is nested in the loop, there is a double indentation of the program.
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 125
5.23 Each record in a student file contains, among other data, the student’s NAME and HEIGHT.
Write a pseudocode program which finds the name and height of the tallest student. (Compare
with Problem 5.10.)
The pseudocode program follows, where again we have two read statements.
TALL = 0
TALLMAN = »JOHN DOE»
read NAME, H EIG H T
DOUNTIL End of File
IF TALL < H EIG H T
TALL = H EIG H T
TALLMAN = NAME
ENDIF
read next NAME, H EIGHT
ENDDO
write »THE TALLEST STUDENT IS!, TALLMAN, »WITH HEIGHT», TALL
END
/
Here, TALL is a numerical variable, initialized by TALL = 0, but TALLMAN is a nonnumerical
variable, initialized by TALLMAN = »JOHN DOE». At the end of any iteration, TALL and TALL
MAN contain, respectively, the height and name of the tallest student yet processed; hence the final
values of TALL and TALLMAN will yield the required height and name of the tallest student.
Supplementary Problems
5.25 A compiler translates a source program into an object program. (True or false.)
5.26 A data item whose value may change during the course of a program is called a ( a ) ________, whereas a
data item whose value normally does not change during the course of a program is called a ( b ) ________.
5.28 Which of the character strings in Problem 5.27 are unacceptable as variable-names in FORTRAN?
(a) x2 + y2 (c) (e ) —
' c + d x J yz
(b) (x + y)2 (d ) t n+l (/) ( x 2 + 2 x y - y 2)5
5.31 Write a FORTRAN formula for fn+1 (a) using parentheses, (b) without parentheses.
126 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
5.35 An automobile dealership uses CODE = 1 for new automobiles, CODE = 2 for used automobiles, and
CODE - 3 for separate accessories. A salesman’s commissions are as follows: on a new automobile,
3% of the selling price but with a maximum of $300; on a used automobile, 5% of the selling price but
with a minimum of $75; on accessories, 6 %. Draw a flowchart or write a pseudocode program with
input CODE and PRICE and output COMMISSION.
5.37 Three positive numbers a, b, c can be the lengths of the sides of a triangle provided each number is less
than the sum of the other two, i.e.
a<b+c h<a +c c<a + h
Draw a flowchart or write a pseudocode program with input a, b, c and output 'YES1 or fNO!, according as a
triangle can or cannot be formed.
5.38 Find the outputs of the flowchart in Fig. 5-25 for the inputs (a) X= 15, Y= 20; (b) X= 15, Y = 5;
(c) X = 2, Y = 18.
5.39 Write the pseudocode program corresponding to the flowchart in Fig. 5-25.
5.40 In which of the process symbols below can the two statements be interchanged without changing the
resulting values of the variables?
C= A C=A
UQ
< <
n H
D=B C=B
C= A
II II
> O
68 >
II II
> o
o >
D=C
5.41 Find the outputs of the following pseudocode program for the inputs (a) A = 15, B = 22; (b ) A = 18,
B = 7; (c) A = 9, B = 7; ( d ) A = 2, B = 5; ( e ) A = 6, B = 3.
read A, B
IF A < B
IF A < 10
X= A + B
ELSE
X= B - A
ENDIF
ELSEIF B < 5
X=AxB
ELSEIF A < 15
X = A2
ELSE
X = B2
ENDIF
write X
END
5.42 Draw the flowchart that corresponds to the pseudocode program of Problem 5.41.
LOOP STRUCTURES
5.43 With reference to Problem 5.8, draw a flowchart or write a pseudocode program which lists the names of
the A students (those with scores of 90 or above) and finds the number and percentage of such students.
5.44 Write a pseudocode program using the DOW HILE structure that finds all pairs of positive integers m, n
such that
m 2+ 2n2< 100
5.45 Draw a flowchart or write a pseudocode program which finds the largest and smallest of 25 distinct
numbers.
5.46 Draw a flowchart or write a pseudocode program which finds the second-largest of 25 distinct numbers.
y = 2 t3 - t 2 - 3 7 t + 36
Write a pseudocode program which outputs y corresponding to each t from - 5 to 5 in steps of 0.25, and
finds the maximum and the minimum of the calculated values of y.
5.49 Find the number of cycles and the value of the index K for each cycle if a DO loop is headed by:
(a ) Do K = 1 to 20 by 3 (c) Do K = 7 to 5 by 2
(b ) Do K = 4 to 9 by 2 (d ) Do K = 15 to 10 by - 2
128 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
5.26 (a) variable, (b) constant 5.29 (A), (d), (/), (g), (A)
5.32 (a) 27, (A) 16, (c) 11, (d) 16, (e) 48, (/) 15
Fig. 5-29
5.43 N=0
A=0
read NAME, SCORE
DOUNTIL End of File
IF SCORE > 9 0
write NAME
A=A+1
ENDIF
N = N+ 1
read next NAME, SCORE
ENDDO
PERCENT = 100 x A/N
write ’NUMBER OF A STUDENTS IS’, A
write ’PERCENTAGE OF A STUDENTS IS', PERCENT
END
5.44 M= 1
N= 1
DOW HILE M < 9
D O W H IL E N < 7
IF M2 + 2 x N2 < 100
write M, N
ENDIF
N = N+ 1
ENDDO
M=M+1
ENDDO
END
130 ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS [CHAP. 5
5.45 read LA RG E
SMALL = LA RG E
D O K = 1 to 24
read A
IF LA RG E < A
LA RG E = A
ELSEIF A < SMALL
SMALL = A
EN D IF
N = N+1
ENDDO
write LARGE, SMALL
END
(Observe that we initialized both LA RGE and SMALL with the first number; hence the loop is cycled
only 24 times.)
[Observe that FIRST and SECOND were initialized with the first two numbers; hence the loop is cycled
only 23 times. The macroinstruction in the third line could be expanded as in Fig. 5-24(6).]
5.47 T=-5
MAX = 2 x T3 - T2 - 37 x T + 36
MIN = MAX
DOW HILE T < 5
Y = 2 x T3- T 2- 3 7 x T + 36
write T, Y
IF M A X < Y
MAX= Y
ELSEIF Y < MIN
MIN = Y
ENDIF
T = T + 0.25
EN D DO
write MIN, MAX
END
(Observe that we initialized MAX and MIN with the first value of y.)
CHAP. 5] ALGORITHMS, FLOWCHARTS, PSEUDOCODE PROGRAMS 131
5.49 (a) Seven times; for K= 1 , 4 , 7 , 1 0 , 1 3 , 1 6 , 1 9 . (b) Three times; for K = 4 , 6 , 8 . (c) Either once, for
K = 7 , or not at all, depending on the compiler. (d ) Three times; for K = 1 5 ,1 3 ,1 1 .