Unit - 1
Unit - 1
UNIT – 1 ALGORITHMICPROBLEMSOLVING
1. 1
AlgorithmicProblemSolving
# Script Begins
A=input(“Enter a message”)
print(A)
# Scripts Ends
Output:
Welcome to python
1. 2
AlgorithmicProblemSolving
5. Input specified: The input is the data to be transformed during the computation to
produce the output. An algorithm should have 0 or more well-defined inputs.
6. Output specified: The output is the data resulting from the computation (your
intended result). An algorithm should have 1 or more well-defined outputs, and should
match the desired output.
7. Correctness: Finite steps in an algorithm must return a correct output for any given
input.
1. Sequence:
Sequencing is the application of each step of an algorithm in the order in which
the statements are given.In a sequence control flow, the instructions are executed in a
linear order one after the other. The sequence can contain any number of actions, but
no actions can be skipped in the sequence. The program, when run, must perform each
action in order with no possibility of skipping an action or branching off to another
action.
Example1.2: Algorithm to find the sum of two numbers
Step 1: Start
Step 2: Get two numbers from user and store it in variables Aand B.
Step 3: Add A and B and assign the result to sum.
sum= A + B
Step 4: Display sum
Step 5: Stop
2. Selection:
1. 4
AlgorithmicProblemSolving
3. Iteration
Iteration is the repetition of a part of an algorithm until a condition is met or for
a specified number of times. One or more instructions are executed repeatedly.
For example, a program written to compute a company`s weekly payroll for
each individual employee will begin by computing the wages of one employee and
continue performing that action in a loop until there are no more employee wages to
be computed, and then the program can move on to its next action.
Each pass through the loop is called iteration. Loops constitute one of the most basic
and powerful programming concepts.
Example 1.4: Algorithm to find sum of 1st 100 integers
Step 1: Start
Step 2: Assign sum = 0, i=1
Step 3: Calculatesum = sum + i and i=i+1
Step 4: Check whether i>100, if no repeat step 3 or go to next step
Step5: Print the value of sum
Step 6: Stop
All logical problems in programming can be solved by forming algorithms
using only the three logic structures, and they can be combined in an infinite number
of ways. The more complex of the computing need is the more complex the
combination of structures.
1. 5
AlgorithmicProblemSolving
1.2.4 Functions
A function is a named block of sequence of reusable code (statement) that is
used to perform a single, related computation. Functions provide better modularity for
your application. Python provides many built-in functions like print(), input(), etc, and
we can also create our own functions.
Some of the advantages of using functions in python are:
Decomposing complex problems into simpler pieces.
Easy to debug and test.
Enables the reuse of code.
Improves clarity and readability of the code.
Improves maintainability.
Enables information hiding.
Reduces duplication of code.
Two types of python functions are:
1. Build-in Function
2. User defined Function
1.3 Notation
1.3.1 Pseudo Code
Pseudocode is a way of expressing an algorithm without conforming to specific
syntactic rules and a simple way of writing programming code in English.It is an
informal high-level description of a computer program or algorithm. Pseudocode is
not actual programming language. It uses short phrases to write code for programs
before you actually create it in a specific language.
Using pseudocode, beginners can more easily communicate ideas and concepts
to other programmers, even though they may be using completely different languages.
There is no such thing as correct pseudocode, although there are a few generally
accepted notations that are widely understood by programmers (e.g. A =5 to create a
variable called A with a value of 5), no matter which language they use.
Why is this so important?
When we are first building a program, we don't really care about the actual
LANGUAGE or SYNTAX we will use. Rather, we care about the logic. Pseudocode
helps us by forcing to think logically rather than about syntax.
Common Keywords: The Keywords often used to indicate common input,
output, and processing operations are
Input: READ, OBTAIN, GET
Output: PRINT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
1. 6
AlgorithmicProblemSolving
Advantages of Pseudocode
It can be easily modified
It can be easily converted into program
Easy to read and understand the concepts
Independent of programming languages.
Disadvantages of Pseudocode
No fixed rules for writing pseudocode.
It cannot be compiled and executed.
For beginners, it will be difficult to follow the logics.
It does not provide visual representation.
Flowchart Symbols
Different flowchart shapes have different conventional meanings. The
meanings of some of the more common shapes are as follows:
1. 7
AlgorithmicProblemSolving
1. 8
AlgorithmicProblemSolving
Example 1.6: Flowchart to find the sum of first N natural numbers using
iteration structure
1. 9
AlgorithmicProblemSolving
Example 1.7: Flowchart to find Sum and Average of two numbers using
sequential structure
Start
Input a, b
Sum = a+b
Avg = (Sum/2)
Display
Sum, Avg
End
Start
Read num
num %
2==0
False
True
Print it is an Print it is an
odd number even number
End
1. 10
AlgorithmicProblemSolving
1. 11
AlgorithmicProblemSolving
1. 12
AlgorithmicProblemSolving
High level language contains English words and symbols. The specified rules
are to be followed while writing program in high level language. The interpreter or
compilers are used for converting these programs in to machine readable form. The
programs that translate high level language in to machine language are called
interpreter or compiler.
Compiler:
A compiler is a program which translates the source code written in a high
level language in to object code which is in machine language. Compiler reads the
whole program written in high level language and translates it to machine language. If
error is found it displays error message on the screen.
Interpreter:
Interpreter translates the high level language program in line by line manner.
The interpreter translates a high level language statement in a source program to a
machine code and executes it immediately before translating the next statement. When
an error is found the execution of the program is halted and error message is displayed
on the screen.
Advantages
1. Readability.
2. High level language is closer to natural language so they are easier to
learn and understand.
3. Machine independent.
4. High level language program have the advantage of being portable
between machines.
5. Easy debugging.
6. Easy to find and correct error in high level language.
Disadvantages
Less efficient: The translation process increases the execution time of
the program. Programs in high level language require more memory and take
more execution time to execute.
They are divided into following categories:
1. Interpreted programming languages
2. Functional programming languages
3. Compiled programming languages
4. Procedural programming languages
5. Scripting programming language
6. Mark-up programming language
7. Concurrent programming language
8. Object oriented programming language
Interpreted programming languages:
1. 13
AlgorithmicProblemSolving
1. 14
AlgorithmicProblemSolving
1. 15
AlgorithmicProblemSolving
Design an Algorithm
Prove Correctness
1. 16
AlgorithmicProblemSolving
5. Analysing an Algorithm
Efficiency:
Time efficiency, indicating how fast the algorithm runs,
Space efficiency indicating how much extra memory it uses.
Simplicity:
An algorithm should be precisely defined and investigated with
mathematical expressions.
Simpler algorithms are easier to understand and easier to program.
Simple algorithms usually contain fewer bugs.
6. Coding an Algorithm
Most algorithms are destined to be implemented as computer programs.
Programming an algorithm presents both a peril and an opportunity.
A working program provides an additional opportunity in allowing an
empirical analysis of the underlying algorithm. Such an analysis is based
on timing the program on several inputs and then analysing the results
obtained.
Iteration
Recursion
1.5.1 Iteration
1. 17
AlgorithmicProblemSolving
Step 1: Start
Step 2: Get a number from the user and store it in variable num.
Step 4: Repeat step 5 and step 6 until start is less than or equal to the num.
Step 5: Multiply start with fact and store the result in variable fact.
Step 7: Display the value of fact as the factorial of the given number.
1.5.2 Recursion
Step 1: Start
Step 2: Get a number from the user and store it in variable num.
Step 5: Stop
1. 18
AlgorithmicProblemSolving
Finding_Factorial(n)
Step 1: Start
Step 4:Return f
Step 5: Stop
1. 19
AlgorithmicProblemSolving
Flowchart
Start
Read List
Elements
minimum = L[0]
Is False
i<n
True
Is False
L[i]<minimum
True
minimum = L[i]
Increment i
Print minimum
Stop
Pseudocode
BEGIN
SET numlist=[ ]
GET n
FOR i=1 to n
GET numlist elements
ENDFOR
1. 20
AlgorithmicProblemSolving
Algorithm
Step 1: Start.
Step 2: Read n (card to be inserted).
Step 3:set i=0.
Step 4:Check whether n>ith card and i<length(list) if true go to step 5
else go to step 6
Step 5:Increment i and go to step 4
Step 6:Shift the cards from ith position to len(list) by 1 position right.
Step 7:Insert the card at ith position.
Step 8: Stop.
Pseudocode
BEGIN
READ n
SET i=0
WHILE (n>ith card& i<length(list)):
INCREMENT i
END WHILE
SHIFT cards in ith position to len(list) by 1 position right.
1. 21
AlgorithmicProblemSolving
Flowchart
Start
Read n
i=0
Is False
n>ith card & i<
length (list))
True
i=i+1
Stop
1. 22
AlgorithmicProblemSolving
Algorithm
Step1: Start
Step 2: Declare hidden, guess
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then
Print Guess is hit
Else
Print Guess not hit
Print hidden
Step 6: Stop
Pseudocode
BEGIN
COMPUTE hidden=random value in a range
READ guess
IF guess=hidden, then
PRINT Guess is hit
ELSE
PRINT Guess not hit
PRINT hidden
END IF-ELSE
END
Flowchart
1. 23
AlgorithmicProblemSolving
Start
Read Guess
False Is True
Guess==hidden
Stop
1. 24
AlgorithmicProblemSolving
Towers
Disks
3 Smallest
1 Largest
These rings are of different sizes and stacked upon in an ascending order, i.e.
the smaller one sits over the larger one. There are other variations of the puzzle where
the number of disks increase, but the tower count remains the same.
Rules
The mission is to move all the disks to some another tower withoutviolating the
sequence of arrangement. A few rules to be followed for Tower of Hanoi are −
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.
Following is an animated representation of solving a Tower of Hanoi puzzle with
three disks.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This
presentation shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps. To write an
algorithm for Tower of Hanoi, first we need to learn how to solve this problem with
lesser amount of disks, say → 1 or 2. We mark three towers with name, source,
destination and aux (only to help moving the disks).
The goal of the puzzle is to move all the disks from leftmost peg to rightmost
peg.Move only one disk at a time.A larger disk may not be p1aced on top of a smaller
disk. For example, consider n=3 disks
1. 25
AlgorithmicProblemSolving
Step: 1
Step: 2
1 3
Step: 3
1 2 3
1. 26
AlgorithmicProblemSolving
Step: 4
1 2
Step: 5
2 1
Step: 6
3 2 1
1. 27
AlgorithmicProblemSolving
Step: 7
3 1
Output:
Algorithm
Procedure Hanoi(disk, Beg,End,Aux)
If disk==1. THEN
move disk from Beg to End
ELSE
Hanoi (disk -1, Beg, Aux, End)
move disk from Beg to End
Hanoi (disk -1, Aux, End, Beg)
END If
END Procedure
1. 28
AlgorithmicProblemSolving
1. 29
AlgorithmicProblemSolving
Step 1: Start
Step 2: Readi, a,b, show
Step 3: Initialize a=0, b=1, i=2 and show =0
Step 4: Read number of terms of Fibonacci series to be printed (n)
Step 5: Print a and b
Step 6: Repeat following stepsuntil i<n
show=a+b
a=b
b=show
Increase value of i each time by 1
print the value of show
Step 7: End
1. 30
AlgorithmicProblemSolving
1. 31
AlgorithmicProblemSolving
1. 32
AlgorithmicProblemSolving
Start
Read a, b, c
False True
Is a>b
False True
Is b>c
False True
Is a>c
Stop
Example 1.20: Flowchart to whether the given year is leap year or not
1. 33
AlgorithmicProblemSolving
Start
IF
False
(year MOD 400 == 0)
or ((year mod 100!=0)
and(year mod 4==0))
True
Stop
1. 34
AlgorithmicProblemSolving
1. What is an algorithm?
“Algorithm is a step- by-step procedure for solving a task or a problem. It is an
ordered sequence of finite, well defined, unambiguous instructions for
completing a task.”
It is English like representation of the logic used to solve the problem.
2. What are the steps for developing algorithms?
Step 1: Obtain a description of the problem.
Step 2:Analyze the problem.
Step 3: Develop a high-level algorithm.
Step 4: Refine the algorithm by adding more detail.
Step 5: Review the algorithm.
3. Write an algorithm to find minimum of 3 numbers in a list.
Step 1: Start
Step 2: Get 3 numbers A,B,C from the user
Step 3: Check whether (A>B) if true then go to step 4 otherwise go
to step 5
Step 4: Check whether (A>C) if true then print “A is greater”
otherwise print “C is greater”
1. 35
AlgorithmicProblemSolving
6. Write the pseudo code to calculate the sum and product of two numbers and
display it.
READ number1, number2
COMPUTE sum = number1 + number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
7. How does flow of control work?
Control flow is the order in which the individual statements are executed. Different
types of control flows are
1. Sequence
2. Selection
3. Iteration
8. What is a function?
A function is a named block of sequence of reusable code (statement) that is
used to perform a single, related computation. Functions provide better modularity for
your application. Python provides many built-in functions like print(), input(), etc, and
we can also create our own functions.
9. Define state.
In computer science, a system is described as stateful if it is designed to
remember preceding events or user interactions. The remembered information is
called the state of the system.
10. List the advantagesflowchart.
It provides a better way for communicating the logic to solve the problem.
It provides an effective way to analyse the problem.
It serves as a good program document.
It acts as blueprint for coding.
It makes debugging easier.
11. Compare flowchart and pseudo code.
Flowchart and Pseudo code are used to document and represent the algorithm.
In other words, an algorithm can be represented using a flowchart or a pseudo code.
Flowchart is a graphical representation of the algorithm. Pseudo code is a readable,
formally styled English like language representation of the algorithm.
12. Define a flowchart.
1. 36
AlgorithmicProblemSolving
1. 37
AlgorithmicProblemSolving
1. 38
AlgorithmicProblemSolving
16 Marks Questions
1. 39
AlgorithmicProblemSolving
1. 40