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

Intro To Problem Solving CH 4

Uploaded by

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

Intro To Problem Solving CH 4

Uploaded by

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

Introduction to Problem Solving

c h a p t e r

In This Chapter
4.1 Introduction 4 _3 Designing Algorithms

4.2 Problem Solving Cycle

4.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, i.e., problem solving, i.e., analysing a problem, designing algorithms using tools like
flowcharts and pseudocode etc.. So, let us begin.

4.2 Problem Solving Cycle


Programs are not quick creations. In order to create efficient and effective programs, you
should adopt a proper problem solving methodology and use appropriate techniques.
Broadly problem solving requires four main steps :
1. Identify and analyse the problem.
2. Find its solution and Develop algorithm of the I.ANALYSIS~
solution. Analyse the 2. DESIGN
problem Find solution
3. Code the solution in a programming language. and Develop
4. Test and Debug the coded solution. (
Algorithm

And finally implement and maintain it. 4.TESTING )


Perform Testing
The above mentioned steps are four major steps in a and
problem solving cycle. Each step contains many Debugging 3. CODING
sub-steps. The aim of a problem solving cycle is to '- Coding of the
solution
create a working program for the solution.
Figure 4.1 Steps in problem solving cycle.
71
76 COMPUTER SCIENCE WITH PYTHON

Processing - WMt and how the processing would use [NOTE


inputs to produce the desired output. One must be able to Ider,
Output - the output expected from the algorithm ; the where inputs, processing ·i
objecti\.-e of the algorithm. outputs are taking place w~
an algorithm.
A Program is the expression of an algorithm in a programm ing
language.

4.3.1 Flowcharts I FLOWCHART


A flowchart is a pictorial representation of srep by step solution o~ a A flowchart is a p1
problem. A flo\\-mart not only pictorially depicts the sequence m representati on of step hy~
which instructions are carried out in an algorithm but also is used solution of a problem. ll4t
as an aid in developing algorithms. I
There are various flowchart symbols that carry different messages and are used for differti
purposes. These symbols are shown below :
Symbof Purpose
c=) Flow of

L 7
Start/Stop

Input/Output
l control symbol

-{ Annotation

Connector
DecismBox 0
Following section illustrates the working and use of flow charts along with algorithm developmenl
Writing Algorithms
We have chosen a language for algorithms that resembles our programming language Python. l.(l
us discuss certain rules for writing algorithms.
Identifiers
Identifiers are the names given to various components of a program by the programmer e.g., m
variables that hold values, to functions, modules etc.
While choosing names for identifiers, make sure that these are meaningful and not unnecessarilr
long or short names.
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 ad of assigning the value of its right-hand side to
the variable on its left Some people take liberty and use assignment operator to assign values
variables in algorithms. 10

Sequence
The steps of an algorithm are executed in the sequence of top to bottom. One after another so ste~
must be listed in the correct order.

\
SOLVING
TRODUCTION TO PROBLEM
,., 4: IN
ChOP'g
s
. /Co nd itio na l Statement
algorithm takes the fol low ing
fo
in
Seledion ditional sta tem ent
an
if co nd itio n :
A con dit i·on ••
if con sta tem ent
ent # blo ck 1 OR
sta tem els e
# blo ck 2
S2
en t
bed ded • an other if-the n-e lse sta tem
m
mo re if-then-else sta tem ent s em
be on e or
'fheremaY
sta tem ent s pictorially.
Figure 4.2 depicts conditional

true~:}-~

eme nts.
Figure 4.2 The conditional If stat

ent
Re etition _ Lo op ing Statem
called ite rat ion sta tem ent )
p A looping statement (also
ent s dep end ing up on a
lets you repeat a set of sta tem for item in seq :
ation, the for loo p an d
condition. To accomplish iter
wh ile loo p are use d.
Yes
for looping statement Next
for ite m in seq uen ce :
: St # blo ck of sta tem en ts

ent s to be rep eat ed for Sta tem ent block


St represents the set of sta tem
Wh en the sta tem ent s
each item in the sequence. Figure 4.3 (a) for loop proces
s.
in the seq uen ce, the
block gets exe cut ed for eac h ite m
for-loop sto ps. I
I
r-w hil elo op
while looping statement 1 processing
wh ile co nd itio n Fals e

St # blo ck of sta tem ent s

ent s to be rep eat ed. Th e


St represents the set of sta tem
ts the con dit ion bef ore
while ite rat ion sta tem ent tes
if the con dit ion is false
entering int o the loo p. Th us,
loop, the wh ile -lo op
~e n before ent eri ng int o the
~-------~-------•
I

will nev er get exe cut ed.


les of alg ori thm s
Let us no w con sid er som e exa mp
and flowcharting.
cessing.
Figure 4.3 (b) while loop pro
COMPUTER SCIENCE 'N
78 1
f" I 11-1
--------::-:::::;;;;;.-;;;
. ; ; - - - - - ~ f 1 t 1 ' : . J , l'
::
EXAMPLE DrowII -~' ttR1 "",nbtrs, along
O ft,ru,cluut to"""
1

Start
Willi algoritl,m in simple t,,gllsh.
SOLUTION

Algorithm
Step 1. Start
Step 2. Get two numbers Nl and N2
Step 3. S r Nl + N2
Step 4. Print the result S
Step 5. Stop

EXAMPLE Drau, a n--• ·-to findAraandPtrimtttroJRtctangle,alongwithalgorithm in


V1Lv1111, . r-
s,n,p/e
L : Lengtl, of Rtctanglc, B: Brtodth of Rectangle c11~1·.
l9i.
AREA : Arca of Rrctanglt, p£RIMET£R : Perimeter of RtclJJ
nglt Slart
SOLUTION

Algorithm
Step 1. Start
AREA=LxB
Step 2. Input Side-Length&: Breadth say Z. B
Step 3. AREA .- Lx B PERIMETER = 2 x (L + B)

Step 4. PERIMETER .- 2 x (L +B)


Print AREA, PERIMETER
Step 5. Print AREA, PERIMETER

_,~
1
EXAMPLE Draw aflowchart to convert ttmptroture from Cllsius to Fahrenhei
t along wit!, algorithm in
simple English. C : temperature in Ctlsius, F: temptrature Fahrt
nhtit
Formulas to be used :
Fahrenheit to Celsius : C = (F - 32).~; Celsius to
Fahrenheit: F =C. ! +32
9 5
SOLUTION
Algorithm
Input value of C
Step 1. Start
Step 2. Input temperature in Celsius in variable C F a 9.0/5.0 • C • 32

Step 3. F f-(9.0/5.0xQ+32
Step 4. Print Temperature in Fahrenheit F
Step 5. Stop
Chop'•' 4 : INTRODU CTION TO PROBLEM SOLVING

EXAMPLE Draw a flowchart to drtermlne tire


largn- of two numbers, along wilh algorithm in simple
English.
SOLUTION
Algorith m
Step 1. Start
Step 2, Get two number s a and b
Step 3. If a> b then print a else print b
Step 4. Stop

Draw a flow chart to print even numbers from 2 to 10 using a loop approach, along w1tlr
4
EXAMPLE
algorithm in simple English.
SOLUTION
Algorithm
Step 1. ;~2
Step 2. While i< 10
False
Repeat steps 3 through 4
Sr,, 3. Print i True

Step 4. i~i+2
Print i
Step 5. Stop

EXAMPLE I 4
Draw a flow chart to calculate 2 , along with
tdgorllhm in simple English.
SOLUTION
Algorithm
Step 1. Input Base (2), Power (4)
Product =Base
Step 2. Product Base
Step 3. Product Product "' Base Product =Product • Base

Step 4. Product Product "' Base


Product =Product • Base
Step 5. Product Product • Base

Step 6. Print Product


Product =Product • Base
Step 7. Stop
of instructions, a finite set of
-.a1iQ\15ltu: of instructions to be earn ~0tnll\a.riq
by which the computereorout llttijts llt qttc
PeoPle ~:,
t<ic~ ''l~
• ,lgorithm. q
~iJJJ·llS an algorithm are flowchart
- ilndp
ildmJllllgraphical representation that ill se\J.doc d
of aproblem. Ustrates the0 t.
li!!ICl:it''°on of a computer program
1 ted • Or algorith. \
be trans a into a proper "llll,It·
code lJf
7 lt\g I •
\
ll't'nll:meas its success leads to the final
out: solution.~11,..
r•~

rs in a program and debugging is th


• Thus, the testing and debugging in::
, rectifying the errors, which have been fo~
solving?
• • g the main algorithm into functions.~
algorithm and other functions. Finally, 11-Ei

specification of the function without~

7.
ING
O N TO PROBLEM SOLV
RODUCTI 10
4 . rNT
• of first 50 •
Chapter
th So lut ion .
hart to fin d e sum
[)r aw a flowe
B. natural numbers.
5olution.
START Inp ut Low (1),
High (10 )

Co un t= Lo w

No

Pri nt cou nt
\
i
Co unt = Co unt + 1

un t an d pr int fro m 1 to 10.


PR INT SU M
11. Write pseudocode
to co

END
So lut ion .
(l0 )
1. INPUT Lo w( l), Hi gh
factorial Co un t= 1
9_ Draw aflowc
hart for computing double 2.
(N -2 )x (N )x ... x
-4 WHILE (C ou nt <= Hi gh
)
ofN(N/!J, where N! != Nx 3.
ug h 5
(N -lc ); Re pe at ste ps 4 th ro
(N - k) >= 1. (N is an PRINT Co un t
where k is multiple of2 and 4.
Co un t = Co un t + 1
even number) START
5•
# end of wh ile
Solution.
of a
to calculate the factorial
RE AO N 12. Wr ite pseudocode
nu mb er (N).
So lut ion .
1: In pu t N
2: Fa ct or = 1
3 : Co un ter = 1
N)
4: W hil e (C ou nt er f
ug h 6
Re pe at ste ps 4 th ro
• Co un ter
5: Fa cto r = Fa ct or
te r + l
6: Co un ter = Co un
)
7: Pr in t (N., Fa ct or
COMPUTERS
CIENc:
m.
13. 0,., ,,.. . . . . --" *j,cffritl of'
15• nnte pse11doco,Je to . E Vv1l1..•1
I to 50. µr,,,t f:
..-,,x~ Solution.
tle11 I
\
I
'~~,bf,
~we>.• 1
1 Start \
2 I• 1 •
3 : While I <= 50
Repeat st
4 IF ((1'~ 2)=/P s 4th~
Displ an ) lHEN °u01.
1)111
# END of IF
5 l=I+ 1
7 Stop
16. Writt pstudocode to
• get al'llltnb
pnmt. er a,,d
Solution. ¾,,
'1
INPUT number
prime <- TRUE
FOR i <- 2 TO number
IF number is d. .
lVlSibl
. prime<- FALSE eby it~
IF prime =TRUE:
PRINT "prime"
ELSE
PRINT "not prime"

1-l 0-, 1,_.,, ,, foprinf Eta llllllf,as IJdroffll


17. Forevtry numberfrom 1 to
number is divisible by 100'output Fizl ,
l loSO. L- • 3' output 8 1
numucr IS divisible by 5 and uzz h
Sokm. tht number is divisible by' bothOU/put f"1zzBk::1
.. 3 and
thtst cond1llons match then · 5•11111:111,
. ' 111st oui...
number. Wnte pseudocode to imp/ ·r•I •
ement this.
Solution.
FOR i <-1 TO 10000
IF i is divisible by 3 ANO i is divisible bys tie
PRINT •fizzBuzz"
ELSE IF i is divisible by 3 then
PRINT •Fizz"
ELSE IF i is divisible by 5 then
PRINt"Buzz"
ELSE
PRINT i
18. Dry nm the algorithm given below which cont.if
11 simple far loop. Show the trace table.

FORi+-1 T04.
OUTPUT i*2
#ENO of FOR
NG
ION TO PROBLEM SOLVI
LITRODUCT
,,~
':

Trace tabJe
'" ""
5oh .1ti Of1 . ,--- Qu tnu t
i
,- 2
1
,- 4
2
,- 6
3
·- 4
8 ;t
- loop inside ano the r far loo
p. S1u:n,
. below which contains a for
the algorithm given
o,y ru n
J9. num +- 0
to ta l 4--0
FOR i +- 1 TO 3
FOR j +- 1 TO 3
nu m+ -j • i
to ta l +- to ta l + num
# END of inn er FOR
# END of ou ter FOR
PRINT to ta l
Trace ta ble OU TP UT
Solution. tot al = tot al + nu m
I nu m= J,. I
I 0
0
1
1 1
1 3
2 2
3 6
3
2 8
2 1
4 12
2
6 18
3
3 21
3 1
6 27
2
9 36
3
36

q_• i e I i n e s I o N CE RT Q
u esI i o n s [NCERT Chapter 4j

.
. s and divides one by another and displays
tlze quofi('11f.
ds number
1. Write pseudocode that ·,;a
two
Ans.
INPUT nu ml, num2
qu oti en t numl/num2
PRINT qu oti en t
st pcf':'.(111 to u•irl t'1rtY
ping a coin jiz,r! times. The fir
1s a p,;,. Dl~i~11 a11
s the last slice of a cake by flip
2. Two frie11ds decide who get player 1 wi ns a flip, a11d a 2 mea11s player 2 u•i1
flips wins the cake. An input of 1 means e ?
algorithm to determ ine wlzo takes the cak
COMPUTER SCIENc

---
E'i¥1t~
(c) Calculate the perce,ita \
Ans. INPUT cmarks
ge Of %rks '1
,
If-•111111 1115111111' , rnn,a"k .
total = cmarks s' P111 Cl
- •p)Jyll'l
BSE If ,_ • 2118 • perc = (total/3i- lllrna"ks s
00) ,.. i- ti..
PllN1' 'Pl1Je1'21115 MDII PRINT cmarks """ lee n,~\
PRINT , ' "•11a"ks
Aggregat : , ' P111a
ELSE •enter 1 ar 2 only' PRINT 'Percent e , tot
:
,_ . ,. _,q,ltso/5 age : : , al
8. Write an algorithm to find ' Pe~c
Wnlr • ,- I ;zt • prid116 IO_, 25~ th
Jt "'1S r..wwi different numbers entered b e gre111e
ldaaRlli11_.ICl11 ••25 Y the ltser.51 Q\·t,
Ans.
-. _.,,,,.., 5 I 11111 INPUT num1, num2
I

lft--
PIDIU IF numl > num2
....,If PRINT num1
IWaffm · ELSE IF num2 > num1
J a->61f is ID frumrdm a PRINT num2
r... aaplr '"J,..,.
ELSE
artlit...-,fli aa .
ML The D blp. all b!talJded I mtain PRINT 'both are equal,
llllllber mtims ,.,. • Write an algorithm that Perro
1• r111s the fi
Ask a user to enter a number If o/fo.,t:..
bttwe 5 d 15 • the u, • d lire 11~~,1

.....
en an , wrzte 0
s..,.,- number is between 15 and 2; G~tfN f

,....,
r• • m BLUE. If the number is behveen, lVr1te I~ .::-

...,,.
25
the word ORANGE. If it is any ~;d 35,1~
0
write that ALL COLOURS ARE BEA~n~
Ans.
A11L Total• INPUT num
lllllE IF num >= 5 and <= 15 THEN
PRINT GREEN
I I

ELSE IF num >= 15 and <= 25 THEN


PRINT I BLUE I
ELSE
Li,~.,. .
I lhtl'ria• PRINT 'ALL COLOURS ARE BEAUTIFUL'
rdidr;, lht,,,, rite an algorithm that accepts four 1111mhfr:1
Ans. t and find the largest and smallest of thn
ItflUT 1
billMount • IJIIUJ' nl, n2, n3, n4
gstaaount • IF n1 >n2 and nl > n3 and nl >n4 THEN
PRINT it , PRINT nl 'is greatest' •
PRINT •GST • •, ISt-111 ELSE IF n2 > nl and n2 > n3 and >n4 lll!I
ni
PRINT 'Total ai11.nt ', PRINT n2 'is greatest' 1lll
• Write pseudoaJdt th/It fDill ELSE IF n3 > nl and n3 > n2 and n3 >n4
PRINT n3 'is greatest' ""
(a) Read the marts of thrtt
ELSE IF n4 > nl and n4 > 02 and n4 >n3 ,,.,
Science, Mtzthematic, """P.
PRINT n4 • is greatest' · EN
(b) Calcul,tt the aggrtglllt 1tlll1k,. lF nl <n2 and nl < n3 d
an n l<n4TH
PRINT nl 'is smalleSt '
SOLVING
ou CT IO N TO PROBLEM
. 1NTRO
tioP1•' ' • Ans.
n2 < n4 THEN
nl and n2 < n3 and
I.Sf IF n2 < • is sm all es t•
' E RINT n2 n3 < n4 THEN
p 3 < nl and n3 < n2. and
el.SE IF n t
PRINT n3 • is sm all es and n4 < n3 THEN
n4 < nl and n4 < n2,
el.SE I F
PRINT n4 •is sm all es
t •

oritlun to displa.y the tot


al water bill II
/ 7
lg b
Wriltesanofathe month dependmg upon the nu m er i
r the i I
c}ulrg . consumed
by the customer as pe i I
of units . . . . l
lloWing cntena • t ! Decision M ak ing
fa its @ 5 pe r uru
• for the first 100 un !I
pe r un it
for next 1.50 un its @ 10 . i
:II
re tha n 0@ 20 pe r urut
II sno 2.5

AnS-
Ii Flow of Control

INPIJT un its
i school or
IF un its > 25 0 THEN • 75 + 15 0 • 10 + 10
0• 5 ng is an algorithm for going to
bi ll . (u nit s-2 50 ) i 14 . Fo llo wi
ements in this to
TH EN col lege. Can yo u suggest improv
ELSE IF un its
bi ll • (u
>
ni
10
ts-
0
10 0) • 10 + 10 0• 5
I :
i
inc lud e oth
(a) W ak e up
er options ? Reach_School_
(b) Ge t re ad y
Algoritlun

ELSE Ta ke bu s
bi ll • un its • 5 i (c) Ta ke lu nc h bo x (d)
PRINT un its , bi ll
! (e) Ge t of f the bu s
!: llege
ed in (j) Reach sc ho ol or co
di fie d to in co rp or ate
Wh en the y are req uir
u. What are conditionals ? An s. It ca n be mo se of ac tio n is
a pro gra m? t a . sit ua tio ns wh er e a dif fer en t co ur
Ans. Conditionals are
th e sta tem en ts th at tes req uir ed , e.g., if bu s is
mi ss ed .
I
condition. Wake up
req uir ed in a pr og ra m wh er e 1
Conditionals are ! Get Ready
e dif fer en t flo w- of- action
the control ha s to tak ult . ! Take Lunch Box
iti on 's res
depending up on a co nd I IF tak en bu s THEN
1 Ri de th e bu s
13. Match the pairs
Functions Ge t of f th e bu s
Flowchart Symbols #i f bu s mi ss ed
ELSE
tra ns po rt
Flow of Control Ta ke ot he r means of
Ge t down at sc ho ol

17
lle ge .
Reach Sc ho ol or Co
Process Step efa n11111."t7
15. W~ te a p se u ~ to calculate the factorial
itt en as 5! = Sx 4x 3x 2
>< J).

EJ
(Hmt. Factorial of5, wr
Start/Stop of the Process An s. INPUT num
F=1
WHILE num > 1
Data
F = F • num
num = num - 1
#e nd of wh ile
Decision Making
PRINT F
fo11owin8:
6. Wrftt ~ ~ d i e
(•)

ReadX. Y,Z

No

rint 'The

Print avg

7. Write an algorithm entered by user, using both pseudJ


flowchart.

!
Chapte r 4 : INTRO DUCTIO N TO PROBLE M SOLVIN G

Draw a flowch art, write an algori thm and pseud o code far..
8. To find the area and perime ter of a rectang le.
9. To calcula te the area and the circum ferenc e of a circle.
10. To calcula te the simple interes t .
11. To check wheth er a year is a leap year or not.
12. To check if a numbe r is a positiv e or negati ve numbe r.
13. To check if a numbe r is an odd or even numbe r.
but< 20) or
14. To catego rise a person as either child (< 13), teenag er(>= 13
specified.
15. To print all narura l numbe rs up to n.
16. To print n odd numbe rs.
17. To print square of a numbe r.
18. To accept 5 numbe rs and find their averag e.
averag e.
19. To accept numbe rs till the user enters O and then find their
20. To print square s of first n numbe rs.
21. To print the cube of a numbe r.
22. To print to print cubes of first n numbe rs.
23. To find sum of n given numbe rs.
24. To find factori al of a given numbe r.

25. Given the follow ing pseudo code :


Use variab les sum, produ ct, numberl, number2 of type real
displa y "Inpu t two numbers"
accep t numbe rl, number2
sum = numberl + number2
print "The sum is", sum
produ ct = numberl • number2
print "The Produ ct is ", produ ct
end program
if it is workin g fine.
Draw a flow chart for the same and dry run the given pseudocode
26. Given the follow ing pseudo code :
Use variab les: choice., of the type chara cter
ans, numberl., number2., of type integ er
displa y "choose one of the follow ing"
displa y "m for multi ply"
displa y "a for add"
displa y "s for subtr act"
accep t choice
displa y "inpu t two numbers you want to use"
accep t numbe rl, number2
i f choice = m then ans = numberl • number2
1f choice = a then ans = numberl + number2
if choic e= s then ans = numberl - number2
display ans
it is working fine.
Draw a flow chart for the same and dry run the given pseudocode if

You might also like