POA -solid coverage
POA -solid coverage
1.1 ALGORITHM
An algorithm is defined as a step by step procedure for solving a problem. It is a ordered set
of rules to solve a problem. An algorithm is a representation of a solution to a problem. It is a well-
defined computational procedure consisting of a set of instructions that takes some value or set of
values, as input, and produces some value or set of values, as output.
Algorithm
Input A step by step method Output
for solving a problem
Definiteness
Instruction must be clear, user defined & Precise. There should not be any ambiguity.
Input
An algorithm has zero or more, but only finite number of inputs, zero inputs. Eg: ASCII
character of 0-225.
1.2 Problem Solving and Python Programming
Output
An algorithm has one or more output.
Effectiveness
An algorithm should be effective that means each of the operation to be preformed in
algorithm should be computer programming language independent.
Uniqueness
Result or each steps are uniquely defined and only depend on the input and result of the
preceding steps.
Generality
Algorithm should apply to set of input, rather than single input.
Feasibility
It must be possible to perform each instructions.
1.2.2 State
Stored data are regarded as part of the internal state of the entity performing the algorithm.
The state is stored in one or more data structures. For such computational process, the algorithm must
Algorithmic Problem Solving 1.3
be rigorously defined and it must be specified in the way that it applies in all possible circumstances.
Data Structure specify the arrangement of data in a particular format.
1.2.4 Function
A function is a sequence of instructions that perform a task, bundled as a unit. Functions
can accept input arguments and produce output values. A function in Python is defined by using the
keyword def, after which the name of the function follows, terminated by a pair of braces (which
may or may not contain input parameters) and, finally, a colon (:) signals the end of the function
definition line. Immediately afterwards, indented by four spaces, we find the body of the function,
which is the set of instructions that the function will execute when called.
Sequence Structure
This is the most common form of control structure. Each statement in the program is
executed one after another in the given order. The flow of sequence structure is shown in Figure.1.1.
Statement 1
Statement 2
Statement n
Selection Structure
The selection control structure is the presentation of a condition and the choice between two
(or sometimes more) actions. The choice made depends on whether the condition is true or false. It is
also called a decision, one of the three basic logic structures in computer. This structure is sometimes
referred to as an if-then-else because it directs the program to perform in this way: If Condition A
is True then perform Action X else perform Action Y. The flow of sequence structure is shown in
Figure.1.2.
True False
Algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
Iteration Structure
The iterative process is also called as repetition or looping. It carries out a particular action
over and over again until some condition is met. A loop is created to return the program to where
the repetition has started for as long as it takes until the condition is met.
1.6 Problem Solving and Python Programming
There are two ways of testing to see if the condition is met: pre-test loops, and post-test
loops. In pre-test loops, the condition is tested at the beginning of the loop. If the condition fails,
the looping process will never carried out. Here the loop is operated only when condition is met.
Pre-test loop ends when the condition fails.
Post-test loops test the condition at the end of the loop. The looping process is executed
first whether the condition is true or false and will keep repeating until the condition is met. This
loop ends when the condition is true. The structures of pre-tested and post-tested loops are shown
in Figure.1.3.
True False
False
True
1.3.1 PSEUDOCODE
Pseudocode (pronounced SOO-doh-kohd) is a kind of structured English for representing
algorithms and is a “text-based” detail design tool for human understanding rather than machine
understanding. It allows the designer to concentrate on the logic of the algorithm without worrying
about the details of language syntax.
Once the pseudo code is prepared, it is rewritten using the syntax and semantic rules of a
programming language.
Sequence
It is indicated by writing one statement after another, each statement on a line by itself, and
all statements aligned with the same indent. The actions are performed in the order in which they
are written, from top to bottom.
Common Keywords
Input: READ, INPUT, OBTAIN, GET
Output: PRINT, OUTPUT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP
Examples
(i) Pseudo code for computing the area of a rectangle.
READ height of rectangle
READ width of rectangle
COMPUTE area as height times width
PRINT area
Selection
It is a decision (selection) in which a choice is made between two alternative courses of
action and it comprises of the following constructs:
•• IF-THEN-ELSE
•• CASE...ENDCASE
IF-THEN-ELSE
Binary choice on a given Boolean condition is indicated by the use of four keywords:
◦◦ IF, THEN, ELSE, and ENDIF.
The ELSE keyword and “sequence 2” are optional. If the condition is true, sequence 1 is
performed, otherwise sequence 2 is performed.
Examples
(i) Pseudo code to check whether the number is odd or even.
READ number
IF number MOD 2 = 0 THEN
DISPLAY “Number is Even”
ELSE
DISPLAY “Number is Odd”
ENDIF
(ii) Pseudo code to check whether the given non-zero number is positive or negative.
READ number
IF num is less than 0 THEN
PRINT num is negative
ELSE
PRINT num is positive
ENDIF
1.10 Problem Solving and Python Programming
CASE
CASE is a multiway branch (decision) based on the value of an expression. CASE is a
generalization of IF-THEN-ELSE. Four keywords, CASE, OF, OTHERS, and ENDCASE, and
conditions are used to indicate the various alternatives.
CASE expression OF
condition 1 : sequence 1
condition 2 : sequence 2
...
condition n : sequence n
OTHERS:
default sequence
ENDCASE
The OTHERS clause with its default sequence is optional. Conditions are normally numbers
or characters indicating the value of “expression”, but they can be English statements or some other
notation that specifies the condition under which the given sequence is to be performed. A certain
sequence may be associated with more than one condition.
Examples
(i) Pseudo code for simple calculator
READ n1, n2
READ choice
CASE choice OF
+ : PRINT n1+n2
– : PRINT n1-n2
* : PRINT n1*n2
/ : PRINT n1/n2
ENDCASE
B : gradepoint = 8
C : gradepoint = 7
D : gradepoint = 6
E : gradepoint = 5
U : gradepoint = 0
ENDCASE
DISPLAY gradepoint
Repetition
It is a loop (iteration) based on the satisfaction of some condition(s). It comprises of the
following constructs:
•• WHILE...ENDWHILE
•• REPEAT...UNTIL
•• FOR...ENDFOR
WHILE...ENDWHILE
It is a loop (repetition) with a simple condition at its beginning. The beginning and ending
of the loop are indicated by two keywords WHILE and ENDWHILE.
The loop is entered only if the condition is true. The “sequence” is performed for each
iteration. At the conclusion of each iteration, the condition is evaluated and the loop continues as
long as the condition is true.
Examples
(i) Pseudo code to print the numbers from 1 to 100.
n=1
WHILE n is less than or equal to 100
DISPLAY n
INCREMENT n by 1
ENDWHILE
1.12 Problem Solving and Python Programming
(ii) Pseudo code to print the sum of the digits of a given number
INPUT a Number
INITIALIZE Sum to zero
WHILE Number is not zero
COMPUTE Remainder by Number Mod 10
ADD Remainder to Sum
DIVIDE Number by 10
ENDWHILE
PRINT Sum
REPEAT...UNTIL
It is a loop with a simple condition at the bottom. This loop is similar to the WHILE loop
except that the test is performed at the bottom of the loop instead of at the top. Two keywords,
REPEAT and UNTIL are used.
The “sequence” in this type of loop is always performed at least once, because the test
is peformed after the sequence is executed. At the conclusion of each iteration, the condition is
evaluated, and the loop repeats if the condition is false. The loop terminates when the condition
becomes true.
Examples
(i) Pseudo code to print the numbers from 1 to 100.
n=1
REPEAT
DISPLAY n
INCREMENT n by 1
UNTIL n is greater than 100
(ii) Pseudo code to print the sum of the digits of a given number
INPUT a Number
INITIALIZE Sum to zero
Algorithmic Problem Solving 1.13
REPEAT
COMPUTE Remainder by Number Mod 10
ADD Remainder to Sum
DIVIDE Number by 10
UNTIL Number is zero
PRINT Sum
FOR...ENDFOR
FOR is a “counting” loop. This loop is a specialized construct for iterating a specific number
of times, often called a “counting” loop. Two keywords, FOR and ENDFOR are used.
Examples
(i) Pseudo code to print the numbers from 1 to 100.
FOR n=1 to 100
DISPLAY n
ENDFOR
(ii) Pseudo code to input ten numbers and print the sum.
INITIALIZE sum to 0
FOR n=1 to 10
INPUT number
COMPUTE sum as sum+number
ENDFOR
DISPLAY sum
Nested Constructs
The constructs can be embedded within each other, and this is made clear by use of indenting.
Nested constructs should be clearly indented from their surrounding constructs.
Examples
(i) Pseudo code to find the smallest among three numbers using nested IF construct.
READ the three numbers a, b, c.
1.14 Problem Solving and Python Programming
Invoking Subprocedures
To call subprocedures (functions), CALL keyword is used with the following structure:
Examples:
CALL SumAndAvg WITH NumberList
◦◦ Calls a function SumAndAvg with NumberList as an argument. This function does
not return any value.
Algorithmic Problem Solving 1.15
1.3.2 Flowchart
Flowchart is a diagrammatic representation of an algorithm or a stepwise process, showing
the steps as boxes of various kinds, and their order by connecting these with arrows. Flowcharts
are used in designing or documenting a process or program. In other words, a flow chart, or flow
diagram, is a graphical representation of a process or system that details the sequencing of steps
required to create output. A flowchart is a picture of the separate steps of a process in sequential
order.
1.16 Problem Solving and Python Programming
Flowchart is very helpful in writing program and explaining program to others. Flowchart
makes us to understand the problem unambiguously. It is often used by programmer as a program
planning tool for organizing a sequence of step necessary to solve a problem by a computer.
GUIDELINES
The following are some guidelines in flowcharting:
(a) In drawing a proper flowchart, all necessary requirements should be listed out in logical
order.
(b) The flowchart should be clear, neat and easy to follow. There should not be any room for
ambiguity in understanding the flowchart.
Algorithmic Problem Solving 1.17
(c) The usual direction of the flow of a procedure or system is from left to right or top to
bottom.
(d) Only one flow line should come out from a process symbol.
or
(e) Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, should leave the decision symbol.
=0 =0
(f) Only one flow line is used in conjunction with terminal symbol.
(g) Write within standard symbols briefly. As necessary, you can use the annotation symbol
to describe data or computational steps more clearly.
(h) If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. Avoid the intersection of flow lines if you want to make it more
effective and better way of communication.
(i) Ensure that the flowchart has a logical start and finish.
(j) It is useful to test the validity of the flowchart by passing through it with a simple test
data.
sum ← a+b
Display sum
stop
Algorithmic Problem Solving 1.19
Calculate discriminant
D←b-4ac
True is False
D ≥ 0?
x1←rp+j ip
x1← rp-j ip
Display r1 and r2
Stop
fterm←0, sterm←1
is False
sterm ≤ 1000?
True
Display sterm
temp←sterm
sterm←sterm+fterm
Stop
fterm←temp
1.20 Problem Solving and Python Programming
Fig Programming
and clarify the doubts after leading the problems description. Correct algorithm should
work for all possible inputs.
•• Ascertaining the capabilities of a computational Device: The second step is to
ascertain the capabilities of a machine. The essence of von-Neumann machines
architecture is captured by RAM, Here the instructions are executed one after another,
one operation at a time, Algorithms designed to be executed on such machines are called
sequential algorithms. An algorithm which has the capability of executing the operations
concurrently is called parallel algorithms. RAM model doesn’t support this.
•• Choosing between exact and approximate problem solving: The next decision is
to choose between solving the problem exactly or solving it approximately. Based on
this, the algorithms are classified as exact and approximation algorithms. There are
three issues to choose an approximation algorithm. First, there are certain problems like
extracting square roots, solving non-linear equations which cannot be solved exactly.
Secondly, if the problem is complicated it slows the operations. E.g. traveling salesman
problem. Third, this algorithm can be a part of a more sophisticated algorithm that
solves a problem exactly.
•• Deciding on data structures: Data structures play a vital role in designing and analysing
the algorithms. Some of the algorithm design techniques also depend on the structuring
data specifying a problem’s instance. Algorithm + Data structure = Programs
•• Algorithm Design Techniques: An algorithm design technique is a general approach
to solving problems algorithmically that is applicable to a variety of problems from
different areas of computing. Learning these techniques are important for two reasons,
First, they provide guidance for designing for new problems. Second, algorithms are
the cornerstones of computer science. Algorithm design techniques make it possible to
classify algorithms according to an underlying design idea; therefore, they can serve as
a natural way to both categorize and study algorithms.
•• Methods of specifying an Algorithm: A Pseudocode , which is a mixture of a natural
language and programming language like constructs. Its usage is similar to algorithm
descriptions for writing psuedocode there are some dialects which omits declarations of
variables, use indentation to show the scope of the statements such as if, for and while.
Use → for assignment operations, (//) two slashes for comments. To specify algorithm
flowchart is used which is a method of expressing an algorithm by a collection of
connected geometric shapes consisting descriptions of the algorithm’s steps.
•• Proving an Algorithm’s correctness: Correctness has to be proved for every algorithm.
To prove that the algorithm gives the required result for every legitimate input in a finite
amount of time. For some algorithms, a proof of correctness is quite easy; for others
it can be quite complex. A technique used for proving correctness s by mathematical
induction because an algorithm’s iterations provide a natural sequence of steps needed
for such proofs. But we need one instance of its input for which the algorithm fails.
If it is incorrect, redesign the algorithm, with the same decisions of data structures
Algorithmic Problem Solving 1.23
design technique etc. The notion of correctness for approximation algorithms is less
straightforward than it is for exact algorithm. For example, in gcd (m,n) two observations
are made. One is the second number gets smaller on every iteration and the algorithm
stops when the second number becomes 0.
•• Analysing an algorithm: There are two kinds of algorithm efficiency: time and space
efficiency. Time efficiency indicates how fast the algorithm runs; space efficiency
indicates how much extra memory the algorithm needs. Another desirable characteristic
is simplicity. Simper algorithms are easier to understand and program, the resulting
programs will be easier to debug. For e.g. Euclid’s algorithm to fid gcd (m,n) is simple
than the algorithm which uses the prime factorization. Another desirable characteristic
is generality. Two issues here are generality of the problem the algorithm solves and
the range of inputs it accepts. The designing of algorithm in general terms is sometimes
easier. For eg, the general problem of computing the gcd of two integers and to solve
the problem. But at times designing a general algorithm is unnecessary or difficult or
even impossible. For eg, it is unnecessary to sort a list of n numbers to find its median,
which is its [n/2]th smallest element. As to the range of inputs, we should aim at a range
of inputs that is natural for the problem at hand.
•• Coding an algorithm: Programming the algorithm by using some programming
language. Formal verification is done for small programs. Validity is done thru testing
and debugging. Inputs should fall within a range and hence require no verification. Some
compilers allow code optimization which can speed up a program by a constant factor
whereas a better algorithm can make a difference in their running time. The analysis
has to be done in various sets of inputs. A good algorithm is a result of repeated effort
& work. The program’s stopping / terminating condition has to be set. The optimality
is an interesting issue which relies on the complexity of the problem to be solved.
Another important issue is the question of whether or not every problem can be solved
by an algorithm. And the last, is to avoid the ambiguity which arises for a complicated
algorithm.
who finds a way to solve the problem. The developer must create an algorithm that will solve the
client's problem.
min= numbers[0]
True
No
if i<min
Yes
min= i
Stop
•• Start with an empty left hand and cards face down on the table.
•• Then remove one card at a time from the table and Insert it into the correct position in
the left hand.
•• To find a correct position for a card, we compare it with each of the cards already in the
hand from left to right.
1.26 Problem Solving and Python Programming
Once the position is found, the cards from that position are moved to the next higher indexed
position and in that order.
Algorithm
1. Start
2. Ask for value to insert
3. Find the correct position to insert, If position cannot be found ,then insert at the end.
4. Move each element from the backup to one position, until you get position to insert.
5. Insert a value into the required position
6. Increase array counter
7. Stop
Pseudo Code
READ the list of sorted cards
READ newcard
SET pos to 0
WHILE (pos < numberOfCards) and (CARDS [pos] <= newcard)
INCREMENT pos
ENDWHILE
IF pos < numberOfCards then
INCREMENT numberOfCards by 1
FOR counter = last position used to pos by -1
SET CARDS [counter + 1] to array CARDS [counter]
ENDFOR
ENDIF
SET CARDS [pos] to newcard
Algorithmic Problem Solving 1.27
position=1
No
position<length
Yes
location = position
No location > 0
position=position+1 && cards [location] <
cards [location-1]
Yes
location= location-1
Stop
Algorithm:
Step 1. Generate a random number in between 1 and 100.
Step 2. Prompt the user for a guess number.
Step 3. Determine if the guessing number is
Step 3. (a). Equal to the random number: If it is, output a message that says the guessing is
correct and go to step 4.
Step 3. (b). Less than the random number: If it is,
(i) Output a message “Too low,”
(ii) Ask if the user wants to continue the game. If yes, ask for another guess
number; otherwise go to step 4.
Step 3. (c). Greater than the random number: If it is,
(i) Output a message “Too high,”
(ii) Ask if the user wants to continue the game. If yes, ask for another guess
number; otherwise go to step 4.
Step 4. Stop.
1.28 Problem Solving and Python Programming
Yes No Yes
Does Is
guess=num guess>num?
No
Yes
End
Algorithmic Problem Solving 1.29
Rules to be followed:
•• Only one disk can be moved among the towers at any given time.
•• Only the “top” disk can be removed.
•• No large disk can sit over a small disk.
2 DISKS
A B C
A B C A B C A B C
Start
Declare n
End
Algorithmic Problem Solving 1.31
n=1
?
Return
Algorithm:
Step 1: Set max to 0 and min to 0.
Step 2: For each number x in the list L, compare it to max.
Step 2.a: If x is larger, set max to x. Else set min to x
Step 3: Display max and min
Step 4: Stop
Initialize X< 0
Increment X by 1
Print X
Yes
X < 20
No
End
Read F
C = 5/9*(F-32)
Print C
End
1.34 Problem Solving and Python Programming
Input N
Remainder = N
Modulo 2
Yes No
Remainder = 0?
Output
Answer
End
Input M1,
M2m M3, M4
Grade =
(M1+M2+M3+M4)/4
Yes No
If Grade < 60
End
Algorithmic Problem Solving 1.35
Terminal
Disadvantages:
•• It cannot be prepared for difficult programs
•• Alterations and modifications cannot be done easily
Disadvantages:
•• It is not visual.
Algorithmic Problem Solving 1.37
13. Develop an algorithm and draw the flowchart to get marks for 3 subjects and declare the
result. If the marks >= 35 in all the subjects the student passes else fails.
Algorithm:
1. Start.
2. Declare three variables m1, m2, m3.
3. Read marks of three subjects m1, m2, m3.
4. If m1 >= 35 goto step 5 else goto step 7
5. If m2 >= 35 goto step 6 else goto step 7
6. If m3 >= 35 print Pass. Goto step 8
7. Print fail
8. Stop
1.38 Problem Solving and Python Programming
Flowchart:
Start
m1 = m2 = m3 =0
No
M1>=35
Yes
No
M2>=35
Yes
No
M3>=35
Yes
Stop
14. Develop an algorithm and draw the flowchart to compute average of three numbers.
Algorithm:
1. Start
2. Read numbers a,b,c
3. Compute the average as (a+b+c)
4. Print average
5. Stop
Flowchart:
Start
Read a, b, c
avg =(a+b+c)/3
Print avg
Stop
Algorithmic Problem Solving 1.39
15. Draw the flowchart for following: read age of a person. If age less than 60 then print “Not
a senior citizen” otherwise print “Senior Citizen”.
Start
Read Age
Yes
Print Not a
Age < 20 senior citizen
No
Print
senior citizen
Stop
Start Stop
Processing
Terminal Symbols