0% found this document useful (0 votes)
58 views40 pages

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING Unit 1

Uploaded by

lavanya2web
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views40 pages

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING Unit 1

Uploaded by

lavanya2web
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT I - 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.

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.

PROBLEM SOLVING TECHNIQUES


Problem solving technique is a set of techniques that helps in providing logic for solving
a problem. Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. programs

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.

INPUT ALGORITHM OUTPUT

Two Phases of Algorithmic Problem Solving

Derivation of an algorithm that solves the problem

Conversion of an algorithm into code (or) program

Data types and Data Structures:

In Algorithms the data are numbers, words, list & files. Algorithm provides the logic and data provides
the values.

Program = Algorithm + Data Structures


Data Structures refer to the types of data used and how the data are organized in the program. The
Programming languages provide simple data type such as Integers, real numbers and characters and complex
data structures such as arrays, records and files.

Characteristics of an algorithm

i) Each and every instruction should be precise and unambiguous.


ii) Algorithm should have finite number of steps.
iii) Algorithm should be written in sequence (step-by step).
iv) Algorithm should have finite number of inputs.
v) Ensure that the algorithm will terminate.
vi) Results should be obtained only after the algorithm terminate.

Qualities of a good 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.

Two important factors of an algorithm

Time complexity: It is the amount of time required to complete a task.


Space complexity: It is the amount of memory space required to complete a task.

Key features of an algorithm

Sequence: Each instruction is executed in sequence (step-by-step).


Decision: The result is based on some condition.
Repeat: Process is repeated until condition becomes false.

Steps to develop an algorithm

i) An algorithm should be enclosed by two statements START and STOP.


ii) To read data from user INPUT or READ statement is used.
iii) To display the output PRINT statement is used.
iv) The arithmetic operators used are
+ - Addition operator
- - Subtraction operator
* - Multiplication operator
/ - Division operator
= - Assignment operator
v) Commonly used relational operators are
> -- Greater than
< -- Less than
>= -- Greater than or equal to
<= -- Less than or equal to
== -- Equal to
vi) The commonly used logical operators are
AND, OR,NOT.

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

BUILDING BLOCKS OF AN ALGORITHM

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.

Description of the problem.


Setup
Parameters
Execution
Conclusion
Example: To find the sum of two numbers.
Description of the problem:
To find the sum of two numbers.
Setup:
Two numbers required for addition and one variable for storing the result.
Parameters:
1. Read first number.
2. Read the second number.
Execution:
Calculate the sum of two numbers (a,b)
result = a + b
Conclusion:
The desired output is the sum of two numbers which is stored in the variable ‘result’.
State
State is defined as the condition of algorithm at a moment in a time. Algorithm can be in any of the
following states.
1. START state
2. INPUT state
3. PROCESS state
4. OUTPUT state
5. STOP state

PROCESS
SRART INPUT

STOP OUTPUT

Fig 1.2: States of an algorithm


1. START state:
It represents the starting of the program.
2. INPUT state:
It represents the process of reading the input from the user.
3. PROCESS state:
It represents the process done in the program. E.g. Addition, Subtraction etc..
4. OUTPUT state:
It represents the output displayed on the screen.
5. STOP state:
It represents the ending of the program.

Example: Algorithm to find the sum of two numbers.


1. Start (START state)
2. Read A, B (INPUT state)
3. C=A+B (PROCESS state)
4. Print C (OUTPUT state)
5. Stop (STOP state)

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

Example: Temperature conversion


1. Start
2. Read temperature in fahrenheit f.
3. c = (5/9)*(f-32)
4. Print c
5. Stop
Flowchart:

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

Example: Algorithm to find the biggest among two numbers.


1. Start
2. Read a, b
3. If a>b then Print “a is big”
4. Else Print “b is big”
5. Stop

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:

i) Write one statement per line.


ii) Capitalize the keywords.
iii) End Multiline structure.
iv) Keep Statements language independent.
v) Intend to show hierarchy.
Keywords used in pseudo code:
START: BEGIN
INPUT: READ, OBTAIN, GET, INPUT, DEFINE
OUTPUT: OUTPUT, PRINT, DISPLAY, SHOW

COMPUTE:CALCULATE, COMPUTE, ADD, SUBTRACT, INITIALISE,


DETERMINE
INITIALIZE: SET, INITIALIZE
ADD ONE: INCREMENT
STOP: END

Pseudo code guidelines:


i) Pseudo code statements should be written in simple English.
ii) Each statement should be written in separate line.
iii) The keywords should be capitalized.
iv) Pseudo code should be programming language independent.
v) The steps must be understandable.
vi) Each set of instructions are written from top to bottom.
Advantages (Benefits):

→ It can be read and understood easily.


→ It can be done easily on a word processor.
→ It can be modified easily.
→ It occupies less space.
→ It will not run over many pages.
→ Converting a pseudo code to a program is simple.
Disadvantages (Limitations):

→ 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

Syntax for For: Example: Print n natural numbers

FOR( start-value to end-value) DO


statement
...
ENDFOR

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:

Sl.No Name of the symbol Symbol Description

1 Start/Stop Represent the start and stop of the


program

2 Input/Output Denoted either an input or output


operation

3 Process Denotes the process to be carried out

Represent decision making and


4 Decision branching

5 Flow lines Represents the sequence of steps and


direction of flow

Connects remote parts of the flowchart


6 Connector on the same page

A Document
12 Document

13 Sort Sort in some order

Guidelines for drawing flowchart:

i) All necessary requirements should be listed out in logical order.


ii) There should be START and STOP in the flowchart.
iii) The flowchart should be clear, neat and easy to follow.
iv) The direction of flow is from left to right or top to bottom.
v) Only one flow line should emerge from a process symbol.

vi) Only one flow line should enter a decision symbol but 2 or 3 flow line can leave the decision
symbol.

vii) Only one flow line is used with terminal 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.

ii) Alterations and modifications


If alterations are required, the flowchart needs to be redrawn completely.
iii) Reproduction
Reproduction of the flowchart becomes a problem because it cannot be typed.
iv) Cost
High cost for large applications.
Example1: Draw a flowchart to add two numbers.

Start

Read num1, num2,


sum

sum = num1+num2

Print sum

Stop

Example2: Draw a flowchart to find the product of two numbers.

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.

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. Markup programming language
7. Concurrent programming language
8. Object oriented programming language
9. Logic-based programming language

i) Interpreted programming language

An interpreted programming language is a programming language that executes


instructions directly, without compiling a program into machine-language instructions.
Example: BASIC (Beginners All Purpose Symbolic Instruction Code), LISP (List Processing
Language), Python.
ii) Functional programming language

Functional Programming languages define every computation as a mathematical


evaluation. They are based on mathematical functions. They focus on application of functions.
Example: Clean, curry, F#, Haskell and Q

iii) Compiled programming language


Compiled Programming language is a programming language which uses compilers to
convert the source code into machine code.
Example: Ada, algol, C,C++,C#, COBOL, Java, Fortran, VB
iv) Procedural programming language
A procedural language is a type of computer programming language that specifies a
series of well-structured steps and procedures within its programming context to compose a
program. These languages specify the steps that the program should take to reach to an
intended state. Procedure is a group of statements. It makes the program structured and
helps to reuse the code.
Example: CLIST, Hypertalk, MATLAB, PL/I

v) Scripting programming language


Scripting languages are Programming languages that control applications.
Example: AppleScript, AWK, MAYA, PHP, VBSCRIPT.
vi) Markup programming language
Markup language is an artificial language that define how the text to be displayed.
Example: CURL, SGML, HTML, XML, XHTML.

vii) Logic-based programming language


Logic-based programming language is a type of programming language that is based on
logic.
Example: ALF, Fril, Janus, Leda, Prolog.

viii) Concurrent programming language


It is a computer programming language that executes the operations concurrently.
Example: ABCL, Afnix, E, Joule, Limbo.

ix) Object-Oriented programming language


It is a Programming languages based on concepts of objects. Objects contain data
and functions.
Example: Agora, Beta, Lava, Moto, Scala, Slate.
Machine language:
In machine language, instructions are in the form of 0’s and 1’s. Instructions in
machine language consist of two parts.

OPCODE OPERAND

→ OPCODE tells the computer what functions are to be performed.


→ OPERAND tells the computer where to store the data.
Assembly language:
In assembly language, mnemonic code is assigned to each machine language
instruction which is easy to remember and write. Instruction in assembly language
consists of 4 parts.
LABEL OPCODE OPERAND COMMENT
4GL language:
4GL (Fourth generation languages) are simple which is used to access databases.

ALGORITHMIC PROBLEM SOLVING

Algorithms are procedural solutions to problems. Algorithmic problem solving is


defined as the formulation and solution of problems where solution involves the
principles and techniques to construct the correct algorithms. It means that solving
problems that require formulation of an algorithm for their solution.
Steps in designing and analyzing an algorithm
The steps are
i) Understanding the problem
ii) Ascertaining the capabilities of a computational device
iii) Choosing between exact and approximate problem solving
iv) Deciding on appropriate data structures.
v) Algorithm design techniques
vi) Methods of specifying an algorithm.
vii) Proving an algorithm’s correctness.
viii) Analyzing an algorithm.
ix) Coding an algorithm.

Understanding the Problem


It is the process of finding the input of the problem that the algorithm solves.
It is very important to specify exactly the set of inputs the algorithm needs to
handle.
A correct algorithm is not one that works most of the time, but one that works
correctly for all legitimate inputs.
Ascertaining the Capabilities of the Computational Device
If the instructions are executed one after another, it is called sequential
algorithm.
Unit 1: Algorithmic problem solving 13
If the instructions are executed concurrently, it is called parallel algorithm.
Choosing between Exact and Approximate Problem Solving
The next principal decision is to choose between solving the problem exactly or
solving it approximately.
Based on this, the algorithms are classified as exact algorithm and approximation
algorithm.
Deciding a data structure:
Data structure plays a vital role in designing and analysis the algorithms.
Some of the algorithm design techniques also depend on the structuring data
specifying a problem’s instance
Algorithm+ Data structure=programs.
Algorithm Design Techniques
An algorithm design technique (or “strategy” or “paradigm”) is a general
approach to solving problems algorithmically that is applicable to a variety of
problems from different areas of computing.
Learning these techniques is of utmost importance for the following reasons.
First, they provide guidance for designing algorithms for new problems,
Second, algorithms are the cornerstone of computer science
Methods of Specifying an Algorithm
Pseudocode is a mixture of a natural language and programming language-like
constructs. Pseudocode is usually more precise than natural language, and its
usage often yields more succinct algorithm descriptions.
In the earlier days of computing, the dominant vehicle for specifying algorithms
was a flowchart, a method of expressing an algorithm by a collection of
connected geometric shapes containing descriptions of the algorithm’s steps.
Programming language can be fed into an electronic computer directly. Instead,
it needs to be converted into a computer program written in a particular
computer language. We can look at such a program as yet another way of
specifying the algorithm, although it is preferable to consider it as the algorithm’s
implementation.
Proving an Algorithm’s Correctness
Once an algorithm has been specified, you have to prove its correctness. That is,
you have to prove that the algorithm yields a required result for every legitimate
input in a finite amount of time.
A common technique for proving correctness is to use mathematical induction
because an algorithm’s iterations provide a natural sequence of steps needed for
such proofs.
It might be worth mentioning that although tracing the algorithm’s performance
for a few specific inputs can be a very worthwhile activity, it cannot prove the
algorithm’s correctness conclusively. But in order to show that an algorithm is
incorrect, you need just one instance of its input for which the algorithm fails.
Unit 1: Algorithmic problem solving 14
Analysing an Algorithm
1. Efficiency.
Time efficiency, indicating how fast the algorithm runs,
Space efficiency, indicating how much extra memory it uses.
2. 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.
Coding an Algorithm
Most algorithms are destined to be ultimately 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.

5.SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:


1. iterations
2. Recursions
5.1.Iterations:
A sequence of statements is executed until a specified condition is true is called
iterations.
1. for loop
2. While loop
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-value) DO BEGIN
statement GET n
... INITIALIZE i=1
ENDFOR FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
statement GET n
... INITIALIZE i=1
ENDWHILE WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Recursion

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

Sl.No Recursion Iteration


1 Function calls itself until the Repetition of loop until condition
base condition is reached. fails.
2 It keeps code short and It keeps the code longer.
simple.
3 It is slower. It is faster.
4 It takes more memory. It takes less memory.
5 Tracing is difficult if any Tracing is easier if any problem
problem occurs. occurs.

Algorithm for factorial of n numbers using recursion:


Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact

Pseudo code for factorial using recursion:


Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
Sub function factorial(n):
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)

ILLUSTRATIVE EXAMPLES

Minimum in a list

Consider the following requirement specification:

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

Step2:Read total number of elements in the list

Step3:Read the first element as E

Step4:MIN=E

Step5:SET i=2

Step6:If i>n goto Step 11 ELSE goto Step 7

Step7:Read ith element as E

Step8:if E < MIN then set MIN=E

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

Read first Element as E

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 base algorithm to Insert a Card in a List of Sorted Cards

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

Pseudocode to Insert a Card in a List of Sorted Cards

READ Number of element in sorted list as N


SET i=0
WHILE i<N
READ Sorted list element as List[i]

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.

The total number of moves will be 2n – 1, where n is the number of disks.


Algorithm:

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

Fig 1.4: Tower’s of Hanoi with 3 disks


Flowchart:

Hanoi()
Start

Read disk
If

Define function
n=1
Hanoi()
Move disk from souce to

dest

Call the function


Hanoi() Call function Hanoi()

Stop
Move disk from source to
dest

Call function Hanoi()

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

Hanoi (disk-1, source, aux, dest)


Move disk from source to dest
Hanoi (disk-1, aux, dest, source)
ENDIF
END

You might also like