2 Problem Solving
2 Problem Solving
Chapter 2
The world of problem solving
Narasimhan T.
2.1 Introduction
In today’s world, the computer is an invaluable tool to every engineer and scientist for
solving problems related to his or her discipline. But what is a problem? Problem is any
task at our hand that we wish to accomplish. The problems may be as unimportant as
what to watch on television or as important as choosing a new profession. If a bad decision
is made, time and resources are wasted, so it’s important that people know how to make
decisions well.
1. Identify the problem: The first step toward solving a problem is to identify the
problem. The task to be done is identified.
2. Understand the problem: Once a problem has been identified, its exact nature
needs to be determined. We must understand what is involved in the problem before
we can continue towards the solution. In order to effectively solve a problem, you need
to know as much about it as possible. When tackling a new problem, it is important
to talk to anyone who might be familiar with the problem. Several techniques can
be used to gather information about a problem. Some of these include conducting
interviews, sending questionnaires to employees or other people concerned with the
problem. Structuring a big problem into simple manageable ones help in developing
a clear picture of the problem.
13
14 CHAPTER 2. THE WORLD OF PROBLEM SOLVING
3. Identify the possible ways to solve the problem: Generating possibilities for
solutions to the defined problem comes next in the process. It is important to generate
as many solutions as possible before analyzing the solutions or trying to implement
them. There are many different methods for generating solutions. Brainstorming is
one of the most commonly used techniques for generating a large number of ideas in
a short period of time. Brainwriting and Mind Mapping are two additional tools to
generate ideas.
4. Select the best way to solve the problem from the list of solutions: Once
a list of possible solutions is determined, the next step is to identify the best among
them. This decision making can be done using intuition based approach or through a
reasoning approach. In the intuition based approach, we go with our mind’s feelings
to take a decision. Intuition is actually a combination of past experience and your
personal values. Reasoning is using the facts and figures to make decisions. We need
to identify and evaluate the pros and cons of each possible solution before selecting
the best one.
5. Implementation: Once the best solution has been determined, we need to implement
it by writing instructions/programs. Program means the set of instructions that make
up the solution after they have been coded into a particular computer language. The
instructions should be as simple as possible.
6. Evaluate the solution: In the final step, the implemented solution is evaluated.
To evaluate a solution means to check its result to see if it is correct. If the result
is either incorrect or unsatisfactory, then the problem solver must review the list of
instructions to see that they are correct or start the process all over again. The
evaluation of our implementation must be based on whether or not our goals are met.
This can be achieved by monitoring and gaining feedback from people affected by
any changes that occurred. It is good practice to keep a record of outcomes and any
additional problems that occurred.
S1
True False False
C C
S2
True
B1 B2
B
S3
In the sequence structure, all the instructions in the pseudocode are executed once
without skipping any statements. On the other hand, with selction structure and loop
structure, it is possible to skip certain instructions or repeatedly execute certain instructions.
In such structures, the statements to be executed will be selected based on the outcome of
testing a condition. For writing such conditions, we use special symbols called relational
operators. The various relational operators are listed in the following table:
Operator Meaning
> greater than
< less than
== equal to
>= greater than or equal to
<= less than or equal to
!= not equal to
2.3. ALGORITHMS AND PSEUDOCODES 17
It is also possible to link two or more conditions using logical operators like “AND”, “OR”.
Eg:- a > b AND a > c.
2.3.1.1 Sequence
This is the most elementary construct where the instructions of the algorithm are executed
in the order listed. It is the logical equivalent of a straight line. Consider Figure 2.1.
Statement S1 is executed first which is then followed by statement S2 and so on till all
the instructions are executed. No instruction is left unprocessed and every instruction is
executed only once.
A The if structure
There are three variations of the if-structure:
if condition
true_instructions
endif
If the test condition is met, the statements denoted by true_instructions are executed. If
the test condition is not met the statements arc skipped.
Example 2.1. The following pseudocode checks if an input value x is positive.
1 if x > 0
2 Print(x,“is positive”)
3 endif
if condition
true_instructions
else
f alse_instructions
endif
18 CHAPTER 2. THE WORLD OF PROBLEM SOLVING
This structure contains two blocks of statements. If the test condition is met, the first
block (denoted by true_instructions) is executed and the algorithm skips over the second
block (denoted by f alse_instructions). If the test condition is not met, the first block of
statements is skipped and the second block is executed.
1 if age > 0
2 Print(“You are a major”)
3 else
4 Print(“You are a minor”)
5 endif
if condition1
true_instructions1
else if condition2
true_instructions2
else
f alse_instructions
endif
Example 2.3. The following code compares two variables and prints the relation between
them.
1 if x > y
2 Print(x,“is greater than”,y)
3 else if x < y
4 Print(y,“is greater than”,x)
5 else
6 Print(“The two values are equal”)
7 endif
There is no limit of the number of else if statements, but the last branch has to be
an else statement. The conditions are evaluated from the top downward. As soon as a
true condition is found, the statements associated with it are executed and the rest of the
structure is bypassed. If none of the conditions are true, the final else part is executed.
That is, if all other conditional tests fail, then the block f alse_instructions is executed.
2.3. ALGORITHMS AND PSEUDOCODES 19
caseof expression
case value1 :
block1
case value2 :
block2
..
.
default :
def ault_block
endcase
The case structure is made up of several blocks of instructions, usually only one of which
will be selected and then executed based on the value of expression. The value of expression
is compared with value1 . If there is a match, the first block of statements denoted as block1
will be executed and the structure is exited. If there is no match, the value of expression
is compared with value2 . If there is a match here, block2 is executed and the structure
is exited. This process continues until either a match for the expression value is found or
until the end of the cases is encountered. The def ault_block will be executed when the
expression does not match any of the cases.
Example 2.4. The following pseudocode prints a color name based on the value of a
character called code.
1 caseof dir
2 case ‘N’:
3 Print(“North”)
4 case ‘S’:
5 Print(“South”)
6 case ‘E’:
7 Print(“East”)
8 case ‘W’:
9 Print(“West”)
10 default :
11 Print(“Invalid direction code”)
12 endcase
as the condition evaluates to True. Finally when the condition becomes False, the block
B is skipped and thus the loop is exited.
Each execution of the block is called an iteration or a pass. If the number of iterations
(how many times the block is to be executed) is known in advance, it is called definite
iteration. Otherwise it is called indefinite or conditional iteration. The block which is
repeatedly executed is called loop body. There are three types of loop constructs as discussed
below:
while condition
true_instructions
endwhile
Here the loop body (true_instructions) is executed continuously as long as condition
evaluates to True. When the condition evaluates to False, the loop is not entered (loop
body is bypassed).
repeat
f alse_instructions
until condition
There are two major differences between the while and repeat-until loop constructs.
First, in the while loop, the pseudocode continues to loop as long as the resultant of the
condition is True; in the repeat-until loop, the looping process stops when the resultant of
the condition is True. Second, in the while loop, the condition is tested at the beginning;
in the repeat-until loop, the condition is tested at the end. for this reason, the whileloop
is known as entry controlled loop and the repeat-until loop is known as exit controlled loop.
Note that when the condition is tested at the end, the instructions in the loop are executed
at least once.
(a) (b)
(c)
In the first variant (part (a) of Figure 2.2), the loop variable is incremented (increased by
1) after each iteration and the loop execution stops when the counter value becomes greater
than EndValue. In the second variant, whose pseudocode syntax is given in part (b) of
Figure 2.2, the loop variable is decremented (decreased by 1). Here BeginValue should be
greater than or equal to EndValue and the loop exits when this condition is violated. It is
also possible to update the loop variable by an amount other than 1. The value by which
the loop variable is increased or decreased is known as StepValue. In part (c) of Figure 2.2,
the StepValue is specified using the keyword by . Table 2.1 lists some examples of for loop.
In the examples, var is the loop variable.
2.4 Flowcharts
A flowchart is a graphic/visual representation of an algorithm and shows the flow of pro-
cessing from beginning to end of a solution. Flowcharts are composed of various blocks
interconnected by flowlines. Each block in a flowchart represents one instruction from the
algorithm. Flowlines indicate the direction of data flow (order in which the algorithm steps
are executed).
Different types of blocks are defined to represent the various programming constructs
of algorithm (pseudocode). Most blocks have one or more entrances, flowlines directing the
flow of the data into the block. Most blocks have only one exit, flowlines directing the data
out of the block, since, in most cases, data can flow to only one other block. The exceptions
to this rule are the blocks representing decision or loop structures. Such blocks could have
multiple exits, one for each possibile outcome of the condition being tested and each such
outcome is called a branch.
Each programming construct has its own symbolic representation in a flowchart. Ta-
ble 2.2 lists some commonly used flowchart symbols and their descriptions.
The diamond indicates a decision. It has one entrance and only two
exits from the block. One exit is the action when the tested condition is
True and the other exit is the action when the condition is False.
Rectangles with lines down each side indicate the process of modules.
Start
SimpleInterest
1 Start
2 Read(principal , rate, years) Read(principal , rate, years)
3 SI = (principal ∗ rate ∗ years)/100
4 Print(SI ) SI = (principal ∗ rate ∗ years)/100
5 Stop.
Print SI
Stop
Start
LargerTwo
1 Start Read(a, b)
2 Read(a, b)
3 if a > b
4 large = a False
a > b?
True
5 else
6 large = b
large = b large = a
7 endif
8 Print(large)
9 Stop.
Print(large)
Stop
Start
SmallestThree
1 Start
Read(a, b, c)
2 Read(a, b, c)
3 if a < b
4 small = a False True
a < b?
5 else
6 small = b
7 endif small = b small = a
8 if c < small
9 small = c
10 endif
11 Print(small )
12 Stop.
True
c < small ?
small = c
False
Print(small )
Stop
Problem 2.4 To determine the entry-ticket fare in a zoo based on age as follows:
Age Fare
< 10 7
>= 10 and < 60 10
>= 60 5
Start
TicketFare
1 Start Read(age)
2 Read(age)
3 if age < 10
4 fare = 7 False True
5 else if age >= 10 AND age < 60 age < 10?
6 fare = 10
7 else fare = 7
False True
8 fare = 5 age < 60?
9 endif
10 Print(fare)
fare = 5 fare = 10
11 Stop
Print(fare)
Stop
Grade Message
R Red
G Green
B Blue
Any other value Wrong code
Start
PrintColour
1 Start
Read(code)
2 Read(code)
3 caseof code
4 case ‘R’:
5 Print(“Red”) caseof
6 case ‘G’: code
7 Print(“Green”)
8 case ‘B’:
‘R’ ‘G’ ‘B’ default
9 Print(“Blue”)
10 default : Print(“Red”) Print(“Green”)
11 Print(“Wrong code”) Print(“Blue”) Print(“Wrong code”)
12 endcase
13 Stop
Stop
Start
PrintDown
1 Start
2 for count = 50 downto 1 count
50 1
3 Print(count) -1
4 endfor
5 Stop
Print(count)
count
Stop
Start
PrintMult5
1 Start count
2 for count = 10 to 99 by 5 10 99
5
3 Print(count)
4 endfor Print(count)
5 Stop
count
Stop
Start
SumN
1 Start
Read(n)
2 Read(n)
3 sum = 0
4 for count = 1 to n sum = 0
5 Read(num)
6 sum = sum + num count
7 endfor 1 n
1
8 Print(sum)
9 Stop
Read(num)
count
Print(sum)
Stop
Factorial Start
1 Start
2 Read(n)
3 fact = 1 Read(n)
4 for var = n downto 1
5 fact = fact ∗ var
6 endfor fact = 1
7 Print(fact)
8 Stop
var
n 1
-1
var
Print(fact)
Stop
Start
LargeN
1 Start
Read(n, num)
2 Read(n, num)
3 large = num
4 for count = 1 to n − 1 large = num
5 Read(num)
6 if num > large count
7 large = num 1 n−1
1
8 endif
9 endfor Read(num)
10 Print(large)
11 Stop
True
num > large?
large = num
False
count
Print(large)
Stop
Problem 2.11 To determine the average age of students in a class. The user will stop
giving the input by giving the age as 0.
Start
AverageAgev1
1 Start sum = 0
2 sum = 0 count = 0
3 count = 0
4 Read(age) Read(age)
5 while age!=0
6 sum = sum + age
7 count = count + 1 while False
8 Read(age) age!=0
9 endwhile
10 average = sum/count
11 Print(average) True
avg = sum/count
12 Stop
sum = sum + age
count = count + 1 Print(average)
Stop
Start
AverageAgev2
1 Start sum = 0
2 sum = 0 count = 0
3 count = 0
4 Read(age) Read(age)
5 repeat repeat
6 sum = sum + age sum = sum + age
7 count = count + 1 count = count + 1
8 Read(age)
9 until age == 0 Read(age)
10 average = sum/count
11 Print(average)
False
12 Stop
until
age == 0
True
average = sum/count
Print(average)
Stop
Figure 2.14: To determine the average age using repeat until loop
2.4. FLOWCHARTS 31
Problem 2.13 To find the average height of boys and average height of girls in a class of
n students.
Solution: See Figure 2.15.
Start
AverageHeight
1 Start Read(n)
2 Read(n)
3 btotal = 0
4 bcount = 0 bcount = 0
gcount = 0
5 gtotal = 0 btotal = 0
6 gcount = 0 gtotal = 0
7 for var = 1 to n
8 Read(gender , height) var
9 if gender == ‘M ’ 1 n
1
10 btotal = btotal + height
11 bcount = bcount + 1
12 else Read(gender , height)
13 gtotal = gtotal + height
14 gcount = gcount + 1
15 endif
16 endfor False True
17 bavg = btotal /bcount gender == ‘M ’?
18 gavg = gtotal /gcount
19 Print(bavg, gavg)
20 Stop gtotal = gtotal + height btotal = btotal + height
gcount = gcount + 1 bcount = bcount + 1
var
Print(gavg, bavg)
Stop