PSPP Unit I
PSPP Unit I
1.1 - ALGORITHMS
An Algorithm is defined as step by step procedure for solving a problem. An Algorithm
is a well-defined computational procedure consists of a set of instructions that takes some values
as an input, then manipulate them by following prescribed texts in order to produce some values
as output.
Examples:
1. Write an algorithm to find the area of circle.
Step1: Start
Step2: Read the value of radius as r
Step3: Calculate area = 3.14*r*r
Step4: Print the value of area.
Step5: Stop
3. Write an algorithm for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89.
Step1: Start
Step2: Read Numbers as N
Step3: Initialize the value of Total as 0 and as 1
Step4: Repeat step 5 to step7 until i is less than n
Step5: Read the marks
Step6: Add mark to the total
Step7: Increment the value of i
Step6: Print the value of total
Step7: Stop
sum num1+num2
Step-5: Display sum
Step-6: Stop
• There are two types of statements they are
i. Simple Statement
ii. Compound Statement
i) Simple Statement:
• Simple Statement consists of a single logical line.
Ex:
• Expression Statement
• Assignment Statement
• Print Statement
• Import Statement
ii) Compound Statement:
• Compound Statements consist of a group of statements. They control the execution of
other statements. It consists of one or more clauses.
Ex:
• if – statement
• while – statement
• for – statement
• try – statement
b) State
An algorithm is a deterministic automation for accomplishing a goal which given an
initial state, will terminate in a defined end state and internal state for performing an algorithm.
• Initial State starts by keyword “START” or “BEGIN”.
• Internal State starts from data, which is read as an input, written to an output and stored
for processing. The stored data is regarded as a part of Internal State.
• End State is nothing but the keyword “END”
c) Control Flow
Control Flow or Flow of Control is the order function calls, instructions and statement are
executed or evaluated when a program is running. Program Control structures are defined as the
program statements that specifies the order in which statements are executed. There are three
types of control structures. They are.
Process 1 Start
Read radius r
Process 2 S=3.14*r*r
Print S
Process n
Stop
IF Condition THEN
Process A
…
…
…
Process
END IF
2) IF….THEN…ELSE
• In this structure
o If the condition is true. It performs the process A.
o Else the condition is false. It executes process B.
• The process execution is depending on the condition.
Pseudo code Flow Chart
IF Condition THEN
Process A
ELSE IF
Process B Conditio
Process A ns
Process B
END IF
Process 2
…
…
Process 1 Process 2 Process N
…
case Type-n:
Process n
END CASE
d) Functions
Functions are "self-contained" modules of code that accomplish a specific task. Functions
usually "take in" data as INPUT, process it, and "return" a result as OUTPUT. Once a function is
written, it can be used over and over and over again. Functions can be "called" from the inside of
other functions. Functions "Encapsulate" a task (they combine many instructions into a single
line of code).
Ex:
>>>def add(num1,num2): #Function Definition
num3=num1+num2
print(“The sum is”,num3)
return num3
>>>a=10
>>>b=20
>>>c=add(a,b) #Function Call
Flow of a Function:
When a function is "called" the program "leaves" the current section of code and begins
to execute the first line inside the function. Thus the function "flow of control" is:
• The program comes to a line of code containing a "function call".
• The program enters the function (starts at the first line in the function code).
• All instructions inside of the function are executed from top to bottom.
• The program leaves the function and goes back to where it started from.
• Any data computed and RETURNED by the function is used in place of the function in
the original line of code.
• Functions allow us to create sub-steps. (Each sub-step can be its own function and a
group of Instructions)
• They allow us to reuse code instead of rewriting it.
• Functions allow us to keep our variable namespace without any confusion.
• Functions allow us to test small parts of our program in isolation from the rest.
Function Workspace
Every function has its own Workspace which means that every variable inside the
function is only usable during the execution of the function. After that we cannot use the
variable. The variables can be created inside the function or passed as an argument.
• The parameter "r" is called a Formal parameter, this just means a place holder name for
radius.
The variable ‘radius’ is the Actual parameter, this means "what is actually used" for this call to
the function
Example:
Write a Python Program to find area of a circle:
>>>def circle(r): #Where ‘r’ is the Formal Parameter
rad=3.14*r*r
print(“The area of circle is”,rad)
>>>radius=9
>>>circle(radius) #Where ‘radius’ is the Actual Parameter
Ex:
READ num1, num2
result = num1 + num2
WRITE result.
Examples:
1. Write a pseudocode to find the area of circle.
BEGIN
READ radius r
INITIALIZE pi=3.14
COMPUTE Area=pi*r*r
PRINT r
2. Write a pseudocode to find the biggest of two numbers
BEGIN
READ A, B
IF A>B
PRINT “B is big”
ELSE
PRINT “A is big”
3. Write a pseudocode for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89
BEGIN
INITIALIZE total=0,i=1
WHILE i<n
READ mark
total=total+mark
INCREMENT i
PRINT i
END
1.3.2. Flowchart
• A flow chart is a diagrammatic representation that illustrates the sequence of operations
to be performed to arrive the solution.
• Each step in the process is represented by a different symbol and has a short description
of the process steps.
• The flow chart symbols are linked together with arrows showing flow directions.
(or)
• Only one flow line should enter a decision symbol but two or three flow lines can leave.
Start Stop
• Write within standard symbols briefly. You can also use annotation symbol to describe
the data more clearly.
– – – Calculation Part
• If the flowchart becomes complex then it is better to use connector symbols to reduce the
number of flow lines.
• Flow chart should have a start and stop.
• Validity of a flow chart can be tested by passing through it with a simple test data.
Advantages of Flow Chart:
• Flow Charts are better in communication.
• A Problem can be analyzed in an effective way.
• Program Flow Charts Serve as a good documentation.
• Flow Charts acts as a blue print during system analysis and program development phase.
• The maintenance of operating program becomes easy with the help of flow chart.
Disadvantages of Flow Chart:
• Sometimes the program logic is quite complicated, In that case flowchart becomes
complex and clumsy.
• If alterations are required the flowchart may require re-drawing completely.
• As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
Example:
1. Draw a flowchart to find the area of circle.
Start
Read r
area=3.14*r*r
Print area
Stop
Start
Read a,b
a>b
yes No
Start
Read N
Total=0
i=1
If
i<n
Stop Total=Total+Mark
Yes No
Design an algorithm
Prove Correctness
• An Input to an algorithm specifies an instance of the problem and range of the input to
handle the problem.
ii) Decision making
The Decision making is done on the following:
a) Ascertaining the Capabilities of the Computational Device
• After understanding the problem one need to ascertain the capabilities of the
computational device the algorithm is intended for.
• Sequential Algorithms:
o Instructions are executed one after another. Accordingly, algorithms designed to
be executed on such machines.
• Parallel Algorithms:
o An algorithm which can be executed a piece at a time on many different
processing device and combine together at the end to get the correct result.
iii) Choosing between Exact and Approximate Problem Solving:
• The next principal decision is to choose between solving the problem exactly (or) solving
it approximately.
• An algorithm used to solve the problem exactly and produce correct result is called an
exact algorithm.
• If the problem is so complex and not able to get exact solution, then we have to choose an
algorithm called an approximation algorithm. i.e., produces an approximate answer.
Ex: extracting square roots.
iv) Deciding an appropriate data structure:
• In Object oriented programming, data structures is an important part for designing and
analyzes of an algorithm.
• Data Structures can be defined as a particular scheme or structure to organize the data.
An Iterative function is one that repeats some parts of the codes again and again until one
condition gets false.
Ex:
Write a Python program to print 10 values:
>>>i=0
>>>while i<=10:
print(“The Value of i is”,i)
i++
>>>
Recursion:
A Recursive function is the one which calls itself again and again to repeat the code. The
recursive function does not check any condition. It executes like normal function definition and the
particular function is called again and again.
Examples:
Algorithm, Pesudocode, Flowchart for finding Factorial using Recursion
1. Algorithm to find the factorial of given number using recursion
Step1: Start
Step2: Read the value of n
Step3: Call factorial(n) and store the result in f
Factorial(n)
Start
Read n Return
3. Draw the flowchart for finding the factorial using reifcursion n*factorial(n-1)
n==
0
f =factorial(n)
Return 1
No
Print f
Unit I Page 1.23
[Type text]
yes
ILLUSTRATIVE EXAMPLES
1.1. Find Minimum in a list:
Algorithm: Start
Step1:Start
Step2:Read total number of elements in the list
Read N
Step3:Read the first element as E
Step4:MIN=E
Read first Element as E
Step5:SET i=2
Step6:If i>n goto Step 11 ELSE goto Step 7
Step7:Read ith element as E Min= E I=2
i=i+1
Print MIN
END
Flow chart:
Position 0 1 2 3 4 5
Original list 4 6 9 10 11
7>11 4 6 9 10 11
7>10 4 6 9 10 11
7>9 4 6 9 10 11
7>6 4 6 7 9 10 11
Algorithm: Start
Step 1: Start
Step 2: Declare variables N, List[], i, and X.
Step 3: READ Number of element Rineasdonroteodf elilesm
t aenstN
as E
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1 i=0
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i = N-1
Step 11: IF i>=0 AND X<List[i] THEN go it<oNstep 12 ELSE go to step15
Step 12: List[i+1]=List[i]
Step 13: i=i-1
List[i+1]=List[i]
i=i+1
List[i+1]=X
Unit I Page 1.26
[Type text]
Step 1: Start
Step 2: SET Count =0
Step 3: READ Range as N
Step 4: SELECT an RANDOMNUMBER from 1 to N as R
Start
Step 5: READ User Guessed Number as G
Step 6: Count = Count +1 Count=0
Step 7: IF R==G THEN go to step 10 ELSE go to step 8
Step 8: IF R< G THEN PRINT “G
ReuaedssrainsgeTN
oo High” AND go to step 5 ELSE go to step9
Step 9: PRINT “Guess is Too Low” AND go to step 5
Step 10: PRINT Count as Number of Guesses Took
R=random Number from 1 to N
Pseudocode:
SET Count =0
READ Range as N Read User guessesed Number G
R>G
An outline to
solve this
problem,
from the
starting pole,
to the goal
pole, using an intermediate pole:
1. Move a tower of height-1 to an intermediate pole, using the final pole.
2. Move the remaining disk to the final pole.
3. Move the tower of height-1 from the intermediate pole to the final pole using the
original pole.
we can use the three steps above recursively to solve the problem.
END Procedure
Flow Chart for Tower of Hanoi Algorithm
Begin Hanoi(disk,source,dest,aux)
IS
disk==1
Honai(disk-1,source,aux,dest)
Move disk from source to dest
Honai(disk-1,source,aux,dest)
Stop
7. Write the pseudo code to calculate the sum and product displaying the answer on the
monitor screen.
BEGIN
INITIALIZE variables sum, product, number1, number2 of type real
READ number1, number2 sum = number1 +number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
8. Give the rules for writing Pseudo codes.
o Write one statement per line.
o Capitalize initial keywords.
o Indent to show hierarchy.
o End multiline structure.
o Keep statements to be language independent
.
9. Give the difference between flowchart and pseudo code.
• Flowchart is a graphical representation of the algorithm.
• Pseudo code is a readable, formally English like language representation.
10. Define a flowchart.
A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart
is drawn using boxes of different shapes with lines connecting them to show the flow of control.
The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form.
A complex task can be broken down into Recursive calls are expensive (inefficient) as
simpler sub-problems using recursion. they take up a lot of memory and time.
Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.
Advantages Disadvantages
Recursive functions make the code look clean Sometimes the logic behind recursion is hard to
and elegant. follow through.
A complex task can be broken down into Recursive calls are expensive (inefficient) as
simpler sub-problems using recursion. they take up a lot of memory and time.
Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.
20. Write an algorithm to accept two number. compute the sum and print the result.
(University question)
Step 1: Start
Step 2: READ the value of two numbers
Step 3:Compute sum of two numbers
Step 4 :Print the sum
Step 5:Stop
21. Write an algorithm to find the minimum number in a given list of numbers. (University
question)
• Step 1: Start
• Step 2:Read the total number of element in the list as N
• Step3:Read first element as E
• Step 4:MIN=E
• Step 5:Set i=2
• Step6:IF i>n goto Step 11 ELSE goto Step 7
• Step 7:Read i th element as E
• Step 8:IF E<MIN then set MIN=e
• Step 9:i=i+1
• Step 10:goto step 6
• Step 11:print MIN
Unit I Page 1.46
[Type text]
• Step12:Stop
22. Outline the logic to swap the contents of two identifiers without using the third variable
(University question)
• Step1: Start
• Step 2:Read A,B
• Step 3 :A=A+B
• Step 4:B=A-B
• Step5:A=A-B
• Step 6:Print A ,B
• Step 7:Stop