0% found this document useful (0 votes)
27 views

2 Problem Solving

This document discusses problem solving and algorithms in programming. It covers the following key points: 1. It outlines the typical steps in problem solving: identifying the problem, understanding the problem, identifying possible solutions, selecting the best solution, implementing the solution, and evaluating the solution. 2. It defines an algorithm as a finite sequence of instructions to solve a problem in a finite amount of time. Pseudocode is described as a more informal way to describe an algorithm using a mix of English and code. 3. It discusses the typical constructs used in pseudocode, including sequencing, selection (if/else), and repetition (while loops). Relational and logical operators are also covered.

Uploaded by

Narasimhan T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

2 Problem Solving

This document discusses problem solving and algorithms in programming. It covers the following key points: 1. It outlines the typical steps in problem solving: identifying the problem, understanding the problem, identifying possible solutions, selecting the best solution, implementing the solution, and evaluating the solution. 2. It defines an algorithm as a finite sequence of instructions to solve a problem in a finite amount of time. Pseudocode is described as a more informal way to describe an algorithm using a mix of English and code. 3. It discusses the typical constructs used in pseudocode, including sequencing, selection (if/else), and repetition (while loops). Relational and logical operators are also covered.

Uploaded by

Narasimhan T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

EST102 : Programming in C

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.

2.2 Steps in problem solving


Effective problem solving usually involves working through a number of steps or stages as
described below:

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.

2.3 Algorithms and pseudocodes


An algorithm describes the method for solving a problem or doing a task. It is a finite
sequence of instructions to solve a problem in a finite amount of time. More formally it
is a step by step procedure which, given an input, enables us to obtain an output. We
say the algorithm transforms the input into output through a systematic execution of the
instructions. Any algorithm must satisfy the following criteria :

• Input : To be supplied by the user.

• Output : To be generated by the algorithm.

• Definiteness : Each instruction must be clear and unambiguous.

• Finiteness : Algorithms must terminate after a finite number of steps.


2.3. ALGORITHMS AND PSEUDOCODES 15

• Effectiveness : Instructions in the algorithm must involve only basic arithmetic/logical


operations.
Pseudo-code is a compact and informal high level description of an algorithm. An algo-
rithm uses short English-like phrases to describe the outline of a solution. On the other
hand, pseudocode uses an appropriate combination of natural language (English) and math-
ematical language to describe the solution. Pseudo-code is more structured than English
prose but less detailed than a program. It is part English, part structured code. The En-
glish part provides a relaxed syntax that describes what must be done, without showing
unnecessary details such as variable (symbolic names for memory locations) declarations,
error messages. The code part consists of high level programming constructs. (See Section
2.1 below.)
Pseudo-code is not a computer program and thus is independent of any programming
language. It cannot be compiled nor executed, and does not follow any syntax rules.
To make the distinction more clear, let us see an algorithm to evaluate the expression
d = a + b ∗ c. We call the algorithm Evaluate-Algo.
Evaluate-Algo
1 Start
2 Read the values of a, b and c.
3 Find the product of b and c.
4 Store the product in a temporary variable (storage) temp.
5 Find the sum of a and temp.
6 Store the sum in d.
7 Print the value of d.
8 Stop.
The following is the pseudocode to evaluate the same expression.
Evaluate-Pseudo
1 Start
2 Read(a, b, c)
3 d=a+b∗c
4 Print(d)
5 Stop
In a pseudocode, Read is used to read input values. Print is used to print a message.
The message to be printed should be enclosed in a pair of double quotes. For example,
Print(“Hello there!!”)
prints
Hello there!!
To print the value of a variable, just use the variable name. In the above example, Print(d)
displays the value of the variable d.
Although pseudocode and algorithm are technically different, we use those words inter-
changeably.
16 CHAPTER 2. THE WORLD OF PROBLEM SOLVING

2.3.1 Constructs of a pseudocode


A good pseudo code should follow the structured approach to programming. The goal
of structured coding is to linearize the control flow through a code so that the execution
sequence follows the order in which the code is written. [Note that, when it is said that “the
pseudocode is executed”, it just means that the pseudocode instructions are processed. It
doesn’t denote the actual execution on a computer.] Linear flow of control can be achieved
by restricting the set of allowed program constructs to single entry, single exit formats. This
feature helps in reducing the number of paths for flow of control within a code. Sequencing,
selection and repetition (loop) is a sufficient set of constructs to describe the control flow
of any single entry single exit code segment. The general form of these constructs are:
Sequencing: S1 ; S2 ; S3 ; · · ·
Selection: if B then S1 else S2
Iteration: while B do S
The single entry, single exit nature of these constructs is illustrated in Figure 2.1.

S1
True False False
C C
S2
True
B1 B2
B
S3

Sequencing Selection Repetition


Figure 2.1: A sufficient set of constructs for structured programming

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.

2.3.1.2 Decision or Selection


A selection structure consists of a test condition together with one or more groups (or
blocks) of statements. The result of the test determines which of these blocks is executed.
In Figure 2.1, if the condition C evaluates to True, then the block B1 is executed, skipping
the block B2 . When the conditon is evaluated to False, the block B2 is executed, skipping
the block B1 . There are mainly two types of selection structures as discussed below:

A The if structure
There are three variations of the if-structure:

A.1 if-then structure


Thg general form of this structure is:

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

A.2 if-then-else structure


The general form is given below:

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.

Example 2.2. The following pseudocode checks if a person is a major or not.

1 if age > 0
2 Print(“You are a major”)
3 else
4 Print(“You are a minor”)
5 endif

A.3 if-then-else if-then-else structure


Sometimes a solution to a problem requires the computer to select one action from a set
of actions. This kind of solution can be designed through if-then-else if-then-else structure
whose general form is given below:

if condition1
true_instructions1
else if condition2
true_instructions2
else
f alse_instructions
endif

Here, if condition1 is met, true_instructions1 will be executed. Else condition2 is checked.


If found True, the block true_instructions2 is executed. Otherwise f alse_instructions
will be executed.

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

B The case structure


The case structure provides an efficient and elegant alternative to if-then-else if-then-
else structure. The pseudocode representation of the case structure is given below.

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

2.3.1.3 Repetition or loop


For certain problems, a certain block of instructions must be repeatedly executed. We
handle this with the repetition or the loop construct. In Figure 2.1, if the condition C
evaluates to True, then the block B is executed. After this, the condition is again tested
and if found True, the block B is executed second time and this process continues as long
20 CHAPTER 2. THE WORLD OF PROBLEM SOLVING

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:

A The while loop


A while loop is generally used for indefinite iteration. The general form of the while loop
is as follows:

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).

B The repeat-until loop


The second type of loop structure is the repeat-until structure. This type of loop also
implements indefinite iteration. Here the set of instructions constituting the loop body is
repeated until condition becomes True. That is, the loop body is repeated as long as the
condition evaluates to False. The pseudocode form of repeat-until loop is shown below.

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.

C The for loop


The for loop implements definite iteration. There are three variants of the for loop as
shown in Figure 2.2. All the three for loop constructs use a loop variable as a counter
that starts counting from a specific value called BeginValue and updates (increments or
decrements the value of) the variable after each iteration. The set of instructions within
the loop repeats till the counter value reaches EndValue.
2.3. ALGORITHMS AND PSEUDOCODES 21

for loop_variable = BeginValue to EndValue for loop_variable = BeginValue downto EndValue


loop_instructions loop_instructions
endfor endfor

(a) (b)

for loop_variable = BeginValue to EndValue by StepValue


loop_instructions
endfor

(c)

Figure 2.2: Three types of for loop constructs

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.

Table 2.1: for loop examples

Loop construct Description Values taken by var


for var = 1 to 10 var gets incremented by 1 till it reaches 10 1, 2, · · · 9, 10
for var = 10 downto 1 var gets decremented by 1 till it reaches 1 10, 9, · · · 2, 1
for var = 2 to 20 by 2 var gets increased by 2 till it reaches 20 2, 4, · · · 18, 20
22 CHAPTER 2. THE WORLD OF PROBLEM SOLVING

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.

Table 2.2: Various flowchart symbols and their description

Flowchart symbol Description

Flattened ellipse indicate the start and the end of a module.

The rectangle indicates a processing block, for such things as


calculations.

The parallelogram denotes an input/output operation

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.

count The polygon indicates a for loop. It is the symbolic representation of


A B the loop:- for count = A to B by S.
S

Flowlines are indicated by arrows to show the direction of data flow.


Each flowline connects two blocks.
2.4. FLOWCHARTS 23

This indicates an on-page connector. This is used when one part of a


long flowchart is drawn on one column of a page and the other part on
the other column of the same page.

This indicates an off-page connector. This is used when the flowchart is


very long and spans multiple pages.

2.4.1 Solved problems - Algorithms and Flowcharts

Problem 2.1 To find simple interest.


Solution: See Figure 2.3.

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

Figure 2.3: To find simple interest

Problem 2.2 To determine the larger of two numbers.


Solution: See Figure 2.4.

Problem 2.3 To determine the smallest of three numbers.


Solution: See Figure 2.5.
24 CHAPTER 2. THE WORLD OF PROBLEM SOLVING

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

Figure 2.4: To find the larger of two numbers

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

Figure 2.5: To find the smallest of three numbers


2.4. FLOWCHARTS 25

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

Solution: See Figure 2.6.

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

Figure 2.6: To determine the entry fare in a zoo

Problem 2.5 To print the colour based on code as follows:

Grade Message
R Red
G Green
B Blue
Any other value Wrong code

Solution: See Figure 2.7.


26 CHAPTER 2. THE WORLD OF PROBLEM SOLVING

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

Figure 2.7: To print colors based on a code value

Problem 2.6 To print the numbers from 1 to 50 in descending order.

Solution: See Figure 2.8.

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

Figure 2.8: To print numbers in descending order

Problem 2.7 To print all the multiples of 5 from 10 to 99.


Solution: See Figure 2.9.
2.4. FLOWCHARTS 27

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

Figure 2.9: To print multiples of 5 between 10 and 99

Problem 2.8 To find the sum of n numbers input by the user.

Solution: See Figure 2.10.

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)

sum = sum + num

count

Print(sum)

Stop

Figure 2.10: To find the sum of n numbers


28 CHAPTER 2. THE WORLD OF PROBLEM SOLVING

Problem 2.9 To find the factorial of a number.


Solution:
The factorial of a number n is defined as n! = n × n − 1 × · · · · · · × 2 × 1. See Figure 2.11
for the pseudocode and flowchart.

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

fact = fact ∗ var

var

Print(fact)

Stop

Figure 2.11: To find the factorial of a number

Problem 2.10 To determine the largest of n numbers.


Solution:
Read the first number and assume it to be the largest. That is, initialize a variable large to
the first number. Then, compare the remaining n − 1 numbers with large and update the
value of large if required. See Figure 2.12.
2.4. FLOWCHARTS 29

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

Figure 2.12: To find the largest of n numbers

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.

Solution: See Figure 2.13.

Problem 2.12 Redo Problem 2.11 using repeat-until loop construct.

Solution: See Figure 2.14.


30 CHAPTER 2. THE WORLD OF PROBLEM SOLVING

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

Figure 2.13: To determine the average age using while loop

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

bavg = btotal /bcount


gavg = gtotal /gcount

Print(gavg, bavg)

Stop

Figure 2.15: To find the average height of boys and girls

You might also like