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

Chapter 5 - Introduction to Problem Solving

Uploaded by

misanthrope2708
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 5 - Introduction to Problem Solving

Uploaded by

misanthrope2708
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

5

Introduction to
Problem Solving
In This Chapter

5.1 Introduction
5.2 Problem Solving Cycle

5.3 Designing Algorithms

5.1 INTRODUCTION
There is a famous quote by Steve Jobs, which says, "Everyone in this country should learn to
program a computer, because it teaches you to think".
This quote itself is proof-enough to say that in order to program a solution for a problem, you
should think in a specific way. And this is what we are going to talk about in this chapter.
In this chapter, you will learn about problem solving, i., analysing a problem, designing
algorithms using tools like flowcharts and pseudocode and problem solving using
decomposition. So, let us begin.

109
110 cOMPUTER SCIENCE WITH
PYTHON
5.2 PROBLEM SOLVING CYCLE
Programs are not quick creations. In order to create efficient and effective programs, youh
should
adopt a proper problem solving methodology and use appropriate techniques. In fact, prah.
solving methods follow a cycle - the problem solving cycle. In the coming lines, we are eoin bblem
discuss the same. oing to
Broadly problem solving requires four main steps
1. Identify and the problem.
analyse
2. Find its solution and Develop algorithm of the solution.
3. Code the solution in a
programming language.
4. Test and Debug the coded solution. 1
Analyse the
2
And finally implement and maintain it. problem Find solution
and Develop
The above mentioned steps are four major steps in a Algorithm
problem solving cycle. Each step contains many
sub-steps. Let us talk about these sub-steps in order to
Perform Testing
understand the problem solving cycle. The aim of a and
problem solving cycle is to create a working program Debugging
Coding of the
for the solution. solution

The sub-steps of a problem solving cycle to createa


Figure 5.1 Steps in Problem solving cycle.
working program are:

1. Understand the It is very important to understand the problem minutely because


problem well sometimes the problem is not that appears but something else that
is causing it.

2. Analyze the problem Problem analysis is very important as the outcome of this will
convert to the success of final solution. While analyzing
identify processing components
identify the relationships among processing components.
3. Think of As per the problem analysis, think of
possible solutions by trying ths
possible solutions think of different ideas for solutions
check your ideas for aptness
finally, zero on most appropriate solution.
Follow Modular Many small logically related modules.or functions must be P
approach while ferred over a big problem. It is called Modular approach whered
designing miost divide a big program into many smaller and more managea
appropriate solulion understandable modules.
Design the final program by
deciding step by step solution
breaking down solution into simple steps.
tions

ldentify operalions Program coding involves identification of constituent operathe


out
for solution required to get the desired output. One must decide ab
minimum but simple operations
required. Identiry
minimum number of inputs
required
arithmetic and logical operations required for solution
simple and efficient data structures suiting the need:
Chapter 5 : INTROLDUCTION TO PROBLEM SOLVING 111

Code program using Ihe next


step is to code the program as per finding or previOus
appropriate contro step. Coding is the technical word for writing the program. This
structures step is to translate the algorithm into a programming language-
IOu should use most appropriate control structures out of available

options. Thus, it is important to know the working of different


control structures and their suitability in different situations.
such conditional or
Use appropriate control structures as

looping control structures.


Think program's efficiency in terms of speed, performance and

effectiveness.
Test and Debug your and debugging
7. Testing is the process of finding errors in a program
program is the process of correcting errors found during the testing process.
Thus, this phase involves:
finding errors in it.
rectifying the errors.
Documentation is intended to allow another person or the prog
8. Complete your rammer at later date, to understand the program. Documentation
documentation
might also consist of a detailed description of what the program
does and how to use the program.
After testing and documentation, implement your program for
9. lmplement your
code actual use on site. Now, the real users can use your programs.

10. Maintain your Maintaining programs involves modifying the programs to remove

previously undetected errors, to enhance the program with different


program
features or functionality, or the program
keep up-to-date as

government regulations or company policies change.

5.2.1 Problem Solving using Decomposition


The previous section talked about problem solving cycle. The DECOMPosITION
first five steps of problem solving cycle are very important as The process of breaking down a big|
rest of the steps are based on them. or complex problem into a set of
The first five steps involve understanding the problemn, smaller sub-processes in order to
sub-module understand a problem or situation
analyzing it, and thinking of possible solution with better, is known as decomposition.
and operations in it. All this is effectively carried out using

decomposition. Let us know what decomposition means.

into a set of smaller


Decomposition is the process of breaking down a big complex problem
or

sub-processes to allow us to describe, understand, or execute the problem better. Decomposition

involves
Dividing a task into a sequence of subtasks.
Identifying elements or parts of a complex system.
Big problem Break down into
smaller, logical parts

Part 2 of problem
Part 1 of problem
Further break down
Further break down into even smaller
into even smaller,
ogical parts
logical parts Sub-problem 2 Sub-problem 3 Sub-problem 4
Sub-problem 1
112 COMPUTER SCIENCE WITH PYTHONV
X

Consider some examples of decomposition:


Everyday example. Making cookies is a complex task that can be broken down into smale
simpler tasks such as mixing up the dough, forming into shapes via cookie cutters,and
baking.
Academic example. Writing an essay is a complex task that can be broken down into snmaller
tasks such as developing a thesis, gathering evidence, and creating a
bibliography page
Engineering example. Designing a solution to construct a bridge by considering site
conditions, technology available, technical capability of the contractor, foundation, etc.
Computer Science example. Writing a computer program/software by determining a
well-defined series of smaller steps (mostly in the form of modules and
the problem or achieve a desired outcome.
functions) to solve

EXAMPLE 1 Decompose the task of creating mobile app.


SOLUTION To decompose the task of creating a mobile app, we would need to know the answer to
a series of smaller problems
what kind of app is to be created.
who the target audience for the app is.
what the user interface of the app will be (what all screens, type of input etc.).
what the app's graphics will look like.
what audio will be included.
what software/ platform will be used to build the app.
how the user will navigate the app.
what additional services will be required for the app, e.g., database etc.
how the app will be tested.

This list has broken down the


complex problem of creating an app into much simpler problems
that can now be worked out.

Need for Decomposition


Decomposition is the process of breaking a large problem
into more manageable
sub-problems. It is very important
to decompose a
problem into smaller sub-problems,
reason being
that large problems are
disproportionately
harder to solve than smaller
problems. t's much easier to Problem size
write two 500-line programs than a
single 1000-line
program. Larger a problem is, harder and more difficult
it is to program NOTE
as
compared to a smaller problem (see
figure).
Decomposing a problem into
Once you know how you can smaller sub-problems is importan
decompose a
problem in
smaller steps, you can create its solution because large problems are
algorithms for it.
by designing disproportionately harder to solve
than smaller problems.
ter 5: INTRODUCTION TO PROBLEM SOLVING 113

(O

2
C
114 COMPUTER SCIENCE WITH PYTHON

5.3 DESIGNING ALGORITHMS

Computers are essentially problem solving devices. Computers solve


these problems
dividing
the by
problems in simple and small steps that are expressed in the form of
instructions. computer
The set of rules that define how
known as algorithm. An
particular problem can be solyed in finite number of stéps is
a

algorithm is composed of a finite set of steps, each of which may


require one or more
operations. But there are certain constraints to be placed on the type
operations' as algorithm carm include. of

These are
Each operation
i.e., it must be
clearly defined what should be done. For instance, 'x
must be definite =6/0,
'add 3 or 8 to a' are not
permitted as these operations are not clearly defined.
Each operation i.e., each step must þe such that it can be done
must be effective
finite amount of time. For using pencil and paper in a
example, arithmetic on integers is effective
operation, whereas arithmetic on real numbers is not since some values
be expressible only may
by an infinitely long decimal expansion
Each operation i.e., the algorithm should terminate after a finite number of
must be finite operations.
Thus, we can
say that a
good algorithm must have
sub-section. characteristics as listed in the following
Characteristics of a Good Algorithm
In order to be an effective
algorithm, an algorithm must have the following characteristics
1. Precision. An algorithm should be
precise, i.e., its steps should be precisely defined.
2.
Uniquenes. Every step should uniquely contribute to the
unique and it is only dependent on the algorithm.
result of a step is It means that the

preceding steps. input and the result of the


3. Finiteness. An algorithm must be finite. It must not repeat the steps
algorithm must stop after a finite number of instructions endlessly. The
have been executed.
4. Input. An algorithm requires a specific type of
5.
input to work upon.
Output. An algorithm produces output as per the stated
received. objectives and the it has input
Components of an Algorithm
An algorithm clearly identifies the following
components :
Input the inputs and the type of inputs required
-

the algorithm. The inputs can be by


can be self-obtained
provided by a user
too, such as reading from a file.
or NOTE
One must be able to identity
Processing what and how the processing would use
-

where inputs, processing and


inputs to produce the desired output. outputs are taking place witn
an algorithm.
Output -the output expected from the algorithm; the
objective of the algorithm.
Chapter 5:
INIRODUCIION TO PROBLEM SOLVING 115

A program is the expression of an algorithm in a programming language. Thus, the success of a


program depends upon the algorithm. Therefore, the logic of the problem must be clearly
expressed in algorithm. The logic of the problem can be expressed in various manners. One of
the most preferred methods is the graphical method of representing the problem's solution,
which is known as flowchart.
Another useful tool for designing algorithms is pseudo-code. In the coming subsections, we are

talking about both these tools.

5.3.1 Flowcharts
A flowchart is a pictorial representation of step by step solution of a problem.
A flowchart not only pictorially depicts the sequence in which
FLOWCHART
instructions are carried out in an algorithm but also is used as
A flowchart.is a pictorial
an aid in developing algorithms. One must be familiar with representation of step by step
such an important tool used in programming. This section solution of a problem.
briefly discusses the technique of flow charting.
There are various flowchart symbols that carry different messages and are used for different
purposes. These symbols are shown below:

Symbol Purpose Symbol Purpose


Flow of
Start/Stop control symbol

Input/Output
Annotation

Processing

Decision Box
O Connector.

Following section illustrates the working and use of tlow charts along with algorithm

development.
Writing Algorithms
0 write algorithms, such a language should be used that is close enough to the programming
language(s) (in which the programs are to be written) so that a hand translation is relatively
Easy to accomplish. Thus, we have chosen a language for algorithms that resembles our

programming language Python.


Let us discuss
certain rules for writing algorithms.
ldentifiers
aentitiers are the names given to various components of a program by the programmer e.g., to

Variables that hold values, to functions, modules etc.


nile choosing names for identifiers, make sure that these are meaningful and not

unnecessarily long or short names.


116
COMPUTER SCIENCE WITH PYTHON
Assignment
The assignment of values to variables is done through assignment statement as
variable - <expression>
e.g A-10
In an algorithm, the left arrow
(-) denotes the act of assigning the value of its right-hand side
the variable on its left. Some to
people take liberty and use assignment operator to assign values to
variables in algorithms.
Sequence
The of an algorithm are executed in the
steps sequence of top to bottom. One after another so
steps must be listed in the correct order.

Selection/Conditional Statements
A conditional
statement in an algorithm takes the following form:
i fcondition ifcondition:
statement # block1 OR statement # block 1
else
s2 # block 2
There may be one or more if-then-else statements
embedded in another if-then-else statement.
Figure 5.1 depicts conditional statements pictorially.

true
Condition Condition
true

false or
false

Figure 5.1 The conditional If statements

Repetition Looping Statement


A looping statement (also called iteration Start
statement)
lets you repeat a set of statements
depending upon a
condition. To accomplish iteration, the for loop and
while loop are used. for item in seq:

tor looping statement Test


for item in sequence: Is seq.
Next Yes
:St #block of statements empty?

No
St represents the set of statements to be repeated for
each item in the sequence. When the statements block Statement block
Stop

gets executed for each item in the sequence, the


for-loop stops. Figure 5.2 (a) for loop process.
nter 5 : INTRODUCTION TO PROBLEM SOLVING 117
Chaprer

while looping statement

while loop
while condition: Condition False
processing

St # block of statements
while ?

Irue
St represents the set of statements to be
The while iteration statement tests
repeated. statement
the condition before entering into the loop.
Thus, if the condition is false even before
entering into the loop, the while-loop will statement
-

never get executed.

Let us now consider some examples of algorithms


and flowcharting.
Figure 5.2 (b) while loop processing

EXAMPLE 2 Draw a flowchart to add two numbers, along


Start
with algorithm in simple English.
SOLUTION
Read N1
Algorithmn
Step 1. Start Read N2
Step 2. Get two numbers N1 and N2
S = N1 + N2
Step 3. S-N1 + N2

Step 4. Print the result S


Print S
Step 5. Stop
Stop

Draw a Flowchartto find Area and Perimeter of Rectangle, along with algorithm in simple English.
EXAMPLE3
L:
Length of Rectangle, B: Breadth of Rectangle
AREA: Area of Rectangie, PERIMETER : Perimeter of Rectangle (Start
SOLUTION
Inputvalue of L, B
Algorithm
Step 1. Start AREA=LxB
Step 2. & Breadth say L, B
Step Input Side-Length
PERIMETER =2 x(L +B)
Step B. AREA -LxB
Step 4. PERIMETER-2x(L+B) Print AREA, PERIMETER
Step
Step 5. Print AREA, PERIMETER

Step 6. Stop (Stop


118 COMPUTER SCIENCE WITH
PYTHON -
EXAMPLE 4 Draw flowchart to convert
a
temperature from Celsius to Fahrenheit
along with algori
ng with
simple English. C : temperature in Celsius, F : temperature Fahrenheit algorithm in
Formulas to be used
Fahrenheit to Celsius C=(F-32)
Start
Celsius to Fahrenheit: F=C. +32
Input value of C
SOLUTIOON
Algorithm F 9.0/5.0*C-32
Step 1. Start
Print F
Step 2. Input temperature in Celsius in variable C
Step 3. F-(9.0/ 5.0x C) +32
Stop
Step 4. Print Temperature in Fahrenheit F
Step 5. Stop

EXAMPLE 5 Draw a flowchart to determine the


larger of two numbers, along with algorithm in simple Start

English.
SOLUTION Read a, b

Algorithmn
Step1. Start Yes
a >b
No

Step 2. Get two numbers a and b

Step 3. If a>b then print a else print b Print a Print b

Step 4 Stop
Stop

EXAMPLE 6 Draw a
flow chart to print even numbers from 2 to 10* using a loop approach, along w
algorithm in simple English.
SOLUTION Start

Algorithm
i 2
Step 1. i-2
Step 2. While i< 10
Repat steps 3 through 4 False
10

Step 3. Print i .

True
Step:4. i-i+2
Step 5. Stop Stop Printi
5: INTRODUCIION TO PROBLEM SOLVING 119
Chapter

EXAMPLE
Draw a flow chart to calculate 2*,
along with algorithm in simple English.
sOLUTION

Start
Algorithm

Step 1. Input Base (2), Power (4) Input base (2).


Power (4)
Step 2. Product- Base
Step 3 . Product P r o d u c t * Base
Product= Base
Step 4 ProductProduct *Base
Product Product Base
Step 5. Product- Product* Base
Step 6. Print Product
Product = Product * Base
Step 7. Stop
Product Product* Base

Print Product

Stop

EXAMPLE8 Draw a flow chart to calculate 2 using a loop approach, along with algorithm in simple English.
SOLUTION
Start
Algorithm
Step 1. Input Base (2), Power (4)
Input base (2),
Power (4)
Step 2. Product -Base
Step 3. Counter-1 Product= Base
Step 4. While (Counter < Power) Counter =1
Repeat steps 4 through 6

Step 5. Product Product * Base S


C o u n t e r < Power
No

Step 6. Counter Counter +1


Yes
Step 7. Print Product Product Product Base
Step 9. Stop Print Product

Product= Counter + 1

Stop
120 COMPUTER SCIENCE WITH PYTHON

5.3.2 Pseudocode
Pseudocode is an informal language that helps programmers describe steps of a progan
solution without using any programming language syntax. Pseudocode is a "text-based"det
(algorithmic) design tool. A pseudocode creates an outline or a rough dratt of a programtletail
that
gives the idea of how the algorithm works and how the control flows from one step to another
ther.
For example, consider the following pseudocode
NOTE
If student 's marks is greater than or equal to 56
Pseudocode is an informal way
display "passed" of describing the steps of a
else program's solution without
using any strict
programming
display "failed language syntax or underlying
The above pseudocode gives you an idea how a program technology considerations.
determines whether a student has passed or failed comparing
the marks of the student.
Consider the same algorithm that we talked in example 5 (determine if the first mumber is
greater than the second number or not). The pseudocode of this algorithm can be like :

Input first number in variable firstnum.


Input second number in variable secondnum
if the firstnum is > the secondnum
display' the first number IS greater than second number"
else
display the first number IS greater than second number.
Please note there are no standard rules to write a pseudocode
as it is totally informal way of representing an algorithm. NOTE
the
In pseudocode, usually
Advantages and Disadvantages of Pseudocode instructions are written in upper
lowercase and
The pseudocode is a very useful and helpful tool in algorithm case, variables in
messages in sentence case
advantages and it has
development. It offers many some

disadvantages too.

Pseudo-code Advatages
I t uses a language similar to everyday English, thus is easy to.understand.

I t highlights the sequence of instructions.


and

The structure of an algorithm is clearly visible through pseudocode, e.g., selection


repetition blocks.
Pseudocode can be easily modified without worrying about any dependencies.
Pseudo-code Disadvantages
I t is not a visual tool like flowcharts.
rammer

S i n c e there is no accepted standard for pseudocode, so it varies from programmer to prog

I t can only be tested on paper, there is no program available to test it.


I t is an informal representation of an algorithm.
5 INTRODUCTION TO PROBLEM SOLVING 121
hapter

IF word = 'x'
EXAMPLE9 Write pseudocode that converts from
Ealrenheit to Celsius or from Celsius to Fahrenheit, PRINT number of words entered

the user's choice. BREAK OUT from the loop


depending on
sOLUTION Pseudocode ELSE

X= INPUT "Press 1 to convert from Fahrenheit add 1 to count


to Celsius or Press 2 to convert from
Celsius to Fahrenheit."

INPUT ask what number? EXAMPLE 11 Write pseudocode that asks how
y
IF 1 is pressed many numbers (say n), and then print all those numbers
# do f t c conversion after n numbers have been entered.
C=5/9*(F - 32) SOLUTION Pseudocode:
PRINT Output C
INPUT value of n #howmany numbers
ELSE IF 2 is pressed
# do c to f conversion
Initialise numbercount
Initialise listnum as an empty list
F 9/5 * (C+ 32)
WHILE the numbercount <= n
PRINT output F
ask for a number
ELSE add one to number count
PRINT "Please enter either 1 or 2"
add number to listnum
# now the numbers have been entered, loop is over
EXAMPLE 10 Write pseudocode that lets the user:
# take listnum' s numbers in item one by one
type words and when they press '*', it prints how many
FOR item in listnum
words the user inputted then quits program.
PRINT item
SOLUTION Pseudocode
# item now takes next number in listnum
WHILE true
INPUT "Enter a Word"
PRINT wOrd

5.3.3 Verifying an Algorithm


Verification of an algorithm means to ensure that the algorithm is working as intended.
For example, if you have written a program to add two numbers but the algorithm is giving
you the product of the two input numbers. In this case, the algorithm is not working as
intended.
NOTE
Then how do you verify an algorithm ? Ohh, yeah you're
right should test it with a sample inputs for which we
we The word 'algorithm' comes
Know the output; if the expected output matched with
the from the ninth-century Arab
is verified. mathematician, Al-Khwarizmi,
output produced by the algorithm, the algorithm who worked on written
we may want
This is really helpful, but for larger algorithms, processes to achieve some goal'
of the
to
verify the intermediate results too of various steps of
The term algebra' also comes
from the term al-jabr, which he
mechanism
agorithm. And for such requirements, a useful
introduced.
verifying algorithm called Dry-Run is used.
5.3.3A Dry Run
their code to trace the
Aary run is the process of a programmer manualy working through
Value of variables. There is no software involved in this process.
COMPUTER SCIENCE WITH PYTHON
122 - K

out of the code. The programmer would sit d..


Traditionally, a dry run would involve print
a

and manually follow


check
the value of a variable to that it was lisad
with a pen and paper d
updated as expected. DRY RUN
If a programmer found that the value is not what it should be, A dry run is the process
of
able to identify the section of code that resulted in the programmer manually working
they are
through their code to trace the
error. value of variables. There is
no
Characteristics of a dry run are: software involved in this process.
I tis carried out during design, implementation, testing or maintenance.

It is used to identify the logic errors in a code.


I t carnnot find the execution errors in a code.

Trace Tables
Dry running an algorithm is carried out using trace tables where the impact of each line of the
code is seen on the values of, variables of the algorithm. As per the line of the code, the
processing that takes place is applied on the variables' values.
For example, wé want to calculate the double of the numbers in sequence 1, 2, 3 and print the
value as 1 added to the double value
To see
Dry Run 1. FOR number <- 1 TO 3
action
V a l - number * 2

3. PRINTVal +1

The trace table for the above code will record the code movement and its impact on
Scan
QR Code
the variables, line by line:

Line number Number V a l -number * 2


Print Val+1
Val
2
Number assigned number *2
value 1

Loop's next pass starts


Val+1
2 is printed
2
4

Loop's next pass startss


3

6
3
7
So the given code's trace table will be as shown above, when the code is The
above given trace table has documented the dry-run.
impact of each line of the code separately.
tar 5 : INTRODUCTION TO PROBLEM SOLVING 123

However, you can skip this style and simply show the impact of code on variables too, eg, as
shown below:

Print
Line numbers Number Valnumber *2 Val +1

1-3 1 2 3

1-3 4 5

1-3

NOTE
You can choose to skip line numbers too, if
Trace tables enable the variable values
in an algorithm
you want as we have done in the example
to be recorded as the algorithm is dry
run.

below.

the code given below SOLUTION


EXAMPLE12Dry-run
and show its trace table. OUTPUT
num Count num < 500 (Values printed)
num-USER INPUT
16 TRUE
count0
32 TRUE
WHILE num < 500 THEN
n u m -n u m * 2 64 2 TRUE
128 TRUE
Count c o u n t +1
256 4 TRUE
#end while
PRINT num
512 FALSE
512
PRINT count
5

5.3.4 Comparing Algorithms


To solve a problem, many times, in
a fact, mostly multiple
C h e c kP o i n t
solutions are available. In other words, you may have
which working correctly and producing
5.1 multiple algorithms which algorithms
In such
the correct, desired results.
a case,

1. Name some useful tools for program should you choose for coding?
another,
decide which algorithm to choose
over
development. In order to
2. What is the difference between an factor.
efficiency will be the deciding
their
algorithmand pseudocode? efficiency of an algorithm are:
3. Which of the following is graphica? Major factors that govern the
to find the solution and
(a) algorithm (b) flowchart the time it takes
which are consumed in the process.
c)pseudocode (d) dry run the resources

Which of the following usefil för buying a car, how do you choose a car
For instance while
tracing a pseudo code ?
avaílable choice? Yup, you are absolutely right; you
from and the fuel.consumption.
(a) algorithm (b) flowchart both the speed
might consider to you, will win.
()pseudocode (d) dry run the most
The factor that matters
. What is the use of trace table ?
124 COMPUTER SCIENCE WITH PYTHON - XI

Similarly, for algorithms, the two deciding factors are


Space-wise efficiency. How much amount of (memory) space the algorithm will take
up
before it terminates. For this, we consider the amount of data the algorithm uses whi
hile
running.
Time-wise efficiency. How much time the algorithm takes to complete. This factor
is
dependent on so many issues like, RAM available, programming language chosen, the
hardware platform and many others.

When you have hardware platform fixed with a specific RAM size, then space efficiene
becomes the deciding factor and the algorithms that takes up less space is chosen.
With this we have come to the end of this chapter. Let us quickly revise what we have leamt so
far in this chapteer.
LET US REVISE

A Flowchart is pictorial representation of step by step solution


a
of a problem.
The logical sequence of precise steps that solve given problem, is called
a
Algorithm.
A n algorithm must be a finite series of steps; each step must be precise; it must be efficient i.e., terminate in a
reasonable amount of time, and must produce the correct results i.e., it must be effective.
T h e process of breaking down a big or complex problem intoa set of smaller sub-processes in order to understand a
problem or situation better, is known as decomposition.
Decomposing a problem into smaller sub-problems is important because large problems are disproportionately
harder to solve than smaller problems.
Pseudocode is an informal way of describing the steps of a program's solution without
using any strict programming9
language syntax or underlying technology considerations.

bjective Type Questions

Multiple Choice Questions


OTQs
1. What is an algorithm ?
(a) A set of steps to solve a problem (b) Software that analyses data
(c) A hardware device that stores data (d) All of these
2. What is pseudo-code ?
(a) A diagrammatic representation of a set of instructions
(b) An algorithm written out in words
(c) A very specific programming language used by all
computers
(d) All of these
3. Which of the following would assign user input to a variable?
(a) INPUT =myVar (6) myVar-INPUT
(c) INPUT myVar (d) All of these
4. What shape represents a decision in a flowchart ?
(a) A diamond (b) A rectangle (c) An oval (d) None of these
Chapter 5:
INIROLUCIION TO PROBLEM SO\ 125

is decomposition ?
5. What
(a) Breaking code down once it has been run
(6) Breaking a problem down into smaller, more manageable sections
()Breaking a problem into subroutines (d) Breaking big data into small data

6.Which of the following are tools to design algorithms ?

(a) Using variables and data (b) Using inputs and outputs

(c) Using pseudo-code and flowcharts (d) Using functions and procedures
7. What is true for
the term Decomposition ?
(a) It uses computers to solve problems.

symbols and removes


(b) It represents real world problems in a computer using variables and
unnecessary elements from the problem.
()It is the process ofbreaking down a large problem into smaller sub-problems.
d) It identifies the steps involved in solving a problem.

8. If Cis true, S1 is executed in both the flowcharts, but s2 is executed in


)both (1) and (2) (d) neither (1) nor (2)
a) (1) only (6) (2) only

While True While True s1


C C

False False

S2

(1) (2)
how many times the loop is iterated?
9. Consider the following pseudocode and determine

while i #5
i:=i+1

4 (b) 5 ()6 (d))0


l0. If C is false just before the loop in the following code, the control flows through

1 $1
2 while C
3 S2
4 S3
(a) S1 S3 (b) S1 $2; $3
S3
(c) S1;$2 ; S2; $3 (d) S1; $2; $2; $2;
. Which of the following activities is algorithmic in nature
(b) Describe a bicycle.
(a) Assemble a bicycle.
how bicycle works.
(c) Label the parts of a bicycle. (d) Explain a

4Which of the following activities is not algorithmic in nature


) Multiply two numbers (b) Draw a kolam.
(c)Walk in the park. (d) Braid the hair.
126 COMPUTER SCIENCE WITH PYTHON - X

13. The process of checking the correctness of an algorithm by checking the variables' values after
steps, without actually running the program is every
(a) No execution (b) Dry run (c) Dry output (d) Dry test
14. The purpose of a trace table is that
(a) it used to record the results from each step in an algorithm;
(b) it used to record the image from flowchart
(c) it used to store variable names
(d) it used to store the output
15. Look at the Algorithm below. In the corresponding Trace Table, what value should 'E' be ?

Algorithm Trace Table


1 number =3 Line number i OUTPUT
2 PRINT number 3
3 FOR i from 1 to 3 2 3
4 number =number + 5
3
5 PRINT number
4 8

5 3
(a) 3
3 2
(b) 8
4 13
(c) 3
5 13
(d) 18
3 E
4 16
5 F

16. Look at the Algorithm below. In the corresponding Trace Table, what value should 'F be ?

Algorithmn Trace Table


1 number = 3

2 PRINT number
Line number OUTPUT
3
FOR i from 1 to 3
4 3
number =
number +5
PRINT number
8

8
3
2
4 13
(a) 3
13
(6)8
(c) 13
18
(d) 18
5

17. What are the common factors for comparing the two
algorithms doing the same work ?
(a) Space b) Time
(c) programming language (d) both (a) and (b) (e) (a), (b), and (c).
Chopter
ofer 5 : INTRODUCTICN TO PROBLEM SOLVING 127

Fill in the Blanks


1. An. is a plan, a set of step-by-step instructions to solve a
problem.
2. Using. we can break down the problem into smallerparts.
3. Writing in. is similar to writing in a programming
language.
4. A i s a diagram that represents a set of instructions.

5. An is simply a sequence of steps for completing a task.


6. Algorithms can be represented in many ways, the most commonly used being and
7. Algorithms are compared through their wise efficiency and wise efficiency.
8. Testing an algorithm by viewing the impact of code on variables, using pen and paper is called.
9. The table that stores the intermediate results of the code on a variable while doing dryrun, is called
table.
10. The is similar to a code but is not based on any programming language.

True/False Questions
1. An algorithm is the step by step solution of a problem.
2. While solving a problem, you start coding from the first step.
3. Decomposition is an additional task, which may be avoided.
4. Decomposition is necessary as larger problems are harder to code.
5. A flowchart is a graphical tool to represent an algorithm.
6. A rectangle symbol in a flowchart represent process.
7. A diamond symbol in a flowchart represents a loop.
8. A diamond symbol in a flowchart represents a condition.
9. Testing and debugging is an optional step in problem solving
10. A thorough analyzed problem yields a better solution.
1. Dry run and trace table are the algorithm verification tools.

12. Trace table always yields correct output.

NOTE: Answers for OTQs are given at the end of the book.

Solved Problems
. Mention the steps you would follow while writing a program.
Solution. The steps to creating a working program are

( Understand the problem well.


(i) Analyze the problem to
for output.
identify minimum number of inputs required
identify processing components.
(ii) Design the program by
solution.
breaking down solution into simple steps.
deciding step by step
(iv) Code the program by
required for solutions.
identifying arithmetic and logical operationsconditional
using appropriate control
structures such as or looping control structure.
COMPUTER SCIENCE WITH PYTHON
128 - XI

( ) Test and Debug your program by


rectifying the errors.
finding errors in it.
(vi) Complete your documentation.
(vii) Maintain your program.
2. What is an algorithm ?
Solution. An Algorithm refers to a sequence of instructions, a finite set of commands or a method.
d of
working, It can be represented as a sequence of instructions to be carried out until an end point is
is
reached as per the rules, conditions or sequence by which the computer or people tackle a problemo
situation.
3. Discuss two common tools for developing an algorithm.
Solution. Two common tools for developing an algorithm are flowchart and pseudocode.
A flowchart is a diagrammatic or pictorial/graphical representation that illustrates the sequence of
operations to be performed for the solution of a problem.
Pseudocode is an informal high-level description of a computer program or algorithm. It is written in
symbolic code in English which must be translated into a proper code using a specific programming

language.
4. What do you understand by analysing an algorithm ?
Solution. Problem analysis is an important phase as its success leads to the final solution. In problem
analysis, mainly following things are carried out:
identifying processing components.
identifying the relationships among processing components.
5. What is testing and debugging?
Solution. Testing is the process of finding errors in a program and debugging is the process of
correcting errors found during the testing process. Thus, the testing and debugging involves :
finding errors in the program. rectifying the errors, which have been found.
6. How do you implement Decomposition while problem solving?
Solution. Decomposition is implemented by dividing the main algorithm into functions. Then one
constructs each function independently of the main algorithm and other functions. Finally, the main
algorithm is constructed using the functions.
When we use the functions, it is enough to know the specification of the function without knowing
how the function is implemented.
START
7. Draw a flowchart to find the largest of three
numbers A, B, and C.
READ A, B, C
Solution.

YES IS NO YES IS YES


B> C?
A> B? A>C?
NO NO

PRINT B PRINT C PRINTA

END
5 INTRODUCTION TO PROBLEM SOLVING
Chapter
129
raflowchart to fina the sum of first 50 natural 10.
Drawa flow chart to count and print from 1 to 10.
numbers
Solution.
Solution.

START Start

SUM 0 Input Low (1),


High (10)

N0
Count Low

N=N+1

S
No
Count s High
SUM SUM+1
Yes
Print count
IO
ISN 50? Stop

YES Count Count +1


PRINT SUM

11. Write pseudocode to count and print from 1 to 10.


END Solution.
.Draw
1. INPUT Low(1), High(10)
a
flowchart for computing double factorial 2. Count = 1
ofN (N!), where N!! =Nx (N-2) x (N-4) x..x
3. WHILE (Count <= High)
(N-k);
Repeat steps 4 through 5
where k is multiple of2 and (N -k) >=1. (N is an ; PRINT Count
even number)
START 5. Count Count +1
Solution. #end of while

READ N 12. Write pseudocode to calculate the factorial of a


number (N).
Solution.
M= N
DF 1
1: Input N
2: Factor = 1

3: Counter = 1
DF DF M
4: While (Counter £ N)
Repeat steps 4 through 6
5: Factor = F a c t o r * Counter

M=M-2 SM<=1? 6: Counter = Counter +1

YES 7: Print (N, Factor)


PRINT DF

END
130 COMPUTER SCIENCE WITH
PYTHON
13. Draw a flow chart to calculate the factorial of a: 15. Write pseudocode to print Even numbers
umbers between
number (N). to 50.
Solution. Solution.
Start
12 I =1
Start
3: While I <= 50

Input N Repeat steps 4 through 5


4 IF ((I % 2) = 0) THEN

DisplayyI
Factorial = 1 #END of IF
5 I I+1
7 Stop
Counter 1
16. Write pseudocode to get a number and check
ifit is
prime.
Solution.
Is
No INPUT number
CountersN
prime<-TRUE
Yes FOR i - 2 TO number
IF number is divisible byi then
Factorial = Factorial * Counter
Print Factorial prime FALSE
IF prime =TRUE:
Counter =Counter +1| Stop PRINT "prime"
ELSE
PRINT "not prime"

17. For every


14. Draw a flowchart to print Even numbers between 1 number from 1 to 100, output Fizz if the
to 50. number is divisible by 3, output Buzz if the number
is divisible by 5, and
Solution. output FizzBuzz if the numbe
is divisible
by both 3 and 5. If none of these
conditions match, then just output the number
Start Write pseudocode to implement this.
Solution.
FOR i 1 TO 100 DO
IF i is divisible by 3 AND i is divisible by 5 then
PRINT "FizzBuzz"
Is I> 50
Yes ELSE IF iis divisible
by 3 then
PRINT "Fizz"
No ELSE IF iis divisible
by 5 then
PRINT "Buzz"
Yes ELSE
% 2 = 0)
? Print PRINT i
No tainsd
18. Dry run the algorithm given below which cona
111 simple for loop. Show the trace table.
FOR i - 1
TO 4
Stop OUTPUT i*2
# END of FOR
5:
INTRODUC CTION TO PROBLEM SOLVING 131
Chapter

Solution. Trace table

Output

19 Dry run the algorithm given below ohich contains a for loop inside another for loop. Show the trace table.
num-0

total-0

FOR i - 1 TO 3
FOR j - 1 TO 3
num-j *i
total-total + num
# END of inner FOR
# END of outer FOR
PRINT total

Solution. Trace table

num= j*i total =total +num OUTPUT


0
1

2 8

12
18

3 21

27

3 36

36

uidelines to NCERT Questions INCERT Chapter 4]

1. Write pseudocode that reads frvo numbers and divides one by another and displays the quotient.
Ans.
INPUT num1, num2
quotient num1/num2
PRINT quotient
2. Two
coin five times. 1he first person to win three
ends decide who gets the last slice of a cake by flipping a
ps oins the cake. An input of 1 means player 1 wins a flip, and a 2 means player 2 wins afip. Design an
algorithm to ermine who takes the cake ?
132 COMPUTER SCIENCE WITH PYTHON
- X

Ans. INPUT num (c) Calculate the percentage of marks.


IF num = 1 THEN Ans. INPUT cmarks, mmarks, pmarks
PRINT 'Player1 has won' total Cmarks
=
+mmarks +pmarks
ELSE IF num = 2 THEN perc (total/30e) * 100

PRINT 'Player2 has won PRINT cmarks, mmarks, pmarks


ELSE PRINT 'Ageregate ',
PRINT 'Enter 1 or 2 only'
=

total1
PRINT 'Percentage = , perc
3. Write the pseudocode to print all multiples of 5 8. Write an algorithm to find the greatest among tim
two
between 10 and 25 (including both 10 and 25). different numbers entered by the user.
Ans. FOR i in sequence 10. .25 Ans.
IF i modulus 5 = 0 THEN
INPUT num1, num2
PRINT i IF num1 > num2
#End of IF PRINT num1
#End of FOR ELSE IF num2> num1
4. Give an example of a loop that is to be executed a PRINT num2
certain number of times. ELSE
Ans. The FOR loop, can be executed a certain PRINT 'both are equal'
number of times e.g-, 9. Write an algorithm that performs the following
For i in sequence 1..5 Ask a user to enter a number. If the number is
PRINT i between 5 and 15, write the word GREEN. If the
number is between 15 and 25, write the word
5. Suppose you collecting money for something.
are
BLUE. 1f the number is between 25 and 35, write
You need 200 in all. you ask you parents, uncles
the word ORANGE. If it is any other nmumber,
and aunts as well as grandparents. Different people
write that ALL COLOURS ARE BEAUTIFUL
may give either T10, F10 or even T50. You will collect
till the total becomes 200. Write the algorithm. Ans.

Ans. Total = 0
INPUT num
IF num >= 5 and <= 15 THEN
WHTLE Total < 200
PRINT 'GREEN'
INPUT money
ELSE IF num >= 15 and <= 25 THEN
Total Total +Money PRINT 'BLUE'
#End of while
ELSE
6. Write the pseudocode to print thebill depending upon PRINT 'ALL COLOURS ARE BEAUTIFUL
the price and quantity
of am
item. Also print Bill GST,
which is the bill after adding 5% of tax in the total bill.
10. Write algorithm that accepts four numbes
an
11put and find the largest and smallest of then
Ans.
Ans.
INPUT itemname, price, qty
INPUT n1, n2, n3, n4
billamount = price * qty
IF n1> n2 and n1> n3 and n1> n4 THEN
gstamount = billamount * 0.e5
PRINT n1 'is greatest' THEN
PRINT itemname, price, billamount ELSE IF n2 > n2>
n1 and n2> n3 and n 2 >
n4
*

PRINT "GST = ", gstamount


PRINT n2 'is greatest THEN

PRINT 'Total amount = ', billamount + gstamount ELSE IF n3 > n1 and n3> n2 and n3> n*
7. PRINT n3 'is greatest'
Write pseudocode that will perform the following: ELSE IF n4> n1 and n4> n2 and n4
THEN

(a) Read the marks of three subjects Computer


PRINT n4 'is greatest'.
Science, Mathematics and Physics, out of 100.
IF n1< n2 and n1 < n3 and n1 < n4 THEN
(b) Calculate the aggregate marks.
PRINT n1 'is smallest'
ae 6 : INTRODUCTION TO PROBLEM SOLVING 133
ELSE IF n2 < n1 and n2 < n3 and n2 < n4 THEN
Ans.
PRINT n2 'is smallest'
ELSE IF n3 < n1 and n3 < n2 and n3 < n4 THEN Flowchart Symbols Functions
PRINT n3 'is smallest'
ELSE IF n4 < n1 and n4 < n2 and n4 < n3 THEN Start/Stop of the Process
PRINT n4 'is smallest'.
Data
11. Write an algorithm to display the total water bill
charges of the month depending upon the number
of units cOnsumed by the Customer as per the Process Step
followingcriteria
for the first 100 units @ 5 per unit
for next 150 units 10 per unit Decision Making
more than 250 @ 20 per unit

Ans.
INPUT units Flow of Control
250 THEN
IFunits
*
bill (units-250) 75 + 150 *
10 + 100 *
14. Following is an algorithm for going to school or
ELSE IF units > 100 THEN
bill = (units-100) * 10 + 100 * 5 college.Can you suggest improvements in this to
include other options ? Reach_School_Algorithm
ELSE
bill = units * 5
(a) Wake up (6) Get ready
(c)Take lunch box (d) Take bus
PRINT units, bill
() Get off the bus
() Reach school or college
12. What are conditionals? When they are required in;
a program
Ans. It can be modified to incorporate
situations where a different course of action is
Ans. Conditionals are the statements that test a
required, e.g., if bus is missed.
condition.
Wake up
Conditionals are required in a program where
Get Ready
the control has to take different flow-of-action Take Lunch Box
depending upon a condition's result. IF taken bus THEN
13. Match the Ride the bus
pairs
Flowchart Symbols Functions Get off the bus
ELSE #if bus missed
Flow of Control Take other means of transport
Get down at schoo1
Reach School or College.
Process Step
15. Write a pseudocode to calculate thefactorial ofa munber
(Hint. Factorial of5, written as 5! 5x4x3x2 x 1).
Start/Stop of the Process
Ans. INPUT num
F 1
WHILE num> 1
Data F F* num
num = num 11

#end of while
Decision Making PRINT F
134 COMPUTER SCIENCE WITH PYTHO
PYTHON -
16. Draw a flowchart to check whether a given number 4. Else IF Number < 99
is an Armstrong number. An Armstrong number 5. "Double Digit"
of three digits is an integer such that the sum of the 6. ELSE
cubes of its digits is equal to the number itself. For 7. "Big"
example, 371 is an Armstrong number since:
3**3+17**3+1**3 371. Lines
Number OUTPUT
Ans. Executed
NOTE
1, 2, 3
Start mod gives remainder Single Digit
9 1, 2, 4, 5
div gives quotient Double Digit
INPUT num a**b means a" 47 1, 2, 4, 5 Double Digit
99 1, 2, 4, 6, 7 Big
100 1, 2, 4, 6,
d1 num mod 10
q1 = num div 10
7
Big V

d2 q1 mod 10 200 1, 2, 4, 6, 7
q2 q1 div 10
Big
d3 = q2 mod 10
The error in given
algorithm is that it should
also test for equality i.e., as
n1 =
d3 **
3+ d2 **
3 + d1 **
3
INPUT Number
IF Number
Is
<= 9
num = n1
No "Single Digit"
ELSE IF Number
<= 99
Yes 'Double Digit"
PRINT 'not an ELSE
Armstrong number
PRINT "Big"
'Armstrong number
18. For calculations, we want an algorithmt
some that
accepts only positive integers upto 100.
Stop Accept 1to100_Algo
17. Following is an algorithm to classify numbers INPUT Number
as IF (0 =
Single Digit", "Double Digit" or "Big". Number) AND (Number <= 100)
ACCEPT
Classify_Numbers_Algo Else
INPUT Number REJECT
If Number < 9
(a) On what values will this algorithm fail ?
"Single Digit" (b) Can you
Else If Number < 99 improve the algorithm?
"Double Digit" Ans.
Else ()The given algorithm will fail at inpa
"Big" number as zero
(0).
Verify for (5, 9, 47, 99, 100, 200) and correct the (b) Corrected algorithm:
algorithm if required. INPUT Number
Ans. IF (0 < Number) AND (Number <= 100)
1. INPUT Number ACCEPT
2. IF Number < 9 ELSE
3. "Single Digit" REJECT
INTRODUCTION TO PROBLEM SOLVING
Chopter 5 :INTR
135

GLOSSARY

Graphical representation ot a problem's solution.


Flow Chart

Step wise logic ot a program in normal English.


Algorithm

Pseudocode
Logic written in English which looks like a programming language but not actually a programming language.
Testing a program with pen and paper, by tracing the impact of each statement on varidbles.
Dry Run

Assignmenfs

pe A:
Short Answer Questions/Conceptual Questions
1. What are the phases of program solving cycle?
while analysing a problem ?
2. What do you do
3. What is done during coding phase ?
4. What is testing and debugging ?
5. Distinguish between a condition and a statement.
6. Draw a flowchart for conditional statement.

7. Both conditional statement and iterative statement have a condition and a statement. How do they differ?
8. What is decomposition ?
9. Name some tools used for problem solution development.
10. What is the difference between an algorithm and a program ?

11.What is dry run ? How is it useful ?


12. What is trace table?

Type B: Application Based Question


1. Write an algorithm to find the square of a number.
2. Draw a flowchart to solve the problem of a non-functioning light bulb.

5. Draw a flowchart for calculating grade from marks percentage.


Write an algorithm to double a number in two different ways : (i) n+n, (i) 2 x n.
. Write an algorithm and draw a flowchart to determine if a student passed the exam or not.( Note there
are 4 subject papers and passing average is 50 or more.)

[Hint: Start

Step 1: Input M1, M2, M3, M4


Input M1, M2, M3, M4
Step 2: GRADE B (M1 +M2 + M3 + MA)/4
Step 3: if (GRADE < 50) then
Grade (M1 + M2+ M3 + M4)/4
Print "FAIL"

else
No
Print "PASS" Yes grade 50 «

# end of if

Print "FAIL" Print "PASS"


End
136 COMPUTER SCIENCE WITH PYTHON
-

6. Write pseudocode for the following :


(a)

START

/Read X, Y, Z

Yes No
Is X>Y?

Yes IsX>2?
No No ls Y>Z? Yes

Print 'The largest number is', Z

Print 'The largest number is', X Print The largest number is', Y

(STOP

(b)

Start

c 0 , s =0

c<5N avg = s/55


Print avg

Yes
Stop
Input num

S s+ num

CC+11

and

7 Write algorithm to display the sum of two numbers entered by user, using both pseudoco
an

flowchart.
INTRODUCTION TO PROBLEM SOLVING
Chapter5 : 137

Dea7a flowchart, write an agorithm and pseudo code for the following questions 8-24
oTo find the area and perimeter of a rectangle.
To
calculate the area and the circumference of a circle.

10, To calculate the simple interest.


To check whether a year is a leap year or not.
nTo check if a number is a positive or negative number.
13 To check if a number is an odd or even number.
14. To
specified.
categorse a person as either child ( 13), teenager (a= 13 but « 20) or adult (20), based on age

15 To print all natural numbers up to n.


print n odd numbers.
16. To
print square of number.
17. To
a

18. To accept 5 numbers and find their averapge.


19. To accept numbers till the user enters 0 and then find their average.
20. To print squares of first n numbers.
21. To print the cube of a number.
22. To print to print cubes of first n numbers.
23. To find sum of n given numbers.
24. To find factorial of a given number.

25. Given the following pseudo code:


Use variables sum, product, number1, number2 of type real
display "Input two numbers"
accept number1, number2
sum number1 + number2
print "The sum is", sum
product= number1 * number2

print "The Product is ", product


end program

Draw a flow chart for the same and dry run the given pseudocode if it is working fine.
26. Given the following pseudo code:
Use variables: choice, of the type character
ans, number1, number2, of type integer
d1splay "choose one of the following"
display "m for multiply"
display "a for add"
display "s for subtract"
accept choice
alsplay "input two numbers you want to use
accept number1, number2
f
choice m then
=
ans =
number1 *
numberz
T
choice =a then ans number1 +numberz
lt choice =
s then ans numberl number2

W
D
display ans
a flow chart for the same and dry run the given pseudocode if it is working fine.
COMPUTER SCIENCE WITH
138 THON
code
27. Given the following pseudo
Use variables: mark of type integer
"distinction"
If mark = 80, display
If mark = 60 and mark < 80, display "merit"
If mark = 40 and mark < 60, display "pass"
If mark < 40 display, "fail"
Draw a flow chart for the same and dry run the given pseudocode if it is working fine.

28. Given the following pseudo code:


Use variables: category of type character
Display "input category"
Accept category
If category "U'
Display "insurance is not available"
Else If category = 'A' then

Display "insurance is double"


Else If category 'B' then
Display "insurance is normal"
Else If category 'M' then
Display "insurance is medically dependent"
Else
Display "entry invalid"

Draw a flow chart for the same and dry run the given pseudocode if it is working fine.

29. Given the following pseudo code:


Use variable: number of type real
DISPLAY"Type in a number or zero to stop"
ACCEPT number
WHILE number 0
Square = number * number

DISPLAY "The square of the number is", square


DISPLAY "Type in a number or zero to stop"
ACCEPT number
ENDWHILE

Draw a flow chart for the same and dry run the given pseudocode if it is working fine.
CHAPTER 5 INTRODUCTION To PROBLEM SOLVING
Multiple Choice Questions
1. (a) 2. (b) 3. (b) 4. (), (d) 5. (b) 6. (c)
7. (c) 8. (a) 9. (b) 10. (a) 11. (a) 12. (d)
13. (b) 14. (a) 15. (a) 16. (d) 17. (b)

Fill in the Blanks


1. algorithm 2. Decomposition 3. pseudocode 4. flowchart 5. algorithm
6. flowcharts, pseudocode 7. space, time 8. Dry run 9. trace 10. pseudocode

True/False Questions
1. T 2. F 3. F 4. T 5. T 6. T
7. F 8. T 9. F 10. T 11. T 12. F

You might also like