Unit I Algorithmic Problem Solving
Unit I Algorithmic Problem Solving
Unit I Algorithmic Problem Solving
1.1 ALGORITHM
An algorithm is a procedure (or) a set of instruction for solving a problem, based
on conducting a sequence of actions.
1.2.1 Statements:
A statement can be termed as a single instruction/operation in an algorithm which
performs exactly single task.
An algorithm is a series of specific steps (statements) which solve a particular
problem.
Example:
Most algorithms have parts:
Description of problem
Set up
Parameters
Execution
Conclusion
The Simple example to find the sum of two numbers:
Description of problem: To find the sum of two numbers.
Set up: Two numbers required for addition and one variable for storing the results.
Parameters:
o Read 1st Number.
o Read 2nd Number.
Execution: Calculate the sum of the two numbers
Result= a + b
Conclusion: The desired result is sum.
Example:
Algorithm to convert Centigrade to Fahrenheit
Example 2:
Algorithm to find student grade system
Step 1 : Start
Step 2 : Read marks
Step 3 : If marks >= 80 then grade =A, go to step 7
Step 4 : If marks >= 60 and marks <=80 then grade = B, go to step 7
Step 5 : If marks >=40 and marks <=60 then grade = C go to step 7
Step 6 : Else Display failed
Step 7 : Display grade.
Step 8 : Stop.
In Repetition one or more steps are performed repeatedly. This logic is used for
producing loops in program logic, when one or more instructions may be executed
several times.
Repetition statements are also called loops, and are used to repeat the same code
multiple times in succession.
The number of repetitions is based on criteria defined in the loop structure, usually a
true/false expression
The three loop structures are:
while loops
do-while loops
for loops
Example:
Read numbers and add them up until their total value reaches or exceeds a set value
represented by n
Step 1: WHILE (total < n)
Step 2: DO
Step 3: Read number
Step 4: Total = total + number
END DO
Step 5: Print total
1.2.5 Functions:
For complex problems our goal is to divide the task into smaller and simpler tasks
during the algorithm design.
A function is a group of statements that together perform a task.
A function is a block of organized, reusable code that is used to perform a single,
related action.
Functions provide better modularity for our application and a high degree of code
reusing.
Example:
Algorithm to find maximum number of an array
Step 1: Get a list of numbers L1,L2,L3….LN
Step 2: Set max = L1
Step 3: Take each element Li from the list and do the following
1.3 NOTATION
1.3.1 Pseudocodes-Introduction
Pseudo code is an informal way of programming description that does not require any
strict programming language syntax. It is used for creating an outline or a rough draft
of a program.
“Pseudo” means imitation; “Code” means set of instructions.
Example
A pseudocode to add two numbers and display the results:
READ num1,num2
Result=num1+num2
WRITE result.
Example
READ name, grossPay, taxes
IF taxes > 0
no
Pseudocode :
IF amount < 100
interestRate = .06
ELSE
Interest Rate = .10
ENDIF
Flowchart Rules
Flowchart is generally drawn from top to bottom
All boxes of flowchart must be connected with arrow.
Only one flow line should come out from a process symbol.
Flowchart must have start and end symbol.
All flowchart start with a Terminal or Process symbol.
Decision symbol have 2 exit points, one for YES (TRUE) and another for NO
(FALSE).
Example
Add 10 and 20
To solve this problem we will take a variable sum and set it to zero. Then we will take
the two numbers 10 and 20 as input. Next we will add both the numbers and save the result in
the variable sum i.e., sum = 10 + 20. Finally, we will print the value stored in the variable
sum.
Algorithm (in simple English)
Initialize sum = 0 (PROCESS)
Enter the numbers (I/O)
Add them and store the result in sum (PROCESS)
Print sum (I/O)
Flowchart
class
class Triangle
Triangle {{
...
...
float
float surface()
surface()
return
return b*h/2;
b*h/2;
}}
Low-level program
LOAD
LOAD r1,b
r1,b
LOAD
LOAD r2,h
r2,h
MUL
MUL r1,r2
r1,r2
DIV
DIV r1,#2
r1,#2
RET
RET
Executable Machine code
0001001001000
0001001001000
1010010010011
1010010010011
1011001010110
1011001010110
1001...
1001...
1.3.5.3 What Are the Types of Programming Languages
First Generation Languages
Second Generation Languages
Third Generation Languages
Fourth Generation Languages
Fifth Generation Languages
Characteristics of an Algorithm:
Precision – the steps are precisely stated (defined).
Uniqueness – results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
Finiteness – the algorithm stops after a finite number of instructions are executed.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.
The next decision is to choose between solving the problem exactly or solving it
approximately. Based on this, the algorithm is classified as exact and approximation
algorithms.
There are three reasons to choose an approximation algorithm.
i. There are important problems that simply cannot be solved exactly for most
of their instances;
Ex: Extracting square roots, solving nonlinear equations and evaluating
definite integrals.
ii. Available algorithms for solving a problem exactly can be unacceptably
slow because of the probem’s intrinsic complexity.
iii. An Approximation algorithm can be a part of a more sophisticated algorithm
that solves a problem exactly.
Design an algorithm
Prove Correctness
1.5.2 Recursion:
A recursive function is one that calls itself again and again. It is used to call the same
function repeatedly.
Recursion splits a problem into one or more simpler versions of itself.
Example: Factorial of a number, Fibonacci series
Factorial Function:
factorial(n):
if (n==0):
return 1
else:
return n*factorial(n-1)
Flowchart
Start
min=L1
F If
min>Li
min=Li
UNIT I /Algorithmic
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] Problem Solving
Pseudocode
READ the numbers in the list Li
ASSIGN min=L1
FOr each element Li in the list, do the following
IF min>Li THEN
min=Li
REPEAT the above step until the last element
PRINT min as minimum value
Program
def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))
Output:
-8
Algorithm
STEP 1: Start
STEP 2: Read the list of ‘n’ sorted cards L
STEP 3: Get a new card
STEP 4: If new card is a number then
Compare the numbers in the list and place in the right order.
Else if new card is a role then
Compare Jack, Queen and King order and place in the right order.
STEP 5: Stop
Flowchart
Start
Stop
Pseudocode
READ the list of ‘n’ sorted cards L
GET a new card
IF new card is a number THEN
COMPARE the numbers in the list and place in the right order
ELSE IF new card is a role THEN
COMPARE Jack, Queen and King order and place in the right order.
Algorithm
Step 1: Start
Step 2: Read the limit L
Step 3: Generate a Random number (r) between 1 and L
Step 4: Guess an integer number n between 1 and L.
Step 5: If n==r then
Flowchart
Start
T F
If n==r
T F
If n<r
Pseudocode
READ the limit L
GENERATE a Random number (r) between 1 and L
GUESS an integer number n between 1 and L.
IF n==r THEN
PRINT “Number is Correct”
ELSE IF n<r THEN
PRINT “Number is low”
ELSE
PRINT “Number is high”
REPEAT from step 3 IF n!=r
Program
import random
number = random.randint( 1, 100 )
print ('I\'m thinking of a number between 1 and 100')
print ('What is the number I\'m thinking of?')
attempts = 0
while answer != number:
attempts = attempts + 1
answer = input( 'Attempt ' )
answer = int( answer )
if answer > number :
print ('Lower')
Procedure:
If we have 2 disks then
Move smaller disk to Auxiliary
Move larger disk to destination
Finally, we move disk from Auxiliary to destination
Algorithm:
Main Program:
Step 1: Start
Step 2:Get the number of disc n
Step 6: Call the function Hanoi(n,a,c,b)
Step 7: Stop
Start
Call Hanoi(n,src,dest,aux)
F
Stop
If n==1 F
Program:
class Tower:
def _init_(self):
self.counter = 0
def Hanoi(self,n,a,c,b):
if n==1 :
self.counter += 1
print (‘{0}->{1}’.format(a,b))
else:
self.hanoi(n-1, a,b,c)
self.hanoi(1, a,c,b)
self.hanoi(n-1, b,c,a)
def main():
tower = Tower()
tower.hanoi(3,”a”,”c”,”b”)