1. I N T RO D U C T I O N
TO
P R O B L E M
S O LV I N G
C H A P T E R - 4
2. Introduction
• Computers are used for solving various day-to-day
problems and thus problem solving is an essential skill
that a computer science student should know.
• It is pertinent to mention that computers themselves
cannot solve a problem.
• Precise step-by-step instructions should be given by us to
solve the problem.
• Thus, the success of a computer in solving a problem
depends on how correctly and precisely we define the
problem, design a solution (algorithm) and implement the
solution (program) using a programming language.
• Thus, problem solving is the process of identifying a
problem, developing an algorithm for the identified
problem and finally implementing the algorithm to
5. Analyzing the problem
• It is important to clearly understand a problem before
we begin to find the solution for it.
• We need to read and analyze the problem statement
carefully in order to list the principal components of the
problem and decide the core functionalities that our
solution should have.
• By analyzing a problem, we would be able to figure out
what are the inputs that our program should accept and
the outputs that it should produce.
6. Developing an Algorithm
• It is essential to device a solution before writing a
program code for a given problem.
• The solution is represented in natural language and is
called an algorithm.
• We start with a tentative solution plan and keep on
refining the algorithm until the algorithm is able
to capture all the aspects of the desired solution.
• For a given problem, more than one algorithm is
possible and we have to select the most
suitable solution.
7. Coding
• After finalizing the algorithm, we need to convert the
algorithm into the format which can be understood by
the computer to generate the desired solution.
• Different high level programming languages can be used
for writing a program.
8. Testing and Debugging
➢ The program created should be tested on various parameters.
•
•
•
The program should meet the requirements of the user.
It must respond within the expected time.
It should generate correct output for all possible inputs.
➢ In the presence of syntactical errors, no output will be obtained.
➢ In case the output generated is incorrect, then the program should
be checked for logical errors, if any. This is to ensure that the
software meets all the business and technical requirements and
works as expected.
9. Algorithm
•
• In our day-to-day life we perform activities by following
certain sequence of steps.
To complete each activity, we follow a sequence of
steps.
• A finite sequence of steps required to get the
desired output is called an algorithm.
10. Before developing the algorithm, let us first identify the
input, process and output:
• Input: Number whose square is required
• Process: Multiply the number by itself to get its
square
• Output: Square of the number
Algorithm to find square of a number.
Step 1: Input a number and store it to num
Step 2: Compute num * num and store it in square
Step 3: Print square
11. Why do we need an Algorithm?
• The programmer first prepares a roadmap of the program to be
written, before actually writing the code. Such a roadmap is
nothing but the algorithm which is the building block of a
computer program.
• For example, searching using a search engine, sending a message,
finding a word in a document, booking a taxi through an app,
performing online banking, playing computer games, all are based
on algorithms.
• Writing an algorithm is mostly considered as a first step to
programming.
• If the algorithm is correct, computer will run the program
correctly, every time. So, the purpose of using an algorithm is to
12. Characteristics of a good algorithm
•Precision -the steps are precisely stated or
defined.
• Uniqueness -results of each step are uniquely
depend on
defined and only
the input and the result of the
preceding steps.
•Finiteness -the algorithm always stops after a
finite number of steps.
• Input
• Output
-the algorithm receives some input.
-the algorithm produces some output.
13. While writing an algorithm, it is required to
clearly identify the following:
• The input to be taken from the user
• Processing or computation to be performed
to
get the desired result
• The output desired by the user
14. Representation of Algorithms
❖ There are two common methods of representing an
algorithm —flowchart and pseudo code.
❖ Either of the methods can be used to represent an
algorithm while keeping in mind the following:
•It showcases the logic of the problem
solution, excluding any implementation details
• It clearly reveals the flow of control during
execution of the program
15. Flowchart
•
•
•
A flowchart is a visual representation of an algorithm.
A flowchart is a diagram made up of boxes, diamonds
and other shapes, connected by arrows.
Each shape represents a step of the solution process
and the arrow represents the order or link among the
steps.
19. Draw a flowchart to solve the problem of a non-functioning
light bulb
20. Pseudocode
• A pseudocode is another way of representing an
algorithm.
• It is considered as a non-formal language that
helps programmers to write algorithm.
• It is a detailed description of instructions that a
computer must follow in a particular order.
• It is intended for human reading and cannot be executed
directly by the computer.
• No specific standard for writing a pseudocode exists.
• The word “pseudo” means “not real,” so “pseudocode”
means “not real code”.
21. Following are some of the frequently used keywords while
writing pseudocode:
• INPUT
• COMPUTE
• PRINT
• INCREMENT
• DECREMENT
• IF/ELSE
• WHILE
• TRUE/FALSE
22. Write an algorithm to display the sum of two
numbers entered by user, using both pseudo code
and flowchart.
Pseudo code for the sum of two numbers will be:
INPUT num1
INPUT num2
COMPUTE Result = num1 + num2
PRINT Result
23. Write an algorithm to calculate area and perimeter of a
rectangle, using both pseudo code and flowchart.
Pseudo code for calculating area and perimeter of a
rectangle.
INPUT length
INPUT breadth
COMPUTE Area = length * breadth
PRINT Area
COMPUTE Perim = 2 * (length + breadth)
PRINT Perim
24. Benefits of Pseudo code
•
•
• Before writing codes in a high level language, a pseudo
code of a program helps in representing the basic
functionality of the intended program.
By writing the code first in a human readable language,
the programmer safeguards against leaving out any
important step.
Besides, for non-programmers, actual programs are
difficult to read and understand, but pseudo code helps
them to review the steps to confirm that the proposed
implementation is going to achieve the desire output.
25. Flow of Control
•
• The flow of control depicts the flow of events as
represented in the flow chart.
The events can flow in a sequence, or on branch based
on a decision or even repeat some part for a finite
number of times.
26. Sequence
•
•
• The sequence construct means the statements are being
executed sequentially .
Algorithms where all the steps are executed one after the other are
said to execute in sequence.
It is simply performing one step after another.
27. SELECTION
•
•
•
• Selection construct means the execution of statements depending
upon a condition.
If a condition evaluates to true, set of statements is followed otherwise
a different set of statements are followed.
This construct is also called decision construct because it helps in
making decision about which set of statements is to be executed.
It is used to make yes/no or true/false decisions logically.
28. Write an algorithm to check whether a number is odd or even.
• Input: Any number
• Process: Check whether the number is even or not
• Output: Message “Even” or “Odd”
Pseudocode of the algorithm can be written as follows:
PRINT "Enter the Number"
INPUT number
IF number MOD 2 = = 0 THEN
PRINT "Number is Even"
ELSE
PRINT "Number is Odd"
29. Write a pseudocode and draw a flowchart where multiple conditions are
checked to categorise a person as either
child (<13), teenager ( >= 13 but <20) or adult (>=20),based on age
specified.
• Input: Age
• Process: Check Age as per the given criteria
• Output: Print either “Child”, “Teenager”, “Adult”
Pseudocode is as follows:
INPUT Age
if Age < 13 then
PRINT "Child"
else if Age < 20 then
PRINT "Teenager"
else
PRINT "Adult"
30. The syntax of if statement is:
if condition:
statement(s)
Example of if
statement is,
age = int(input("Enter your
age "))
if age > = 18:
print("Eligible to vote")
31. Syntax of if else :
if condition:
statement(s)
else:
statement(s)
Example of if else :
age = int(input("Enter your age: "))
if age > = 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
32. Syntax of if else if :
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s
)
Example of if
else if:
number = int(input("Enter a
number: ") if number > 0:
print("Number is
positive") elif number < 0:
print("Number is negative")
else:
print("Number is zero")
33. Algorithm for a card game called “Dragons and Wizards”. Make two
teams DRAGONS and WIZARDS The rules for the game are as
follows:
•If the card drawn is a diamond or a club, Team DRAGONS gets
a point
•If the card drawn is a heart which is a number, Team
WIZARDS gets a point
•If the card drawn is a heart that is not a number, Team
DRAGONS gets a point
• For any other card, Team WIZARDS gets a point
• The team with highest point is the winner
Let us identify the following for a card:
Input: shape, value
Process: Increment in respective team scores by one based on the
34. INPUT shape
INPUT value
SET Dpoint
= 0, Wpoint
= 0
IF (shape is diamond) OR (shape is club) THEN
INCREMENT Dpoint
ELSE IF (shape is heart) AND (value is
number)THEN
INCREMENT Wpoint
ELSE IF (shape is heart) AND (value is not a
number)THEN
INCREMENT Dpoint
ELSE
INCREMENT Wpoint
END IF
If Dpoint > Wpoint THEN
PRINT "Dragon team is the winner"
ELSE
PRINT "Wizard team is the winner"
35. ITERATION
• The iteration construct mean repetition of a set-of-
statements depending upon a condition-test.
• Iteration is a looping construct
• Iteration is a combination of decision and sequence and
can repeat steps
• Iteration can be thought of as “while something is true, do
this, otherwise stop”
• Iteration logic is used when one or more instructions may
be executed several times depending on some condition
.
36. Syntax of the For Loop:
for <variable> in <sequence>:
statements to_repeat
Example of the For Loop:
for letter in 'PYTHON':
print(letter)
Syntax of the while Loop:
while test_condition:
body of while
37. Write pseudocode and draw a flowchart to accept 5 numbers and find their
average.
Pseudocode will be as follows:
Step 1: Set count = 0, sum = 0
Step 2: While count <5 , repeat steps 3 to 5
Step 3: Input a number to num
Step 4: sum = sum + num
Step 5: count = count + 1
Step 6: Compute average = sum/5
Step 7: Print average
38. Write pseudocode and draw flowchart to accept numbers till the user enters 0
and then find their average.
Pseudocode is as follows:
Step 1: Set count = 0, sum = 0
Step 2: Input num
Step 3: While num is not equal to 0, repeat Steps 4 to 6
Step 4: sum = sum + num
Step 5: count = count + 1
Step 6: Input num
Step 7: Compute average = sum/count
Step 8: Print average
39. Verifying Algorithms
• To verify, we have to take different input values and go
through all the steps of the algorithm to yield the desired
output for each input value and may modify or improve as
per the need.
• The method of taking an input and running through the
steps of the algorithm is sometimes called dry run.
• Dry run will help us to:
1. Identify any incorrect steps in the algorithm
2. Figure out missing details or specifics in the
algorithm
• It is important to decide the type of input value to be used
for the simulation.
• In case all possible input values are not tested, then the
40. Comparison of Algorithm
• There can be more than one approach to solve a
problem using computer and hence we can
have more than one algorithm.
• Algorithms can be compared and analysed on the
basis of the amount of processing time they
need to run and the amount of memory that is
needed to execute the algorithm. These are
termed as time complexity and space
complexity, respectively.
• The choice of an algorithm over another is done
depending on how efficient they are in terms of
41. Coding
• Coding is the process of converting algorithm to
the syntax of the given programming
language.
• The ordered set of instructions is written in that
programming language by following its syntax.
• Syntax is the set of rules or grammar that
governs
the formulation of the statements in the language,
such as spellings, order of words, punctuation,
etc.
• A program written in a high-level language is
42. Decomposition
•
•
• The basic idea of solving a complex problem by
decomposition is to 'decompose' or break down a
complex problem into smaller sub problems.
Finally, the sub-problems are combined in a logical way
to obtain the solution for the bigger, main problem.
Each sub problem can be solved independently and by
different persons