1
UNIT-1
ALGORITHMIC PROBLEM SOLVING
Algorithms, building blocks of algorithms (statements, state, control flow,
functions), notation (pseudo code, flow chart, programming language), algorithmic
problem solving, simple strategies for developing algorithms (iteration, recursion).
Illustrative problems: find minimum in a list, insert a card in a list of sorted cards,
guess an integer number in a range, Towers of Hanoi
1.1 ALGORITHMS
An algorithm is defined as a well-ordered collection of unambiguous and
effectively computable operations that are executed, produces a result and
halts in a finite amount of time.
An algorithm is an informal description of a program. Thus an algorithm is a
sequence of simple steps that can be followed to solve a problem.
These steps must be organized in a logical and clear manner.
Complexity
Time Complexity Space Complexity
Time complexity specifies the amount of time required by an algorithm to
give desired output.
Space complexity specifies the amount of memory required by an algorithm
for performing desired task.
Algorithm that takes less time and less memory space is the best one.
1.1.1 CHARACTERISTICS OF ALGORITHM
The steps in the algorithm must be simple and must not be ambiguous.
It should be written in sequence.
Ensure that the algorithm will terminate.
It should conclude after a finite number of steps.
2
Algorithm must solve the given problem.
1.1.2 QUALITIES OF GOOD ALGORITHM
An algorithm is considered as good ,if
It uses most efficient logic(time complexity)
It uses minimal system memory for its execution
It should able to generate most accurate results.
1.1.3 BUILDING BLOCKS OF ALGORITHM
There are three building blocks namely Sequence structure, Selection
structure and Iteration structure.
1.1.3.1 SEQUENCE STRUCTURE:
The execution of the statements is done sequentially
It uses top-down approach.
Eg: Addition of two numbers
Step1: Start
Step2: Read a, b
Step3: Add the value of a with b and store the result in sum.
Step4: Display the value of sum
Step5: Stop
1.1.3.2 SELECTION STRUCTURE:
Two sets of statement blocks are written in a program along with one or
more conditions
The execution occurs if the condition is true, if the condition is false else
part is executed
It is used for making decisions.
Eg: Find the largest among three Numbers
Step1: Start
Step2: Read the value of a, b, c
Step3: IF (a>b) and (a>c) THEN
Print a is largest
ELSE IF (b>c) THEN
Print b is largest
3
ELSE
Print c is largest
Step4: Stop
1.1.3.3 ITERATION STRUCTURE (LOOPING):
The execution of this structure is repeated many times if the conditional
statement is true.
Eg: Finding the Factorial
Step1: Start
Step2: Read the value of n and set i =1
Step3: While i <= n do
fact =fact * i
i=i+1
else Goto step5
Step4: Go to step 3
Step5: print the value of fact
Step6: Stop
1.1.4 ADVANTAGES OF ALGORITHM
It is a step-wise representation, which makes it easy to understand.
It is easy to understand for anyone even without programming knowledge.
Every step in an algorithm has its own logical sequence so it is easy to
debug.
By using algorithm, the problem is broken down into smaller pieces or steps
hence, it is easier for programmer to convert it into an actual program
1.1.5 DISADVANTAGES OF ALGORITHM
Writing algorithm takes a long time.
An Algorithm is not a computer program; it is rather a concept of how a
program should be.
1.1.6 STATEMENTS
reserved words - words that have pre-defined meanings in the Java
language
4
Identifiers - words that are created by programmers for names of variables,
functions, classes, etc.
literals - literal values written in code, like strings or numbers
integer literal - an actual integer number written in code (4, -10, 18)
float literal - an actual decimal number written in code (4.5, -12.9, 5.0)
character literal - a character in single quotes: ('F', 'a', '\n')
string literal - a string in double quotes: ("Hello", "Bye", "Wow!\n")
operators - special symbols that perform certain actions on their operands
A unary operator has one operand
A binary operator has two operands
A ternary operator has three operands (there's only one of these)
Calls to methods (functions).
1.1.7 CONTROL FLOW
Control flow (or flow of control) is the order in which
individual statements, instructions or function calls of an imperative
program are executed or evaluated.
They Are Three Types Of Control Flow
1.Sequence
2.Selection
3.Repetition
1.1.7.1 SEQUENCE:
The execution of the statements is done sequentially
It uses top-down approach.
1.1.7.2 SELECTION:
Two sets of statement blocks are written in a program along with one or
more conditions
The execution occurs if the condition is true, if the condition is false else
part is executed
It is used for making decisions.
1.1.7.3 REPETITION
The execution of this structure is repeated many times if the conditional
statement is true.
1.1.8 FUNCTIONS
Function: piece of prewritten code that performs an operation
5
print function: displays output on the screen
Argument: data given to a function
Example: data that is printed to screen
Statements in a program execute in the order that they appear
From top to bottom.
1.2 NOTATION – PSEUDO CODE
Pseudocode, on the other hand, is a newer tool and has features that make it
more reflective of the structured concepts.
Detailed algorithm before developing a program is very time consuming
It focuses on only logic of program
It is not written using specific syntax
Written by using combination of generic syntax and normal English
language
1.2.1 KEYWORDS
READ,GET
PRINT,DISPLAY
COMPUTE, CALCULATE.
1.2.3 GUIDELINE FOR WRITING PSEUDOCODE
Steps should be understandable.
Statements should be written in English and programming language
independent.
Pseudocode should describe the logical plan to develop a program.
Capitalize the keyword.
Indent to show hierarchy.
End multiple line structure etc.
Eg: Addition of two numbers
• READ a,b
• C=a+b
• WRITE C
• Stop
1.2.4 ADVANTAGES
Pseudocode is language independent; it can be used by most of the
programmers.
6
It becomes east to develop a program based on a pseudocode rather than
with a flowchart.
It is compact and easy to modify.
1.2.5 DISADVANTAGES
Pseudocode does not provide visual representation of the program’s logic.
No accepted standards/ rules for writing pseudocode.
It is not used to understand the flow of the program control.
It cannot be compiled nor executed.
1.3 FLOWCHART
A flowchart is a graphical or symbolic representation of a process.
Represents flow of control and logic in the solution to the problem
Uses different symbols for describing activities.
1.3.1 TYPES OF FLOWCHART
Flowcharts are used for a variety of purposes in manufacturing, architecture,
engineering, business, technology, education, science, medicine,
government, administration and many other disciplines.
Swim lane flowcharts
Data flow diagrams
Influence diagrams
Workflow diagrams
1.3.2 FLOWCHART SYMBOLS
Terminator
- Represent the start and stop of the program.
Input/Output - Denotes either an input or output operation.
Process Symbol - Denotes the process to be carried out.
7
Decision - Represents decision making and branching statements.
Flow lines sequence of steps and direction of flow, used to connect symbols
Connectors - It is used to connect the flow lines.
1.3.3 GUIDELINES FOR PREPARING FLOWCHARTS
It should be simple, clear, neat and easy to follow.
Standard symbols should be used.
The flow lines should not intersect each others.
Only one flow line is used in conjunction with terminal symbol.
The flowchart should have a logical start and stop.
Eg: Adding two numbers: sequential structure
Greatest among two numbers: Selection Control Structure
8
Factorial of n numbers: Looping
9
1.3.4 BENEFITS OF FLOWCHARTS
Makes Logic Clear
Communication- provides a better way for communicating the logic of a
symbol.
Effective Analysis – act as guide or blueprint during the system analysis and
program development phase.
Useful in coding
Useful in Testing etc.
1.3.5 LIMITATIONS
It is difficult to use flowcharts for large program
Difficult to modify and programs are updated regularly. It doesn’t take place
especially in the case of large program.
Complex logic – in case of complex problems, flowcharts tend to continue
for many pages, making them hard to follow.
10
1.4 PROGRAMMING LANGUAGE
A programming language is a vocabulary and set of grammatical rules for
instructing a computer or computing device to perform specific tasks.
The term programming language usually refers to high-level languages, such
as BASIC, C, C++, COBOL, Java, FORTRAN, Ada, and Pascal.
Each language has a unique set of keywords (words that it understands) and
a special syntax for organizing program instructions.
1.5 ALGORITHMIC PROBLEM SOLVING
Example 1: Finding the area of a circle
Algorithm :
Step1: Start
Step2: Read the value of r
Step3: Calculate area = 3.14*r*r
Step4: Print area
Step5: Stop
Pseudocode:
Set area
READ the r
COMPUTE area=3.14*r*r
PRINT area
Stop
Flowchart:
11
2. Find the largest among three Numbers
Algorithm:
Step1: Start
Step2: Read the value of a, b, c
Step3: IF (a>b) and (a>c) THEN
print a is largest
ELSE IF (b>c) THEN
print b is largest
ELSE
print c is largest
Step4: Stop
Pseudocode:
READ a, b, c
IF (a>b) and (a>c) THEN
WRITE a is largest
ELSE IF (b>c) THEN
WRITE b is largest
ELSE
WRITE c is largest
ENDIF
Stop
Flowchart:
12
1.6 SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS
(ITERATION, RECURSION)
Iteration and recursion are both ways to achieve repetition in programs. One can be
converted to the other:
All iterative functions can be converted to recursion because iteration is
just a special case of recursion (tail recursion). In functional languages
like Scheme, iteration is defined as tail recursion.
All recursive functions can be converted to iteration by simulating the
stack to store state.
However, recursion is usually slower and uses more memory because of the
overhead of creating and maintaining stack frames. This doesn’t mean ever use
recursion though. Recursion is the better choice when:
The code is clearer, more concise, and more intuitive
Exploring/manipulating recursive data structures like linked
lists and trees or parsing expressions.
ILLUSTRATIVE PROBLEMS:
1. FIND MINIMUM IN A LIST
Algorithm:
Step 1: Start the program
Step 2: Declare the variable called size
Step 3: Get the number of elements in size
Step 4: Create the list lst []
Step 5: Store the elements
for i in range (0, size):
lst.append(int(input()))
Step 6: Display elements
Step 7: Set min=lst
for i in range (0, size):
if lst[i]
min = lst [i]
13
Step 8: Display result in minimum
Step 9:Stop the program
Pseudocode:
SET size
CREATE lst
READ elements in size
Store element in list
for i in range (0, size):
lst.append(int(input()))
DISPLAY elements
SET min=lst
for i in range (0, size):
if lst[i]<min:
min = lst [i]
PRINT min
Flowchart
14
2. INSERT A CARD IN A LIST OF SORTED CARDS:
Insertion sort is a simple sorting algorithm that works the way we sort
playing cards in our hands.
Algorithm:
Step 1: Start
Step 2: Read the value of n, i,j,temp
Step 3: for i=1 to n-1
Step 4: for j=i
while( a[j]<a[j-1]) then
temp=a[j]
a[j]=a[j-1]
a[j-1]=temp
j=j-1
Endwhile
Endfor
Step 4: Print the sorted list
Step 5: Stop
Program:
15
size=int(input("enter the number ofelements:"))
lst=[]
print("Enter the elements:")
for i in range (0, size):
lst.append(int(input()))
print("Entered list are:",lst)
for i in range (1, len(lst)):
j=i
while j>0 and lst[j-1]>lst[j]:
temp=lst[j]
lst[j]=lst[j-1]
lst[j-1]=temp
j-=1
print("sorted List:", lst)
Output:
enter the number ofelements:3
Enter the elements:
3
4
1
Entered list are: [3, 4, 1]
Sorted List: [1, 3, 4]
3. GUESS AN INTEGER IN A RANGE
Algorithm:
Step 1: Start
Step 2: Read the random number range(0,100)
Step 3: while guessed==false
Step 4: if(user input> random number)
Print a bit lower
Elseif
Print a bit higher
16
end if
end while
Step 5: print the guess number
Step 6: Stop
Flowchart:
3. TOWERS OF HANOI
It consists of three rods (pegs) and a number of disks of different sizes,
which can slide onto any rod.
The puzzle starts with the disks in a neat stack in ascending order of size on
one rod, the smallest at the top, thus making a conical shape.
Rules to move rod:
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack.
No disk may be placed on top of a smaller disk.
With 3 disks, the puzzle can be solved in 7 moves. The minimal number of
moves required to solve a Tower of Hanoi puzzle is 2 n − 1, where n is the
number of disks.
17
Program:
disks = 3
beg = 'A'
aux = 'B'
end = 'C'
def hanoi(n, beg, aux, end):
if n > 0:
hanoi(n-1, beg, end, aux)
print( 'move disk from ', beg, ' to ', end)
hanoi(n-1, aux, beg, end)
hanoi(disks, beg, aux, end)
Output:
move disk from A to C
move disk from A to B
move disk from C to B
move disk from A to C
move disk from B to A
move disk from B to C
move disk from A to C
Pseudocode:
FUNCTION MoveTower (disk, source, dest, spare):
If disk ==0, THEN:
Move dis from source to dest
ELSE:
MoveTower (disk – 1, source, spare, dest)
Move disk from source to dest
Movetower (disk -1, spare, des, source)
END IF
18
Flowchart: