0% found this document useful (0 votes)
6 views35 pages

PSPP UNIT-1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

Unit I

ALGORITHIMIC PROBLEM SOLVING

Fundamentals of Computing – Identification of Computational Problems -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.

Fundamentals of Computing

 Definitions- Computer
o A computer is a machine that manipulates data accordingly to a set of instructions
o Computer is fast operating electronic device that receives data (input), process the data,
stores data, and produces resultant data (output)
o A computer is a device that accepts information (in the form of digitized data), manipulates
and processes the data based on a program, or sequence of instructions
 Overview of Computers
o It is an electronic machine for data storage and processing, processes the given input and
generates output in the form of useful information
o A computer accepts input in different forms such as data, programs and user reply
o Programs refer to set of instructions that can be executed by the computer in a sequential or
non-sequential manner
o The main task of a computer system is to process the given input of any type in an efficient
manner
o Computers are the combination of two things. They are

 Hardware
 Software
1. Hardware
 Computer Hardware is the visible components of the computer that enables the
computer system to function properly
 It is the framework on which the computer software operates
 Computer Hardware is made up of various components.

 Examples
 A computer includes various devices that function as an integrated system to
perform several tasks described above. The devices are
o CPU, MOINTOR, Keyboard, Mouse, Printer etc.
 Central Processing Unit (CPU)
 It is the processor of the computer that is responsible for controlling and
executing instructions in the computer

1
 It is considered as the most important component of the computer
 It is the “brain” of the computer
 The process of the data are been done according to the instructions by the users
 Monitor
 It is a screen, which displays information in visual form, after receiving the
video signals from the computer
 It is the display (or) output unit of the computer. The information’s are
displayed on the screen
 Keyboard
 It is an input device having different sets of keys for operating
 It is like typewriter keyboard
 It has character keys, numeric keys, Indo-Arabian numeric keys, etc., Most of
the key performs dual functions
 Mouse
 It is also an input device to move the cursor on the screen
 It is also known as pointing device
 It is also used to give commands through it’s right and left keys

2. Software
 A set of programs that are executed sequentially is called software.
 Software is generic term for organized collection of computer data and instruction
 It is responsible for controlling integrating and managing the hardware components of a computer
and for accomplishing specific tasks
 Software can be classified into two types: They are
o System Software
 These software are inbuilt software to boot the system, for example Operating
System. Users can’t run the computer without these system softwares. These
softwares are mandatory to start a computer
 Examples: LINUX, UNIX, DOS, etc.
o Application Software
 These softwares are optional and can be used along with the system softwares.
 But used can use computer without application softwares
 The application software are used for specific purpose.

2
 There are thousands of applications available to help the user to perform the desired
tasks.
 It helps the user to work faster
 Examples: Tally, CAD, games software, etc.

Basic Operations of a Computer

 There are basically 5 basic operations to perform any task


o Inputting
o Processing
o Storage
o Controlling
o Outputting
 Inputting
o It is the process of giving raw data to a computer, to perform the desired task through the input
devices such as keyboard, muse etc.,
 Processing
o It is the transformation operation to convert input to output by CPU from the instructions given
by the user
 Storing
o It is the process of saving the data or instruction or information by the system for future
retrieving
 Controlling
o It is the process of directing and sequencing all the operations
 Outputting
o It is the process of displaying the result through the output device like monitor, printer etc.,

Characteristics of a Computer

Speed

A computer works with much higher speed and accuracy compared to humans while performing mathematical
calculations. Computers can process millions (1,000,000) of instructions per second. The time taken by
computers for their operations is microseconds and nanoseconds.

3
Accuracy

Computers perform calculations with 100% accuracy. Errors may occur due to data inconsistency or
inaccuracy.

Diligence

A computer can perform millions of tasks or calculations with the same consistency and accuracy. It doesn’t
feel any fatigue or lack of concentration. Its memory also makes it superior to that of human beings.

Versatility

Versatility refers to the capability of a computer to perform different kinds of works with same accuracy and
efficiency.

Reliability

A computer is reliable as it gives consistent result for similar set of data i.e., if we give same set of input any
number of times, we will get the same result.

Automation

Computer performs all the tasks automatically i.e. it performs tasks without manual intervention.

Memory

A computer has built-in memory called primary memory where it stores data. Secondary storage are removable
devices such as CDs, pen drives, etc., which are also used to store data.

Basic Components of Computer

There are five basic components which include:

1. Input Unit
2. Output Unit
3. Memory Unit
4. Control Unit
5. Arithmetical and Logical Unit

4
 Input Unit
o A computer will only respond when a command is given to the device. These commands can be
given using the input unit or the input devices.
o For example: Using a keyboard we can type things on a Notepad and the computer processes the
entered data and then displays the output of the same of the screen.
o The data entered can be in the form of numbers, alphabet, images, etc. We enter the information
using an input device, the processing units convert it into computer understandable languages and
then the final output is received by a human-understandable language.

 Output Unit
o When we command a computer to perform a task, it reverts for the action performed and gives us
a result. This result is called output. There are various output devices connected to the computer.
The most basic of which is a monitor. Whatever we write using a keyboard or click using a mouse,
is all displayed on the monitor.
o Thus, the output unit gives us the final result once the entire processing is done within the
mechanism of a device.

 Memory Unit
o When we enter the data into the computer using an input device, the entered information
immediately gets saved in the memory unit of the Central Processing Unit (CPU). Because of the
presence of some existing programming, the Memory Unit transmits the data further to the other
parts of the CPU.

5
o Similarly, when the output of our command is processed by the computer, it is saved in the memory
unit before giving the output to the user.

 Arithmetic & Logical Unit


o As the name suggests, all the mathematical calculations or arithmetic operations are performed in
the Arithmetic and Logical Unit of the CPU.
o It can also perform actions like a comparison of data and decision-making actions. The ALU
comprises circuits using which addition, subtraction, multiplication, division and other numerical
based calculations can be performed.

 Central Processing Unit (CPU)


The Central Processing Unit is the core of any computer devices. It comprises three major components of the
computer which have been discussed above:

 Memory Unit
 Control Unit
 Arithmetic and Logical Unit
All these three units are elements of CPU and together help in the efficient working and processing of data. It
is also known as the “Brain of Computer” and no action can be conducted by a device without the execution
and permission of the Central Processing Unit.
Identification of Computational Problems
What is Computation?

 It is any type of calculation that includes both arithmetical and non-arithmetical steps and follows a well-
defined model
 E.g.: Algorithm.

Types of Computational Problems

 Decision Problems
 Search Problems
 Counting Problems
 Optimization Problems

Computational thinking can be split into four parts,

 Decomposition
 Pattern recognition
 Abstraction
 Algorithmic design

Computational thinking allows us,

 To take a complex problem


 Understand what the problem is
 Develop possible solutions
 Present these solutions in a way that a computer, a human, or both, can understand.

In order to solve a problem computationally, two things are needed,


6
 A representation that captures all the relevant aspects of the problem
 An algorithm that solves the problem by use of the representation

Algorithm

Definition of Algorithm: An algorithm is a finite set of instructions for performing a particular


task. The instructions are nothing but the statements in simple English language.

o Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for completing a
task.

o An algorithm is defined as “a step by step procedure for solving any problem”.

o It is an English –like representation of logic which is used to solve the problem.

o The algorithm is independent of any programming language.

Properties/ Characteristics of an Algorithm

o Finiteness
o The algorithm must terminate after a finite number of steps.

o Definiteness

o Each instruction must be clear, well-defined and precise. There should not be any ambiguity.

o Effectiveness

7
o Each instruction must be simple and carried out in finite amount of time.

o Input

o It is a set of values as input data.

o Output

o This is result of the program.

Qualities of an Algorithm

o Accuracy

o Algorithm should provide accurate result than others.

o Memory

o It should require minimum computer memory.

o Time

o Lesser the time taken better the quality.

o Sequence

o Procedure of an algorithm must be sequential form.

o Result

o It should lead to correct result each time.

Example:

Let us take a very simple example of an algorithm which adds the two numbers and store the result in a third
variable.

Step 1: Start.

Step 2: Read the first number in variable 'a'

Step 3: Read the second number in variable 'b'

Step 4: Perform the addition of both the numbers and store the result in variable 'c'.

Step 5: Print the value of 'c' as a result of addition.

Step 6: Stop.

Find the area of a circle of radius r.

Solution:

Inputs to the algorithm:

8
Radius r of the Circle.

Expected output:

Area of the Circle

Algorithm:

Step 1: Start

Step 2: Read input the Radius r of the Circle

Step 3: Area=3.14*r*r // calculation of area

Step 4: Print Area

Step 5: Stop

An algorithm to calculate even numbers between 0 and 99.

Solution:

Step 1: Start

Step 2: Read n or Initialize n=99

Step 3: Initialize i=2

Step 4: If i<=n, then goto step 5 else goto step 7

Step 5: If i%2=0, then goto step 5.1, 5.2 else goto step 6

Step 5.1: Print i

Step 5.2: i=i+1 goto step 4

Step 6: i=i+1 goto step4

Step 7: Stop

Building Blocks of Algorithms

 Statements
 State
 Control Flow
 Functions

Statements / Instructions

 Algorithm consists of finite number of statements


 The statements must be in an ordered form
 Statements might include some following actions
o Input data-information given to the program
o process data-perform operation on a given input
9
o Output data-Processed Result

State
 Transition from one process to another process under specified condition with ina time is called state
Control flow
 The process of executing the individual statements in a given order is called control flow.

 The control can be executed in three ways

1. Sequence

2. Selection

3. Iteration
Sequence

 Instructions are executed in the order as they are written.

 In short, sequence is a series of steps that are followed one after the other.

 When an instruction is executed the execution control moves to the next immediate step.

Example 1: Algorithm to find sum of two numbers


Step 1: Start
Step 2: Read two numbers Num1 and Num2
Step 3: Calculate sum, i.e. Total=Num1+Num2
Step 4: Display Total
Step 5: Stop

Example 2: Algorithm to calculate the area of circle


Step 1: Start
Step 2: Read input r as radius of circle
Step 3: Calculate area, i.e. Area=3.14*r*r
Step 4: Display Area
Step 5: Stop
10
Example 3: Algorithm to convert Fahrenheit to Centigrade
Step 1: Start
Step 2: Read Fahrenheit F
Step 3: Calculate Centigrade C = (F-32)*(5/9)
Step 4: Print C
Step 5: Stop

Selection Statements
 Selection is the program construct that allows a program to choose between different actions. Choose
at most one action from several alternative conditions.
 A selection statement causes the program control to be transferred to a specific part of the program
based upon the condition.
 If the conditional test is true, one part of the program will be executed, otherwise it will execute the
other part of the program.

Example 1 Algorithm to check whether the given number is odd or even


Step1: Start.
Step2: Input Number, Num.
Step3: If Num % 2 == 0. If yes go to Step 4. Else go to Step 6.
Step4: Print number is even.
Step5: Go to Step 7.
Step6: Print number is odd.
Step7: End.

Example 2: Algorithm to find greatest among three numbers


Step 1: Start.
Step 2: Read the three numbers A, B, C.
Step 3: Compare A and B. If A is greater, store A in MAX, else store B in MAX.
Step 4: Compare MAX and C. If MAX is greater, output “MAX is greatest” else output “C is greatest.
Step 5: Stop
11
Repetition or Iteration
 Execute the same lines of code for several times.
 In such cases repetition structure is used to repeat one or more statements for number of times.
Example: Algorithm to print all natural numbers up to n
Step 1: Start
Step 2: Get n value.
Step 3: Initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: Go to step 4
Step 7: Stop

Functions
 Any complex problem will be simpler if the problem is broken smaller and the smaller problems are
solved.
 Hence writing functions would increase the readability and efficiency of the algorithm.
 Once a function is written, it can be used over and over and over again

Benefits of Using Functions


 Reduction in line of code
 Code Reuse
 Better readability
 Easy to debug and test
 Improved maintainability

Notation (Pseudo code, Flow chart, Programming Languages)


o Pseudo code is an informal language used by programmers to develop algorithms.

o Pseudo means imitation and code refers to instructions written in programming language.

o Pseudo code cannot be compiled nor executed.

o There is no real formatting or syntax rules for Pseudo code.

o Pseudo code is a set of statements in plain English which may be translated later into a programming
language.

o It does not include details like variable declaration, subroutines.

o It gives us the sketch of the program before actual coding.

o It is easy for a programmer and non-programmer to understand the general working of the program,
because it is not based on any programming language.

12
Input Read, obtain, Get, Prompt
Output Print, Display, Show
Calculations Compute, Calculate, Determine
Initiate Set, Initialize
Add one Increment

Guidelines for writing Pseudo code


o Write only one statement per Line.

o Capitalize initial keyword.


o Indent to show hierarchy.
o End multi-line structures.
o Keep statement language independent.

Write only one statement per Line

o Readability improves if just one action for the computer is written in one statement.
o A Pseudo code to add two numbers and display results.
READ num1, num2
Result = num1+num2
Write Result

Capitalize initial Keyword

o Keywords listed below should be written in capital letters.


o READ
o WRITE
o IF
o ELSE
o ENDIF
o WHILE
o ENDWHILE
o REPEAT
o UNTIL

Indent to show hierarchy

– Indentation is a process of showing the boundaries of the structure.

– Example 1

If a>b then

PRINT a

ELSE

PRINT b
13
– Example 2

READ name, class, m1, m2, m3

Total=m1+m2+m3

Average=Total/3

IF average is greater than 75

Rank=Distinction

ENDIF

WRITE name, Total, Average, Rank

End multiline structure

– Each structure must be ended properly, which provides more clarity.


– Example: ENDIF for IF statement.

Keep statement language independent

o The programmer must never use the syntax of any programming language.

Control Structures used in Pseudo code

o There are three control structures used in Pseudo code. They are,
o Sequence control structure.
o Selection control structure.
o Iteration control structure.

Sequence Control Structures

o In sequence control structure, the steps are executed in a linear order one after another.
o They are executed in the order in which they are written, from top to bottom.

EXAMPLE: Find product of any two numbers

READ values of A and B

COMPUTE C by multiplying A with B

PRINT the result C

STOP

Selection Control Structure

o It is a decision in which a choice is made between two alternative courses of action.


o IF-THEN-ELSE
o In IF-THEN-ELSE selection structure, if the condition is true, the THEN part is executed.
o Otherwise ELSE part is executed.
14
o Syntax

IF condition THEN

Sequence 1

ELSE

Sequence 2

END IF

o Example

READ values of A, B, C

IF A is greater than B THEN

ASSIGN A to MAX

ELSE

ASSIGN B to MAX

IF MAX is greater than C THEN

PRINT MAX is greatest

ELSE

PRINT C is greatest

STOP

Iterative Control Structures

 It is a loop (iteration) based on the satisfaction of some condition(s). It comprises of the following
constructs:
o WHILE…END WHILE
o REPEAT…UNTIL
15
o FOR…ENDFOR

Syntax for WHILE…ENDWHILE Example: To print numbers from 1 to 100


WHILE condition n=1
Sequence WHILE n is less than or equal to 100
END WHILE DISPLAY n
INCREMENT n by 1
END WHILE

Syntax for REPEAT…UNTIL Example: To print numbers from 1 to 100


REPEAT n=1
Sequence REPEAT
UNTIL condition DISPLAY n
INCREMENT n by 1
UNTIL n is greater than 100
Syntax for FOR…ENDFOR Example: To print N natural numbers
FOR (start-value to end-value) DO BEGIN
statement GET n
……….. INITIALIZE i=1
END FOR FOR (i<=n)DO
PRINT i
i=i+1
END FOR
END
Advantages

 Can be done easily on a word processor.


 Easily modified.
 Implements structured concepts well.
 It is simple because it uses English-like statements.
 No special symbols are used.
 No specific syntax is used.

Disadvantages

 It’s not visual.


 There is no accepted standard, so it varies from company to company.
 Cannot be compiled or executed.

Flowcharts

o A flowchart is a diagrammatic representation of an algorithm.


o A flowchart is drawn using boxes of different shapes with lines connecting them to show the flow of
control.
o The purpose of drawing a flowchart is to make the logic of the program clearer in visual form.
o The logic of the program is communicated in a much better way using a flowchart. Since flowchart is
a diagrammatic representation, it forms a common medium of communication.

Flow Chart Symbols

16
Symbol Symbol Name Description

Represents arithmetic and


Process logical instructions

Terminal Symbol Represent the start and stop of


the program

Flow Lines Used to connect symbols

Represents input and output


Input/ Output operation

Decision Represents decision making


and branching

Connector Used to join different flow


lines

Used to call function


Sun function

Basic Guidelines for Preparing Flow Charts

o The flowchart should be clear, neat and easy to follow


o The usual direction of the flow of a procedure or system is from left to right or top to bottom
o Only one flow line should come out from a process symbol

o Only one flow line should enter a decision symbol. However, two or three flow lines may leave a
decision symbol.

17
o Only one flow line is used in conjunction with terminal symbol.

o Ensure that the flowchart has a logical start and finish.


o It is useful to test the validity of the flowchart by passing through it with a simple test data.

Advantages of Flowcharts

a. Communication
o Flowcharts are better way of communicating the logic of a system to all concerned.
b. Effective Analysis
o With the help of flowchart, problem can be analyzed in more effective way.
c. Effective Coding
o The flowcharts act as a guide or blueprint during the system analysis and program development
phase.
d. Proper Testing and Debugging
o The flowchart helps in debugging process.
e. Effective Program Maintenance
o Maintenance of running program becomes easy with the help of flow chart

Disadvantages of Flowcharts

o A complex and long flow chart may run into multiple pages, which becomes difficult to understand
and follow
o Updating the flowchart with changing requirements is a challenging job.

Programming Languages

A programming language is a set of rules that provides a way of telling a computer what operations
to perform.
Types of Programming Languages

– Machine Language (Low-Level Language)

– Assembly Language

– High Level Language


Machine Language
 Low-Level Languages are closer to the language used by a computer, while high level languages are
18
closer to human languages.
 Machine language is a collection of binary digits or bits that the computer reads and interprets.
 While easily understood by computers, machine languages are almost impossible for humans to use
because they consist entirely of numbers

Advantages
 Translation free
o Machine language is the only language which the computer understands
o In this case conversion is not required
– High Speed
o The machine language program is translation free.
o Since conversion time is saved, the execution of machine language is faster.
Disadvantages
– Hard to find errors in a program written in machine language.
– Writing program in machine language is time consuming process.

Assembly Language
 An assembly language consists of (English like) mnemonics
 Assembly languages use keywords and symbols, much like English, to form a programming language but
same time introduce a new problem
 The problem is that the computer doesn’t understand the assembly code, so we need a way to convert
to machine code, which computer does understand.
 Assembly level programs are translated into machine language by a program called assembler
 Example

ADD a,b
Mnemonic Opcode

• Advantages

– Easy to understand and use

– It is easy to locate and correct errors

• Disadvantages

– Machine dependent
• Normally the assembly language program are machine dependent / written based on the
particular machine language like 8085/8086.
– Hard to learn
• Programmer should know hardware knowledge to create applications using assembly
language.
19
– Less efficient
High Level Languages

 High-level languages allow us to write computer code using instructions resembling everyday spoken
language (for example: print, if, while)
 Programs written in high level language need to be translated into machine language before they can be
executed
 Since programming languages use a compiler to perform this translation and others use interpreter
 Examples: C,C++,BASIC,PYTHON,JAVA,PASCAL,COBOL
 Advantages
o Readability
 High level language is closer to natural language so they are easier to learn and understand
o Machine independent
 High level language program have the advantage of being portable between machines
o Easy debugging
 Easy to find and correct error in high level language
 Disadvantages
o Less efficient
 Takes more memory and more time to execute
Some of the Programming languages are

• Interpreted Programming language

• Functional programming language

• Compiled programming language

• Procedural Programming language

• Scripting programming language

• Markup programming language

• Object-Oriented programming language


Interpreted Programming language

 An interpreted language is a programming language for which executes the program directly,
translating each statement into a sequence of one or more subroutines already compiled into machine
code

Functional Programming Language

 Functional programming language define every computation as a mathematical evaluation


 Some of the functional programming language example are clean, curry, f#, Haskell, Q

Compiled Programming Language

 A compiled programming language is a programming language whose implementations are typically


compilers and not interpreters
 Ada, ALGOL,C ,C ++, C#, COBOL, Java, VB are examples of compiled programming languages

20
Procedural Programming language
 A procedure is a group of statements referenced through a procedure call
 Procedures help in the reuse of code
 Eg: CLIST, Hyper Talk, MATLAB

Scripting programming languages


 Scripting language are programming languages that control an application
 Scripts can execute independent of any other application
 Cold Fusion, PHP, VB Script, Maya

Mark up programming language


 An artificial language that uses annotations to text that define how the text is displayed
 Example: HTML, XML, XHTML, SGML

Object Oriented Programming Languages


 Object oriented programming is based on the concept of objects which may contain data in the form
of procedures often known as methods

Interpreted Programming languages


 Executes instructions directly without previously compiling a program in machine-language
instructions
 Examples
o Java Script
o Python
o Ruby

Algorithmic Problem Solving

 Algorithmic Problem Solving means solving problems that require the formulation of an algorithm for
their solution.
 It includes mainly nine steps they are:
o Understanding the Problem
o Ascertain the capabilities of the computational device
o Choosing between Exact and Approximate Problem Solving
o Deciding a data structure
o Algorithm Design Techniques
o Methods of Specifying an Algorithm
o Proving an Algorithm’s Correctness
o Analyzing an Algorithm
o Coding an Algorithm

21
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.

Ascertain the capabilities of computational device

 Once a problem is understood the capabilities of the computing device has to be ascertained.
 This can be done by knowing the type of the architecture, speed & memory availability.

Choosing between Exact and Approximate Problem Solving

 Once algorithm is devised, it is necessary to show that it computes answer for all the possible legal
inputs.
 This solution is stated in two forms: Exact solution and approximate solution.
 Some examples of problems where an exact solution cannot be obtained are:
o Finding square root of a number
o Solutions of non-linear equations

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
22
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.
 They provide guidance for designing algorithms for new problems.
 Example: Divide and conquer, brute force, Backtracking, Dynamic programming, greedy techniques,
etc.

Methods of Specifying an Algorithm

 There are mainly two options for specifying an algorithm:


o Use of natural language
o Pseudo code and Flow charts
 A Pseudo code is a mixture of natural language and programming language like constructs.
 Flow chart is a method of expressing an algorithm by a collection of connected geometric shapes.

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.

Analysing an Algorithm

1. Efficiency
a. Time Efficiency: Indicating how fast the algorithm runs.
b. Space Efficiency: Indicating how much extra memory it uses.

2. Simplicity
a. An algorithm should be precisely defined and investigated with mathematical expressions.
b. Simpler algorithms are easier to understand and easier to program.
c. Simple algorithms usually contain fewer bugs.

Coding an Algorithm

 Coding is the process of translating the algorithm into a syntax of a given programming language.
 Formal verification is done for small programs.
 Validity is done through testing and debugging.

SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS

 Iterations
 Recursions

23
A sequence of statements is executed until a specific condition is true is called iterations.

I. For loop
II. While loop

Syntax for for loop 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

Recursions

 A function that calls itself is known as recursion.


 Recursion is a process by which a function calls itself repeatedly until some condition has been
satisfied.

Recursive algorithm for Factorial of a given number


Step 1: Start
Step 2: Read number n
Step 3: Call factorial (n)
Step 4: Print factorial f

24
Step 5: Stop

Function Factorial (n)


Step 1: If n==0 then return 1
Step 2: Else f= n* factorial (n-1)
Step 3: Return f

Difference between Recursion and Iteration

Iteration Recursion
 The process is repeated until the condition fails  The function calls itself until the base
condition is satisfied
 It consumes less memory  It consumes more memory
 It is faster  It is slower
 The code is long  The code is short
 Tracing is easier if any problem occurs  Tracing is difficult if any problem
 occurs

Illustrative Problems

1) Finding Minimum in a List


List

1. In Python, list is a data structure which consists of sequence of elements. Each element in a sequence
is assigned with a number called as position or index.

Example

List[0] List[1] List[2] List[3] List[4] List[5]


10 22 5 85 99 6

Minimum Element

Algorithm to Find Minimum in a List Pseudo code for finding minimum in a List
Step 1: Start the program SET initial i
Step 2: Read n READ n
Step 3: Read an list a[] of ‘n’ numbers READ an list a[ ] of ‘n’ numbers
Step 4: Assign first list value to min SET min=a[0]
a[0] FOR i=1 to n
Step 5: For i=1 to n IF a[i]<min THEN
Step 6: if a[i]<min min=a[i]
then min=a[i] END IF
END FOR
Step 7: Repeat step 5 to step 6 until loop
reaches ‘n’
Step 8: Print min
Step 9: Stop

2. Insert a card in a list of sorted cards

25
Description

1. To insert a card in the sorted card we must increase the list size with
2. We can insert a new card in the appropriate position by comparing each elements value.
Example: Initially N=5

List Index List[0] List[1] List[2] List[3] List[4]


Original Cards 3 5 7 9 11

Element to be inserted is10

10<11, Now increase list size by1 and store 11 in 5th position

List Index List[0] List[1] List[2] List[3] List[4] List[5]


Original Cards 3 5 7 9 11

Now you compare 10 with 9. So, it is less than 9

Now you place the new card in 4th position

List Index List[0] List[1] List[2] List[3] List[4] List[5]


Original Cards 3 5 7 9 10 11

Pseudo code for Insert a card in a list of sorted cards

START
READ number of elements in the sorted list, n
SET i=0
WHILE i<n
READ the sorted list element as list[i]
SET i=i+1
END WHILE
READ element to be inserted as x
SET i= n-1
WHILE i>=0 AND x<list[i]
list[i+1] = list[i]
SET i = i-1
END WHILE
list [i+1] = x
END

Algorithm for Insert a card in a list of sorted cards

Step 1: Start

Step 2: Read the number of elements in the sorted list as n

Step 3: Initialize i = 0

26
Step 4: Repeat steps 5 and 6 WHILE i<n

Step 5: Read the sorted list element as list [i]

Step 6: Set i = i+1

Step 7: Read the element to be inserted as x.

Step 8: Set i = n-1

Step 9: Repeat step 9, 10, 11 WHILE i>=0 and x<list [i]

Step 10: list [i+1] =list [i]

Step 11: Set i =i-1

Step 12: list [l+1] = x

Step 13: Stop.

3) Guess an integer number in a range Description

Description

The problem is about to guess what number a computer has in mind.


Objective: Generate a random number between the range (a,b)
Where a is the starting number and b is the end number.
The computer generates one number between the given range
Design algorithm in such a way it prompts the user to enter numbers continuously until it matches
the generated number
Example

 Range (1,20)
 [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
 Computer has selected random number 16

Guess the number between 1 to 20:

Enter your Guess: 19

Sorry, Guess is too high

Enter your Guess: 10

Sorry, Guess is too low

Enter your Guess: 15

Sorry, Guess is too low

Enter your Guess: 18

Sorry, Guess is too high

Enter your Guess: 16


27
Yes Guess is correct Algorithm

Algorithm

Step 1: Generate the random number in between 1 and 20

Step 2: Prompt the user for a guess number

Step 3: If guess>n; print “Sorry, Guess is too high”

Step 4: If guess<n; print “Sorry, Guess is too low”

Step 5: if guess==n; print “Yes Guess is correct”

Step 6: Repeat steps 2 to 5 until the guess is correct.

Step 7: Stop the program

4) Tower of Hanoi

Description

 Tower of Hanoi is a very famous game.


 In this game there are 3 pegs and N number of disks placed one over the other in decreasing size.
 The objective of this game is to move the disks one by one from the first peg to the last peg.
 There is only one condition, we cannot place bigger disk on top of a smaller disk

How to solve Tower of Hanoi?

 Tower of Hanoi can be solved easily by using recursion function

 Tower of Hanoi (disk)=move the disk, if disks=1


Tower of Hanoi (disks-1), if disks > 1
To solve this game we will follow 3 simple steps recursively

We will use a general notation:

28
N denotes the number of disks

T (N,Beg,Aux,End)
Beg is the initial peg

Aux is the auxiliary peg

End is the final peg

Steps

1. T(N-1,Beg,End,Aux)
2. T(1,Beg,Aux,End)
3. T(N-1,Aux,Beg,End)
 Step 1 says: Move top (N-1) disks from Beg to Aux peg.
 Step 2 says: Move 1 disk from Beg to End peg.
 Step 3 says: Move top (N-1) disks from Aux to End peg.

A->C

A->B

29
C->B

A->C

B->A

30
B->C

A->C

Example Algorithm, Pseudo code and Flow charts

Write an algorithm to find area of rectangle


Algorithm Flow chart Pseudo code

31
Step 1: Start BEGIN
Step 2: Get l,b values READ l,b
Step 3: Calculate A=l*b CALCULATE A=l*b
Step 4: Display A DISPLAY A
Step 5: Stop END

Write an algorithm for Calculating area and circumference of circle


Algorithm Flow chart Pseudo code
Step 1: Start BEGIN
Step 2: get r value READ r
Step 3: Calculate A=3.14*r*r CALCULATE A and C
Step 4: Calculate C=2.3.14*r A=3.14*r*r
Step 5: Display A,C C=2*3.14*r
Step 6: Stop DISPLAY A
END

Write an algorithm for Calculating simple interest


Algorithm Flow chart Pseudo code

32
Step 1: Start BEGIN
Step 2: get P, n, r value READ P, n, r
Step3: Calculate SI=(p*n*r)/100 CALCULATE S
Step 4: Display S SI=(p*n*r)/100
Step 5: Stop DISPLAY SI
END

Write an algorithm for Calculating engineering cutoff


Algorithm Flow chart Pseudo code
Step 1: Start BEGIN
Step2: get P,C,M value READ P,C,M
Step3:calculate Cutoff= CALCULATE
(P/4+C/4+M/2) Cutoff= (P/4+C/4+M/2)
Step 4: Display Cutoff DISPLAY Cutoff
Step 5: Stop END

To check greatest of two numbers


Algorithm Flow chart Pseudo code
33
Step 1: Start BEGIN
Step 2: get a,b value READ a,b
Step 3: check if(a>b) print a IF (a>b) THEN
is greater DISPLAY a is greater
Step 4: else b is greater ELSE
Step 5: Stop DISPLAY b is greater
END IF
END

Write an algorithm to check whether given number is +ve, -ve or zero.


Step 1: Start BEGIN
Step 2: Get n value. GET n
Step 3: if (n ==0) print “Given number is Zero” IF(n==0) THEN
Else goto step4 DISPLAY “ n is zero”
Step 4: if (n > 0) then Print “Given number is +ve” ELSE
Step 5: else Print “Given number is -ve” IF(n>0) THEN
Step 6: Stop DISPLAY “n is positive”
ELSE
DISPLAY “n is negative”
END IF
END IF
END

Write an algorithm to print all natural numbers up to n.


Step 1: Start BEGIN
Step 2: get n value. GET n
Step 3: initialize i=1 INITIALIZE i=1
Step 4: if (i<=n) go to step 5 else go to step 8 WHILE(i<=n) DO
Step 5: Print i value PRINT i
34
step 6 : increment i value by 1 i=i+1
Step 7: go to step 4 ENDWHILE
Step 8: Stop END

Write an algorithm to factorial of a given number


Step 1: start BEGIN
step 2: get n value GET n
step 3: set initial value i=1, fact=1 INITIALIZE i=1,fact=1
Step 4: check i value if(i<=n) goto step 5 else goto WHILE(i<=n) DO
step8 fact=fact*i
step 5: calculate fact=fact*i i=i+1
step 6: increment i value by 1 ENDWHILE
step 7: goto step 4 PRINT fact
step 8: print fact value END
step 9: stop

35

You might also like