Understanding Algorithm Construction
Understanding Algorithm Construction
INTRODUCTION TO CONSTRUCTION OF
ALGORITHMS
An algorithm is correct when, for every input case, it stops with the output.
correct. An incorrect algorithm may not stop when it receives a given input case
entry or can stop presenting a result that is not correct.
There can be several functionally equivalent algorithms that solve the same
problem. Equivalent algorithms can use more or fewer resources, have a number
greater or fewer instructions and so on. Again, the analogy between
algorithm and culinary recipe is valid here: some recipes require less effort and
ingredients of what others that result in the same dish.
It is important to emphasize that not every problem has an algorithm. For example, not
There is an algorithm for the financial enrichment problem (legal or illegal). This
the problem does not have an algorithm because it is not even well defined, but there are problems
which are well defined but do not have complete algorithms, such as, for example,
play chess. It is interesting to note that problems that are solved trivially
by human beings, such as speaking a natural language or recognizing a face, neither do
they have algorithmic solutions. On the other hand, problems that are relatively difficult for
humans, like multiplying two numbers with ten digits each, have
relatively trivial algorithms.
The divide and conquer approach is not used specifically in the field of programming.
or computing. In other words, this problem-solving approach is generic and
frequently used even for everyday problems. Therefore, its use will be
exemplified below through the resolution of a non-computational problem.
Suppose you are having friends over for lunch and want to serve them a
delicious bedribs in coconut sauce. So, thealgorithm to be followed to solve this
the problem can be described as follows1:
1
The author thanks nutritionist and chef Suzana Brindeiro for the recipe and the secrets of
executions that are not revealed here.
Chapter 2 Introduction to Algorithm Construction 3
Output:
• Shrimp in coconut sauce
Since kitchen receptions are in fashion and your friends are close, you invite them.
to help you in the preparation of the dish. Now, suppose you assign task 1 to a
from his friends and that he does not know how to execute it (i.e., the task is not trivial for this)
friend). So, you will have to specify this task in more detail for him.
be able to execute it. In other words, you will have to refine task 1 into
subtasks in such a way that your friend knows how to execute each one of them. In
Chapter 2 Introduction to Algorithm Construction 4
Step 1 of the algorithm presented above can be refined to result in the following
sequence of substeps:
Note that step 1.3.2 presents two actions conditioned by the format of the onion (i.e., to
problem input) and only one of these actions should be executed. The
The conditions of step 1.3.2 are the facts that follow the two words and the actions come.
after the words then and not. Conditional actions are very common in programming.
High-level languages provide facilities for coding them.
Steps 1.3 and 1.3.5 presented above involve repetitive actions that have
analogous instructions in programming. For example, step 1.3.5 represents a
loop structure of the type: while a given condition is not met execute
repeatedly a certain action. In the given example, the stopping condition of the
2
A programmer with some experience does not need as much refinement.
Chapter 2 Introduction to Algorithm Construction 5
repetition is the fact that the onion is cut close to the stem and the action to be
repeated is the cutting of the onion.
All the other steps of the prep modethey canto be refined according to the
culinary intimacy of the one who will execute them3In the best case, the friend who will
executing one of the steps is an experienced chef and does not need further
details to execute the task. On the other hand, another friend who has never boiled water
requires that the task to be performed is well detailed. These facts correspond.
in programming: just like a chef, to create a program, a
an experienced programmer needs few details in the description of an algorithm,
while a beginner programmer needs to have a much more refined algorithm in
details.
Wisely, due to the proximity of the two recipes, you will not repeat the steps that are
common to them. That is, the best way to solve this new problem is to take advantage of
part of what was done in the previous problem. In this specific case, all the
ingredients and steps used in the preparation of shrimp sauce can be reused
in the creation of the new dish. Therefore, the two best alternatives for the cook are:
reduce the amount of shrimp or increase the amount of ingredients used in
coconut sauce, so that there is enough sauce for it to create the new recipe. In
In any case, the cook will be reusing part of the work that has already been done.
done and this has an analogous in programming that, unfortunately, is not properly
explored in teaching this subject: code reuse.
3
In fact, even obtaining the ingredients and equipment may require detailing. By
For example, the choices of shrimp and coconut type are critical in this recipe.
Chapter 2 Introduction to Algorithm Construction 6
An algorithm can be written in any language, just like in a natural language (e.g.,
Portuguese) or in a programming language (e.g., C). By the way, a program of
a computer consists exactly of an algorithm (or collection of algorithms) written
in a programming language. Pure natural language is rarely used in writing
of algorithms as it presents inherent problems, such as verbosity, imprecision,
ambiguity and context dependency. The use of a programming language of
high level is also not convenient for writing an algorithm, because the programmer
You need to divide your attention between this task and details about language constructions.
in which the algorithm will be written.
The objective here is the writing of algorithms that, ultimately, can become
programs. However, writing algorithms in a programming language imposes serious
difficulties for those who have not yet gained practice in algorithm construction
they do not know the programming language used well. Thus, when trying to write
an algorithm in a programming language, the learner would be involved in two
simultaneous tasks: the resolution of the issue at hand (i.e., the construction of
algorithm itself) and the use of a language that he still does not master. An idea that
facilitates the programmer's life consists of using in the construction of algorithms a
language close to the programmer's natural language, but that incorporates
similar constructions to those commonly found in languages
programming. A language withthese characteristicsis called language
algorithm or pseudolanguage4In order to serve the purpose for which it is intended, a
algorithmic language still needs to be much easier to use than any
programming language.
4
An alternative resource for the use of pseudocode is flowcharts. This alternative already
It was widely used but is now out of use and will not be studied here.
Chapter 2 Introduction to Algorithm Construction 7
write(x)
printf("%d", x);
The next sections of this chapter describe an algorithmic language that takes into
considering what was presented in this section. The learner should note that not
it is necessary to strictly follow the specifications of this language, as it was
As exposed above, it is an artificial language that aims to assist you in
writing algorithms and the subsequent translation of the algorithm using a language of
programming. For example, you can, if you wish, replace the output statement:
write(x)
by
print(x)
5
Note how it would be much more complicated for the programmer if he had to write the
algorithm in C from the beginning of the development process. In this example, the instruction
write(x)it's much simpler thanprintf("%d", x).
Chapter 2 Introduction to Algorithm Construction 8
Note that, as illustrated in Figure 1, when a variable occupies more than one cell
In memory, its address corresponds to the address of the first cell.
y+5
Chapter 2 Introduction to Algorithm Construction 9
x+y*2
the operands of the operator '+' are the variablexand the expressiony * 2In Section 2.5,
Expressions and operators will be explored in greater detail.
x← y + 2
This assignment instruction reads as: x receives the value of y plus two.
x←x+2
In this case, the variablexreceives the value that she had before6of the assignment to occur
added to2.
6
This occurs because, in an assignment in which a variable receives the resulting value from the
evaluation of an expression, the expression must be evaluated before the assignment happens.
Chapter 2 Introduction to Algorithm Construction 10
When the type of a variable is not easily inferred from the context, it is advisable
include your declaration at the beginning of the algorithm where the variable is used. Declare
variables in an algorithm are also advantageous for translating the algorithm into a program
because it prevents the programmer from forgetting to do it.
Examples:
boolean b
whole x
real y, z
Note that when two or more variables are of the same type, like the variablesy
ez from the previous example, they can be declared in a summarized way by separating them by
commas and preceding them with the name of the common type.
Before exploring in detail the three types of expression mentioned above, there will be
described properties that are common to all operators.
Aridity
The arity of an operator is the number of operands that the operator accepts.
In algorithmic language, operators are divided into two categories of arity:
For example, the addition operator is a binary operator (i.e., it has arity two).
Result
Any operator, when applied to its operands, results in a value. This value is the
result of the operator. For example, the result of the addition operator is the value obtained
when its two operands are added.
Precedence
Operators are grouped into precedence groups, so that, within each group
of precedence, the operators have the same precedence. On the other hand, operators that
belong to different precedence groups have different precedences. For
For example, the addition and subtraction operators are part of the same group of
precedence and the same occurs with the multiplication and division operators. But, the
the precedence group that includes multiplication and division has higher precedence than
that the precedence group of addition and subtraction. Thus, in the expression:
2*5 + 4
the multiplication operator (“*”) is applied before the addition operator (“+”).
Chapter 2 Introduction to Algorithm Construction 12
Associativity
• Left associativity - the left operator is applied before the right one.
right operator.
• Right associativity - the right operator is applied before the operator
from the left.
For example, in the expression8/2/2the first division operator is applied before the
second, because the division operator is left associative. In this case, the
the result of the expression is2(If the division operator had right associativity, the
result would be8.)
OPERATOR meaning
- unary minus (i.e., sign inversion)
+ soma
- subtraction
* multiplication
/ integer division
Chapter 2 Introduction to Algorithm Construction 13
The operands of any arithmetic operator must be numeric. There are two types.
basics of numbers in programming: integers and floating point. The latter
correspond approximately to real numbers in mathematics. Except for the
operator "%", whose operands must always be integers, the operands of any
Other arithmetic operators can be integers or floating point. When the
If the operands of an arithmetic operator are of the same type, the result will be of this type.
same type. If one of the operands is floating point, the result will also be of this type.
type. For example:
Expression Result
2.5 + 4 6.5
6.5 6.5
2+4 6
5%2 1
5/2 2
2.5 2.5
In the above table, operators on the same line have the same precedence. Therefore,
when such operators are found together in the same arithmetic expression, the
the leftmost operator is applied first, except in the case of the inversion operator
of signal that has right associativity.
Note that the use of parentheses changes the properties of precedence and associativity
two operators. For example, in the expression(2 + 3)*4the parentheses make it so that the
the addition operation should be applied before multiplication (i.e., the precedence of addition
becomes greater than the precedence of multiplication). Another example:8/(2/2)
results in8because parentheses increase the precedence of the second operator
division.
Note that a relational expression corresponds to a question whose answer is yes or no.
no. When the answer to this question is yes, the result of the expression istrue;
when the answer to this question is no, the result of the expression isfalse. For
7
Evidently, the result of a relational operator is false when it is not true.
Chapter 2 Introduction to Algorithm Construction 15
example2 is greater than 3corresponds to the question: Is two greater than three? whose answer is
obviously not, therefore, the expression2 > 3results infalse.
2.5 = 5.0/2.0
it may be that you obtainfalseas a result. This occurs because the division5.0/2.0
can result in something like2.499999999999999or maybe,2.500000000000001,
and not exactly in2.5, as would be intuitively expected.
A logical variable (or boolean variable) is a variable that can assume only
a logical value. A boolean variable can be directly assigned a constant
logic or the resulting value from the evaluation of a Boolean expression, as shown by the
examples to follow.
bol1← false
bol2← 2 > 3
Chapter 2 Introduction to Algorithm Construction 16
Constants, variables, and boolean expressions can be combined with each other through
logical operators. There are three most commonly used logical operators in
programming
The possible results of the applications of these operators are typically presented
in tables calledtruth tablesThe truth tables for the operators not,
the presentations are shown below8.
Operator1 noOperating1
true false
false true
The following conclusions can be derived from the observations of the truth tables above:
8
In these tables,operando1eoperating2they can correspond to any constant, variable
the boolean expression.
Chapter 2 Introduction to Algorithm Construction 17
Example:
bol1← 2 = 5
bol2← false
bol3← 10≤ 10
bol4← nãobol1
bol5← bol2ebol3
bol6← bol2oubol3
Exercise: What are the values assumed by logical variablesbol1, bol2, bol3,
bol4, bol5ebol6from the last example?
OPERATOR PRECEDENCE
(unary)no High (applied first)
*, /,% ↓
+, - (binary) ↓
relational operators (=,≠, ≥, etc.) ↓
Chapter 2 Introduction to Algorithm Construction 18
e ↓
or Low (last applied)
Exercise: If the value of the variablex for5at the moment of evaluating the expression
(2 + 4 < 7) and not (x = 10), the result of this expression will be true.
Show, step by step, how this result is obtained.
2.5.5 Functions
When a function appears in an expression, its execution has a higher priority than that of
that the application of any operator presented above. When there is an occurrence of more
from a function in an expression, functions are evaluated from left to right.
bol1oubol2ebol3oubol4
(bol1orbol2)e(bol3orbol4)
Chapter 2 Introduction to Algorithm Construction 19
you have to write it exactly as in the previous line (i.e., with the parentheses);
otherwise, the original expression would be interpreted as:
bol1ou(bol2ebol3)oubol4
given that the operator has higher precedence than the precedence of the operatoryou9.
indicates how many data will be read and then stored as the contents of the variablesx1,
x,2 ..., x n.
An instruction for outputting data from an algorithm to some output medium (by
example, screen, printer) has the following format in algorithmic language:
9
Be careful with logical expressions, as they represent a very common source of error.
in programming (even for experienced programmers!).
Chapter 2 Introduction to Algorithm Construction 20
In this instruction,e1, e2, ..., en they represent the information that will be written in the middle of
output and eacheiit can be:
The execution flow of an algorithm consists of the sequence and the frequency (i.e.,
number of times) that the algorithm instructions are executed. In the natural flow
execution of an algorithm, each instruction is executed exactly once and in the
order in which it appears in the algorithm.
Control structures are instructions that allow the programmer to change the flow.
natural execution of an algorithm. They are divided into three categories:
conditional and two repetition instructions used by the algorithmic language. Deviations
Unconditional ones will be presented later.
Where:
Example:
read(x)
if (x < 0) then
The number is negative
otherwise
The number is not negative.
select (whole-expression)
constant case1
instructions1
constant case2
instructions2
...
constant caseN
instructionsN
standard
instructionsp
The expression in parentheses that immediately follows the selected word must result in
in an integer value. When the resulting value from evaluating this expression coincides with
the value of one of the constants that accompany the words case, the instructions
corresponding to the respective constant are executed.
Example:
select (op)
case 1
You chose option 1
case 2
You chose option 2
case 3
You chose option 3
case 4
You chose option 4
case 5
You chose option 5
pattern
You did not choose a valid option
Chapter 2 Introduction to Algorithm Construction 23
Where:
Example 1:
read(x)
Exercise: What would happen if the body of the loop in this example werex← x - 1and the
if the read value was less than 10?
Example 2:
soma← 0
cont← 1
Exercise: What does the algorithm from the last example write?
Example:
read(x)
do it
x← x + 1
while (x < 10)
Compare this last example with the first example in Section 2.7.2. Note that the
the only difference between them is that that example uses the loopwhile-makeand this
example uses the loopmake-whileNow, assuming that the value read and stored
in the variablexmine12in both cases, the body of the loopdo-whilewould not be
executed none time and the body of the noosewhile-do itwould be executed exactly
once.
The instructionstopis
used to terminate loops, causing the flow of
execution should be diverted to the next instruction following the respective loop
repetition. For example, the following algorithm calculates the sum of numerical values
introduced by a user until he enters the value zero:
Chapter 2 Introduction to Algorithm Construction 25
soma← 0
while (true) do
read(x)
if (x = 0) then
stop
soma← soma + x
x←1
Bye, bye
Exercise: How many blocks are there in the last example and what are the instructions that
What is part of each block?
Chapter 2 Introduction to Algorithm Construction 26
10
Keywords are often written in bold in textbooks and other materials.
printed, but this resource is not available, or at least is not very practical, in
handwritten algorithms.
Chapter 2 Introduction to Algorithm Construction 27
secondition then
instructions
otherwise
instructions
second sight
so
instructions
otherwise
instructions
5*3+4
is better than:
5*3+4
Chapter 2 Introduction to Algorithm Construction 28
you:
5*3+4
• Never write more than one instruction per line. That is, even if
you have a sufficiently small set of instructions for
fitting on one line, don't do it because it will harm readability of the
algorithm.
like this:
11
This is just a verification trick. Obviously, these lines should not be part of it.
of the algorithm.
12
Suppose that the instruction from the example is actually much longer.
Chapter 2 Introduction to Algorithm Construction 29
The first three steps will be explored in depth below, while the
the others will be studied in Chapter 3.
Before proceeding, it is important to emphasize that the machine only does what you are.
capable of teaching her. Thus, the main premise of programming can be stated
like:
Therefore, when writing an algorithm, try to think about how the computer will execute it.
that is, without making any inference, conjecture or assumption, as the computer does not
has this ability.
At this stage, the problem statement must be analyzed word by word until the
input and output data can be properly identified. Once this is done, an attempt is made
describe a procedure in Portuguese that shows how to obtain the result
desired (output) using the available data (input). The table below summarizes this
stage.
1. Read and reflect carefully on the problem, and answer the following questions:
Chapter 2 Introduction to Algorithm Construction 30
1.1 What initial problem data will be available (input)? Write the
response to this question preceded by the word Entry.
What is the expected result (output)? Write the answer preceded by
Exit.
1.3 What type of processing (algorithm) is necessary to obtain the result
expected from the input data? Write an algorithm that does this.
Don't worry for now about whether the algorithm is well detailed.
You can even write it in Portuguese, instead of using the language
algorithmic.
The answers to questions 1.1 and 1.2 are necessary to identify the input data and
program output. When answering these questions, use meaningful names (not
necessarily in Portuguese) to represent input and output data (e.g.,
studentRegistration). Make sure these answers are very accurate before
proceed to step 1.3.
In stage 1.3, you must find a connection between the input data and the result.
desired that allows determining which are the steps of the algorithm that lead to the
result. The following are presented somethe recommendations for being successful in
writing of this algorithm outline13:
• Build a predicted example of the program execution result and use it.
until the end of the development process. An example of execution is
useful not only in the phase of building the algorithm but also serves
as a test case of the algorithm itself and the program that will result from it
end of the process.
• Draw diagrams that assist your reasoning. In particular, use
rectangles to represent variables and track the changes of their
contents represented by the interiors of the rectangles, as shown
several examples presented in the book.
• Try to recognize something that is familiar. That is, try to find a
problem that presents similar output and involves principles
similar. Use analogy and try to find a simpler problem that
be similar to the one in question. That is, if you cannot solve the
proposed problem, try to solve a similar problem first that is
considered easier. Solving a simpler analogous problem may
provide clues for solving a more complex problem.
13
Some of the suggestions presented below were adapted from the book How to Solve It
mathematician George Pólya (see Bibliography).
Chapter 2 Introduction to Algorithm Construction 31
Suppose, for example, that your algorithm aims to solve second degree equations.
gray (i.e.,ax2bx + c = 0So, at this stage of building the algorithm you
you should obtain the following:
Algorithm:
1. Read the values of the coefficients and store them in the variables a, b, c.
If the coefficients do not constitute a quadratic equation, report.
the fact is closed.
3. Calculate the discriminant (∆) of the equation.
If the value of the discriminant is less than zero, inform that there are none
real roots and conclude.
5. Calculate the values of the roots and present the result.
Example 1:
Example 2:
Example 3:
Example 4:
Despite the relative simplicity of the problem exemplified above, it is unlikely that a
beginner programmer can succeed in this stage on the first attempt. In
algorithm in question, the most common mistake among beginners is to assume that the only output of
algorithm is the roots of the equation. In other words, beginners often forget
what may be is that there are no roots or that the coefficients read do not even constitute
a second-degree equation. Therefore, it is important that there is a deep reflection
about the problem in order to accurately determine what the input data is and
output of an algorithm before proceeding with its writing. It is impossible for a
The algorithm is correctly written when its inputs and outputs are not well defined.
specified.
2. Break down each step of the algorithm outlined in Step 1.3 that does not have
trivial solution.
At this stage, the initial algorithm for solving second-degree equations would be
refined as:
read
if (a = 0) then
The value of a cannot be zero
if not
read(b, c)
if (delta < 0)
There are no real roots
otherwise
(-b + sqrt(delta)) / (2 * a)
x2 = (-b - sqrt(delta))/(2*a)
Chapter 2 Introduction to Algorithm Construction 33
Notes:
• Note that the variabledeltathe algorithm above does not represent either
neither input nor output of the algorithm; i.e., it is used as an auxiliary variable
in processing.
• The algorithm presented above is not the only solution to the problem.
Normally, there are many functionally equivalent algorithms
that solve a certain problem. Perhaps not all of these
algorithms may be equivalent in terms of efficiency, but,
meanwhile, don't worry about this aspect.
• Do not expect to quickly achieve a refinement like the one presented.
above. That is, you may need to make several refinements
intermediaries before obtaining a satisfactory algorithm. As an exercise,
refine the algorithm outline presented in Section 2.9.1 and try to obtain
an equivalent algorithm to the one presented above. The result that you
it does not have to be the same as the last algorithm presented, but it should
be functionally equivalent to it.
Note also that if you need to return to Step 1, as recommended above, do not
you need to undo everything you have done so far. Maybe you just forgot to take
considering some input data (Step 1.1), or one of the steps of the algorithm
preliminary (Stage 1.3) or its refinement (Stage 2) may be inadequate.
Chapter 2 Introduction to Algorithm Construction 34
To test an algorithm, you must act as both the computer and the user.
That is, you should perform the algorithm manually as if you were the computer and
You should also provide input data for the algorithm, as if you were a user.
For example, consider the algorithm for solving quadratic equations.
presented above. The first step of this algorithm is the instruction:
Leia
During the tests, you will need to input a value for the variable.a, exercising, thus,
the role of the user, and read the respective value, acting as a computer. Suppose
that you introduce (as a user) and read (as a computer) the value zero. Then, after the
manual execution of this instruction the value of the variablea becomes zero.
if (a = 0) then
The value of a cannot be zero.
Like the value of the variableaat this moment of the execution of the algorithm is zero, according to
with the interpretation of the if-then-else instruction, the instruction:
After writing this sentence, the algorithm ends because the mentioned part is not.
instructions-then-not-executed and there are no more instructions that
can be executed in the algorithm. Now, observing the first expected example of
execution, this was really the expected result of the algorithm. Therefore, the algorithm is
approved in the input case test when the coefficienta is equal to zero.
2.9.4 Implementation
executable program and subsequent tests. In reality, these steps can only be
considered as last if the resulting program is absolutely correct, what
it rarely occurs. The most common is that it contains flaws and, consequently, is
it is necessary to repeat the construction process from one of the previous stages.
int main(void)
{
/* >>> The translation of the algorithm begins below <<< */
x1, x2 );
}
}
Example 1:
Example 2:
Example 3:
Example 4:
Even if you have not yet been formally introduced to the C language, read the
program and try to find some correspondence between it and the presented algorithm
in Section 2.9.2.
Chapter 2 Introduction to Algorithm Construction 37
Problem: Write an algorithm that reads values for two variables and swaps their values.
It shows them before and after the exchange. In other words, if the variables arex e y, at the end
x will have the initial value ofy, andy will have the initial value ofx.
Solution:
Input: x, y
Output: x, y
Preliminary Algorithm:
1. Read the values of x and y
2. Write the values of x and y
3. Store the value of x in a temporary variable
4. Assign the value of y to x
5. Assign the value of the auxiliary variable to y
6. Write the values of x and y
Refined Algorithm:
read(x, y)
write("Values of x and y before the swap", x, y)
Power Table
Problem: Write an algorithm that calculates and presents a table presenting the
first 100 powers of 2 (i.e., 2 ). (Yourn algorithm should not contain 100 instructions)
write!)
Solution:
entry: none
Chapter 2 Introduction to Algorithm Construction 38
Output:
01
12
24
...
100 299
Preliminary Algorithm:
1. Start the exponent with 1
2. Start the power with 1
3. Write 0 and 1
4. While the exponent is less than 100 do
4.1 Assign to the power its current value multiplied by 2
4.2 Write the value of the exponent followed by the power
4.3 Assign to the exponent its current value plus 1
Refined Algorithm:
exponent← 1
power← 1
Problem: Write an algorithm that calculates and writes the sum of a set of
values. The algorithm must terminate when a zero value is read.
Solution:
Preliminary Algorithm:
Read the first value
2. Assign the first value to the variable that will accumulate the sum
3. While the read value is different from zero do the following
3.1 Read a value
Chapter 2 Introduction to Algorithm Construction 39
3.2 Assign to the variable sum its current value added to the value
pool
4. Write the sum of the values read
Refined Algorithm:
read(value)
soma← value
write(sum)
Fibonacci Sequence
Write an algorithm that generates the Fibonacci sequence up to the n-th term.
Solution:
Preliminary Algorithm:
1. Read the number of terms in the sequence
2. If the number of terms entered is less than two,
report that the sequence does not exist and close.
3. Write the first two terms of the sequence
4. Generate and present the terms of the sequence starting from the third
term up to the n-th.
4.1 While the n-th term is not generated and written do:
4.1.1 Calculate the current term as the sum of the two.
previous terms
Chapter 2 Introduction to Algorithm Construction 40
Refined Algorithm:
integer nTerms, antecedent1, antecedent2, current, i
read (terms)
I← 3
of what 2
} else {
/* Initializes the first two terms of the series */
antecedente1 = 1;
antecedent2 = 1;
1, 1, 2, 3, 5
Again, even if you don't know the C language yet, read the program and try.
find some correspondence between the algorithm presented earlier and this program.
What is an algorithm?
Chapter 2 Introduction to Algorithm Construction 42
2. (a) In what aspects is the concept of algorithm analogous to the concept of a recipe?
cuisine? (b) When does this analogy cease to be valid?
7. Describe the divide and conquer approach used in the construction of algorithms.
10. (a) O que é linguagem algorítmica? (b) Por que linguagem algorítmica também é
called pseudolanguage?
What is pseudocode?
for algorithms written in pseudocode?
22. (a) Para que servem os operadores relacionais? (b) Quais são os operadores
relational?
23. What are the possible values resulting from the evaluation of a relational expression?
27. Write the truth table corresponding to the boolean expression:A or B and C, where
A, BandCare logical variables. (Remember that the operatorandhas precedence
greater than the operatoryou.)
(d)L1 or not L2
(e)(A > B) and L1
(f)(L1 or L2) and (A < B + C)
34. (a) O que é fluxo de execução de um algoritmo? (b) Como é o fluxo natural de
execution of an algorithm?
38. What is the difference between the while-do and do-while instructions in terms of
functioning?
39. (a) O que bloco? (b) O que é endentação? (c) Qual é a relação entre bloco e
indentation in pseudocode?
40. Consider the following algorithm, wherei1, i2, i3, i4ei5represent instructions:
if b1 then i1
otherwise
if b2 then
so b3 then
i2
Chapter 2 Introduction to Algorithm Construction 45
otherwise
i3
i4
i5
41. What will be the value of the variableresultafter the execution of the following algorithm?
b1← false
b2← true
b3← false
x← 1.5
y← 3.5
x← x + 1
Two instructions are functionally equivalent if they produce the same effect.
under any circumstances. Check if instructions 1 and 2 below are
functionally equivalent:
Instruction 1:L← X = Y
Instruction 2:if X = Y
so L← true
otherwise L← false;
Chapter 2 Introduction to Algorithm Construction 46
43. Cite five recommended practices in building algorithms that favor the
readability.
46. (a) O que é endentação coerente? (b) Por que é aconselhável usar endentação
coherently in the construction of algorithms?
48. How should a problem for which an algorithmic solution is desired be analyzed?
49. (a) Como um algoritmo deve ser testado? (b) Como um programa deve ser testado?
50. Why, even if an algorithm has been tested and deemed correct, is it
Is it necessary to test a program derived from it?
52. Why is the final stage of building a program not always the last?
2.12.1 Easy
EP2.1) Write an algorithm that takes the radius of a circle as input and calculates its
2
area and displays the result. Given: area of a circle =πr , where r is the radius of the circle.
2
Tip: to obtain r , simply calculate r*r.
EP2.3) Write an algorithm that reads three integer values that will be stored in the
variables x, y, and z. Then, the algorithm calculates and displays the sum and the product of these values.
EP2.4) Write an algorithm that takes two numbers as input and displays the smaller one.
themselves. If the numbers are equal, there will be no difference as to which one will be
presented.
EP2.5) Write a slightly different algorithm from that of the previous exercise that
The numbers are equal.
equal forms.
EP2.6) Write an algorithm that reads three integers and informs which one is the largest.
2.12.2 Moderate
EP2.7) Write an algorithm that repeatedly reads real values that represent radii.
of circles. For each read value, the algorithm calculates the area of the respective circle and displays it.
the result. The algorithm should terminate when a value of zero is read.
EP2.8) Write an algorithm that reads an indefinite number of values and displays the
the least of them. The entry of values ends when zero is read. [Suggestion: Use a
variable to store the smallest value read. Initially, assign this variable the
first value. Then, for each value read, compare it with the value of the variable that should be
count the smallest. If a new value read is less than the one currently
stored in this variable, assign this value to the variable.
EP2.9) Write an algorithm that calculates and presents the factorial of a given number
non-negative integer. The factorial of an integer n≥ 0 is given by:
1, if n = 0
n * (n - 1) * (n - 2) * ... * 2 * 1, if n > 0
Chapter 2 Introduction to Algorithm Construction 48