GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING Unit 1
GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING Unit 1
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.
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating
number of solutions.The problem solving process starts with the problem specifications and ends with a
Correct program.
Algorithms
An Algorithm is defined as step by step procedure for solving a problem. An Algorithm is a well-
defined computational procedure consist 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.
In Algorithms the data are numbers, words, list & files. Algorithm provides the logic and data provides
the values.
Characteristics of an algorithm
i) Time: A good algorithm should take less time to execute the program.
ii) Memory: A good algorithm should take less memory space to execute the program.
iii) Accuracy: A good algorithm should provide more accurate results.
iv) Sequence: A good algorithm should be written in sequence (step-by-step).
v) Understandability: A good algorithm should be easily understandable.
vi) Solvability: A good algorithm should solve the problem.
Example:
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
2.Write an algorithm to find the biggest of two numbers.
Step1:Start
Step2:read the value of a and b
Step3:compare the value of a sand b if a>b then
Print ‘A is largest” otherwise print ‘b is largest’
Step4: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 Totalas 0 and as 1
Step4:read the marks
Step5:repeat step 6 and step7 until i is lessthan n
Step6: Add mark to the total
Step7:Increment the value of i
Step6:print the value of total
Step7:Stop
4. Write an algorithm to find the sum of two numbers.
1. Start
2. Print “Enter two numbers:”
3. Read A, B
4. C=A+B
5. Print C
6. Stop
5. Write an algorithm to swap two numbers.
1. Start
2. Print “Enter two numbers:”
3. Input a, b
4. c = a
5. a = b
6. b = c
7. Print a, b
8. Stop
6. Construct an algorithm to check whether the given number is odd or even.
1. Start
2. Print “Enter two numbers:”
3. Read n
4. r = n%2
5. If r = 0 then
6. Print “Number is even”
7. If r! =0 then
8. Print “Number is odd”
9. Stop
7. Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop
8. Convert temperature Fahrenheit to Celsius.
Inputs to the algorithm:
Temperature in Fahrenheit
Expected output:
Temperature in Celsius
Algorithm:
Step1: Start
Step 2: Read Temperature in Fahrenheit F
Step 3: C 5/9*(F-32)
Step 4: Print Temperature in Celsius: C
Step5: End
9. To determine a student’s average grade and indicate whether successful or fail.
Step 1: Start
Step 2: Input mid-term and final
Step 3: average=(mid-term + final)/2
Step 4: if (average < 60) then
Print “FAIL”
else
Print “SUCCESS”
Step 5: Stop
Algorithm is defined as the effective step-by-step procedure to solve the problem in a finite number of
steps. Algorithms can be designed using the following components. They are
i) Instructions/Statements
ii) State
iii) Control Flow
iv) Functions
Instructions/Statements
Instructions/Statements are the steps which solves a particular problem. Most algorithms have the
basic parts of statements.
In a computer statements might include some of the following actions
• input data-information given to the program
• process data-perform operation on a given input
• output data-processed result.
PROCESS
SRART INPUT
STOP OUTPUT
Control flow
It represents the order of statement execution and direction of flow of programs.
There are three types of control flow.
i) Sequential control flow.
ii) Selection control flow.
iii) Repetition control flow.
i) Sequential control flow
The steps of an algorithm are carried out in a sequential manner.
Statement 1
Statement2
Statement3
Start
Read F
C=(5/9)*(f-32)
Print C
STOP
ii) Selection control flow
Only one of the alternative steps is executed based on the condition.
Yes Condit No
ion
Statement 1 Statement 2
Yes If A>B NO
A is Big B is Big
iii) Repetition control flow
One or more steps are performed repeatedly. This logic is used for producing loops in the program.
The looping process can either be one time or multiple times based on the condition.
Condi No
Statement2
tion
Yes
Statement1
Flowchart:
START
n=0
n=n+1
Print n
If
n<=10
0000
Example: Algorithm to print numbers from 1 to 10.
1. Start
2. Initialize n=0
3. Increment n=n+1
4. Print n
5. If n<=10 then goto step 3
6. Else goto step 7
7. Stop
Functions:
Function is a sub program which consists of block of code(set of instructions)
that performs a particular task.For complex problems, the problem is been divided into smaller and simpler
tasks during algorithm design.
Algorithmic problem solving
Benefits of Using Functions
• Reduction in line of code
• code reuse
• Better readability
• Information hiding
• Easy to debug and test
• Improved maintainability
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
sub function add()
Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
Example: Algorithm to find the biggest among N numbers.
1. Start
2. Read l1, l2, l3…ln into array.
3. Initialize max=l1
4. Read next number l1, do the following
i. If max< l1 then
I) max = l1
ii. Repeat step” i” until n
5. Print max
6. Stop
Advantages of algorithm
i) Easy to understand.
ii) Easy to debug.
iii) It is easy for a programmer to convert algorithm into actual program.
Disadvantages of algorithm
i) It is time consuming. (An algorithm is developed first, which is then converted into
flow chart and then program).
ii) It is difficult to show branching and looping.
NOTATION
Pseudo code
Pseudo code is made up of two words: Pseudo and code. Pseudo means ‘imitation’ and
‘code’ refers to instructions written in programming language. Pseudo code is not a real
programming language, but it looks like a programming language. Pseudo code is also called as
“Program Design Language [PDL]”. It is an outline of a program, written in a form that can be
easily converted into real programming statements. Pseudo code instructions are written in
normal English.
Rules for writing pseudo code:
→ It is not visual.
→ We do not get a picture of the design.
→ There is no standardized style or format.
→ For a beginner, it is more difficult to follow the logic or write pseudo code.
Example 1: Write Pseudo code to calculate sum and average for n numbers.
BEGIN
INITIALIZE sum=0, i=1
READ n
FOR i < = n, then
COMPUTE sum = sum +i
CALCULATE i=i+1
END FOR
COMPUTE avg = sum/n
PRINT sum, avg
END
Example 2: Write Pseudo code to add two numbers.
BEGIN
SET C=0
READ A, B
ADD C=A+B
PRINT C
END
Example 3: Write Pseudo code to calculate area of circle.
BEGIN
READ radius r
INITIALIZE pi=3.14
CALCULATE Area=pi * r *r
PRINT Area
END
Example 4: Write Pseudo code to read number n and print the integers counting up to n.
BEGIN
READ n
INITIALIZE i to 1
FOR i <= n, then
DISPLAY i
INCREMENT i
END FOR
END
Example 5: Write Pseudo code to find the greatest among two numbers.
BEGIN
Read A, B
IF A >B
PRINT “A is greatest”
ELSE
ENDIF END
Syntax for if else: Example: Greatest of two numbers
IF (condition)THEN
statement
...
ELSE
statement
...
ENDIF
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO
statement
...
ENDWHILE
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Advantages:
• Pseudo is independent of any language; it can be used by most programmers.
• It is easy to translate pseudo code into a programming language.
• It can be easily modified as compared to flowchart.
• Converting a pseudo code to programming language is very easy as compared
• with converting a flowchart to programming language.
Disadvantages:
• It does not provide visual representation of the program’s logic.
• There are no accepted standards for writing pseudo codes.
• It cannot be compiled nor executed.
• For a beginner, It is more difficult to follow the logic or write pseudo code as
• compared to flowchart.
Flowchart
Flowchart is a diagrammatic representation of an algorithm. A flowchart is a picture of
the separate steps of a process in sequential order. Flowchart is made up of boxes, diamonds and
other shapes connected by arrows where each shape represents a step in the process. The arrows
show the order of the flow of execution. Flowcharts are used in designing or documenting a
process or program. The logic of the program is communicated in a much better way by using a
flowchart.
Flowchart symbols:
A Document
12 Document
vi) Only one flow line should enter a decision symbol but 2 or 3 flow line can leave the decision
symbol.
START
STOP
viii) If the flowchart becomes complex, connector symbols are used to reduce the number of
flow lines.
ix) The text within the symbols should be brief.
x) The validity of flowchart should be tested by passing simple test data.
Basic design structure of flowchart:
Start
Read
Process
Outpu
t
Stop
Advantages:
i) Better communication
It is easy for the programmer to explain the logic of program.
ii) Effective analysis
It is easy to analyze the problem effectively.
iii) Proper documentation
With the help of flowchart good documentation is done for various purposes.
iv) Efficient coding
Flowchart acts as a guide during the system analysis and program development phase.
v) Efficient debugging
It helps in debugging process.
vi) Efficient program maintenance
The maintenance of a program becomes easy with the help of the flowchart.
Disadvantages (Limitations):
i) Complex logic
Sometimes the logic of the program is quite complicated. In such a case flowcharts
become complex.
Start
sum = num1+num2
Print sum
Stop
Start
product =num1*num2
Read num1, num2,
product
Print
product
Stop
Algorithm Flowchart Pseudo code
An algorithm is a sequence It is a graphical It is a language
of instructions used to representation of algorithm representation of
solve a problem algorithm.
User needs knowledge to not need knowledge of Not need knowledge of
write algorithm program to draw or program language to
understand flowchart understand or write a
pseudo code.
3.3.PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a computer
to perform specific tasks. The programmers have to follow all the specified rules before
writing program using programming language. The user has to communicate with the
computer using language which it can understand.
Types of programming language
1. Machine language
2. Assembly language
3. High level language
Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In
machine language the different instructions are formed by taking different
combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language which the computer understands. For
executing any program written in any programming language, the conversion to
machine language is necessary. The program written in machine language can be
executed directly on computer. In this case any conversion process is not required.
High speed
The machine language program is translation free. Since the conversion time is
saved, the execution of machine language program is extremely fast.
Disadvantage:
It is hard to find errors in a program written in the machine language.
Writhing program in machine language is a time consuming process.
Machine dependent: According to architecture used, the computer differs from each
other. So machine language differs from computer to computer. So a program
developed for a particular type of computer may not run on other type of computer.
Assembly language:
To overcome the issues in programming language and make the programming
process easier, an assembly language is developed which is logically equivalent to
machine language but it is easier for people to read, write and understand.
Unit 1: Algorithmic problem solving 9
Assembly language is symbolic representation of machine language. Assembly
languages are symbolic programming language that uses symbolic notation to
represent machine language instructions. They are called low level language
because they are so closely related to the machines.
Ex: ADD a, b
Assembler:
Assembler is the program which translates assembly language instruction in to a
machine language.
Advantage:
Easy to understand and use.
It is easy to locate and correct errors.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine depends
on the architecture of that computer.
Hard to learn
It is machine dependent, so the programmer should have the hardware
knowledge to create applications using assembly language.
Less efficient
Execution time of assembly language program is more than machine language
program.
Because assembler is needed to convert from assembly language to machine
language.
High level language
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.
Translating high level language to machine language
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 program. Compiler reads the
whole program written in high level language and translates it to machine language. If
any error is found it display 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
Readability
High level language is closer to natural language so they are easier to learn and
understand
Machine independent
High level language program have the advantage of being portable between
machines.
Easy debugging
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.
OPCODE OPERAND
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.
Syntax:
function():
function():
In the above syntax, function() is a function which call itself until the condition is reached.
Difference between recursion and iteration
ILLUSTRATIVE EXAMPLES
Minimum in a list
Take the first element and compare its value against the values of all other elements. Once we find a smaller
element we continue the comparisons with its value. Finally we find the minimum in the list.
Algorithm
Step1:Start
Step4:MIN=E
Step5:SET i=2
Step9:i=i+1
Step10:goto Step 6
Step11:Print MIN
Step12:stop
Pseudocode
BEGIN
READ total number of elements in the list
READ the first element as E
SET MIN=E
SET i=2
WHILE I <= n
Read ith element as E
if E < MIN then set MIN=E
i=i+1 Print MIN
END
Start
Read N
Min= E
I=2
N
IS
Y I<N
Read I th Element as E
Is N
E<N
Y
MIN=E
I=I+1
Print MIN
Stop
Insert a Card in a list of Sorted card
Insterting a card in a list of sorted card is same as inserting an element into a sorted array.
Start from the high end of the list,check to see where we want to insert the data.if the element is less than then
move the high element one postion and next check with next element repeat the process until the correct
position and then insert the element.
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
Step 1: Start
Step 2: Declare variables N, List[], i, and X.
Step 3: READ Number of element in sorted list as N
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
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 to step 12 ELSE go to step15
Step 12: List[i+1]=List[i]
Step 13: i=i-1
i=i+1
ENDWHILE
READ Element to be insert as X
SET i = N-1
WHILE i >=0 and X < List[i]
List[i+1] =List[i]
i=i–1
END WHILE
List[i+1] = X
Flow Chart to Insert a Card in a List of SortedStart
Cards
Read no of element as E
i=0
i<N
N
Read Sorted List List[i]
Y
Read x
i=N-1
i>=0 &&
X<List[i]
List[i+1]=List[i]
N
i=i+1
List[i+1]=X
Y
Stop
Tower’s of Hanoi
A Tower’s of Hanoi is a children’s playing game, played with three poles and a number
of different sized disks which is stacked on the poles. The disks are stacked on the left most pole
in ascending order initially. ie) The largest on the bottom and the smallest on the top.
Rules to be followed:
i) Only one disk can be moved among the towers at any given time.
ii) Only the “top” disk can be removed.
iii) No large disk can sit over a small disk.
The objective is to transfer the disks from the left most pole to the right most pole by
using the centre pole as the temporary pole.
The steps are
i) Move the top n-1 disks from the left pole to the centre pole, n is the number of disks.
ii) Move the nth largest disk to the right pole.
iii) Move the n-1 disks on the centre pole to the right pole.
1. Start
2. Read disk, source, dest, aux
3. Call the function Hanoi(disk, source, dest, aux)
4. Stop
Algorithm for function Hanoi(disk, source, dest, aux):
1. Start
2. If disk=1
Move disk from source to dest
3. Else
Hanoi(disk-1, source, aux, dest)
Move disk from source to dest
Hanoi(disk-1, aux, dest, source)
4. Return
A B C
2
1
A B C A B C
4
3
A B C A B C
5 6
A B C A B C
A B C
Hanoi()
Start
Read disk
If
Define function
n=1
Hanoi()
Move disk from souce to
dest
Stop
Move disk from source to
dest
Return
Pseudo code:
BEGIN
READ disk, source, dest, aux
FUNCTION Hanoi (disk, source, dest, aux)
END
Pseudo code for function Hanoi (disk, source, dest, aux)
BEGIN
IF disk=1 THEN
Move disk from source to dest
ELSE