You are on page 1of 31

Algorithms

Unit-1
Introduction to an Algorithm
 Algorithms are the building blocks of computer programs. They are as important to
programming as recipes are to cooking. An algorithm is a well-defined procedure
that takes input and produces output
 The study of algorithms is one of the key foundations of computer science
 Day to Day problem solving and making strategies to handle different situations.
 Examples :
 Watching TV ( How to operate remote in front of TV)
 Making a cup of coffee or tea (step by step process to making a coffee)
 Plan to go picnic (Sharing money and planning a picnic)
 Every day | Daily activities

 Now we can say that problem is a kind of state or barrier to achieve something and
problem solving is process to get that state removed by performing some sequence
of activities.
Real Life Algorithms
An Algorithm for making cup of coffee
Algorithm begins with input specification. It has to be described in a precise and accurate
manner.
Inputs for making cup of Coffee
1 cup milk, 1 teaspoon sugar, 1 teaspoon of coffee powder, 1 teaspoon of water.
1. Add 1 teaspoon of coffee powder into the cup
2. Add 1 teaspoon sugar into the cup
3. Add 1 teaspoon of water into the cup
4. Stir the ingredients in the cup until well blended
5. Boil milk for 3 minutes of high flame
6. Add hot milk to the coffee syrup and stir until well blended
7. Finally coffee ready
Output specification
At the end of the execution of these instructions that is one cup of hot coffee is ready to
be served.
What is an Algorithm
 Algorithm is a sequence of elementary operations that gives solution to any
problem from a particular specific class of problem in a finite number of
steps.
 A Sequence of activities to be processed for getting desired output from given
input.
 A formula ( Method or Function ) set of steps for solving a particular
problem. To be an algorithm, a set of rules must be unambiguous and have a
clear stopping point.
 There may be more than one way to solve a problem, so there may be more
than one algorithm for a problem.
 As per the above definitions we can say that,
1. Getting desired or specified output is essential after algorithm is executed.
2. One will get output only if algorithm stops after finite time.
3. Activities in an algorithm to be clearly defined in other words for it to be
unambiguous
Think Before Writing An Algorithms Why?
 write an algorithm you must first understand the function that needs to be
performed very clearly.
 If you are not very clear on how to perform the task then you will not be able to
write the algorithm.
 Once you are very clear on how to perform the task and state the steps clearly
and precisely you also need to think about what would be the input specification
and the output specification of the algorithm.
 Notice that the ingredients of the algorithm are input specification and the
output specification.
 Without any of these ingredients the algorithm itself is not complete.
 An algorithm is the heart of problem solving in Computer Science and also Real
Life
Informal definition of an algorithm
used in a computer
 Before writing an algorithm for a problem, we should find
out to followings .
 what is/are the inputs to the algorithm.
 what is/are expected output after running the algorithm.
 While writing algorithms we will use following symbol for
different operations
 „+‟ for Addition
 „-‟ for Subtraction
 „*‟ for Multiplication
 „/‟ for Division
  for assignment
 „>‟ greater than,‟>=„greater than or equal to
 „<„ Less than ,‟<=‟ Less than or equal to
 “==“ Equals to ,‟!=„ not Equals to
For example A  X*3 means A will have a value of X*3.
Qualities of a good algorithm
 Inputs and outputs should be defined precisely.
 Each step in algorithm should be clear and unambiguous.
 Algorithm should be most effective among many different ways to solve a problem
 An algorithm shouldn't have computer code. Instead, the algorithm should be
written in such a way that, it can be used in similar programming languages
Algorithm is not the computer code. Algorithms are just the instruction which
gives clear picture to your idea to write the computer code
We need to make sure that all of these parameters given for a good algorithm are
incorporated when we are actually constructing a good algorithm.
Properties of an algorithm
 Input
 An algorithm accepts zero or more inputs
 Output
 It produces at least one output
 Definiteness
 Each step in algorithm is unambiguous
 This means that the action specified by the step cannot be interpreted (it explain the
meaning of step) in multiple ways & can be performed without any confusion
 Effectiveness
 It consists of basic instructions that are realizable. This means that the instructions can
be performed by using the given inputs in a finite amount of time
 Termination
 An algorithm terminates after a finite numbers of steps
Advantages and Disadvantages of Algorithm
Advantages
 It is a step –by – step representation of a solution to a given problem , which is very
easy to understand
 It has produces a definite procedure.
 It easy to first develop an algorithm , and then convert it into a flowchart and then
into a computer program.
 It is independent of programming language.
 It is easy to debug as every step is got its own logical sequence.
 An algorithm is important in optimizing a computer program according to the available
resources.
 Ultimately when anyone decide to solve a problem through better algorithms then
searching for the best combination of program speed and least amount of memory
consumption is desired
Disadvantages
 It is time consuming and cumbersome (Difficult to handle) as an algorithm is
developed first which is converted into flowchart and then into a computer program.
Algorithm Efficiency
 Speed or Time
An algorithm that takes the least or minimum time to execute
 Space or Memory
An algorithm that uses the least memory or space
 Code or programme or set of Instructions
An algorithm is very shortest description to generate the code
 Speed or Time is the most important factor to build an efficient algorithm
Write an algorithm to find the area of a Circle using radius r

 Inputs to the algorithm:


Radius r of the Circle.
 Expected output:
Area of the Circle
Algorithm
 Step1:Start
 Step2: Read\input the Radius r of the Circle
 Step3: set Area  PI*r*r // calculation of area
 Step4: Print Area
 Step5: End
Write an algorithm to read two numbers and find their sum

 Inputs to the algorithm:


Input Number 1
Input Number 2
 Expected output:
Sum of Number 1 and Number 2
Algorithm
 Step1: Start
 Step2: Input First Number 1
 Step3: Input Second Number 2
 Step4: Set Sum  Number 1 + Number 2
 Step5: Print Sum
 Step6: End
Write an algorithm to Convert temperature
Fahrenheit to Celsius
 Inputs to the algorithm:
Temperature in Fahrenheit
 Expected output:
Temperature in Celsius
Algorithm
 Step1: Start
 Step2: Read Temperature in Fahrenheit F
 Step3: Set C  5/9*(F-32)
 Step4: Print Temperature in Celsius: C
 Step5: End
Types of Control Structures in Algorithms
The algorithm and flowchart, classification to the three types of control structures.
They are:
a. Sequence
b. Branching | Selection | Decision
c. Loop | Repetition
Sequence Algorithm Concepts
 A sequence algorithm is an algorithm that takes one or more linear sequences as inputs.
 In a sequence, there is a linear progression of statements. The result of one statement
is used in subsequent statements. Here are some key actions that are performed and
the common words used in pseudocode
 The sequence is represented by sequence of statements place one after the other – the
one above or before another gets executed first
 Example :- Write an algorithm in pseudocode that finds the average of two numbers
 Step1: Start
 Step2: Declare Variables num1 ,num2,avg ,sum
 Step3: Read | input values num1 ,num2
 Step4: sum  num1 + num2
 Step5: avg sum/2
 Step6: Display the Average of two numbers
 Step6: End

Note :- previous algorithms are the best examples for sequence algorithm
In flowcharts, sequence of statements is usually contained in the rectangular process box
Branching | Selection | Decision
Algorithm Concepts
 IF-THEN-ELSE is decision that is made between two course of actions.
 In a conditional statement you make a test.
 The result of the test is a Boolean - either True or False.
If the result of the test is True you take a certain course of action
if the result of the test is False you take another course of action.

 If the condition is True do a series of actions are executed,


otherwise do another series of actions are executed. The ELSE actions are optional.
Note : In flowcharts, this is represented by the diamond-shaped decision box
 This structure is also known as the selection structure
Write an algorithm to find the Largest number from
given two numbers
 Inputs to the algorithm:
Input num1,num2
 Expected output:
Largest_Num
Algorithm
 Step1: Start
 Step2: Declare variables num1, num2 and Largest_Num
 Step3: Read | input values num1, num2
 Step4: if num1 greater than num2
 4.1 set Largest_Num  num1
else
 4.2 set Largest_Num  num2
 Step 6: endif
 Step7: Print | Display Largest_Num
 Step18: End
Write an algorithm to check voter eligibility criteria
 Inputs to the algorithm:
Input age
 Expected output:
To check eligibility of voter criteria
Algorithm
 Step1: Start
 Step2: Declare variable age
 Step3: Read | input value age
 Step4: if age greater than or equals to 18
 4.1 display “you can vote”
else
 4.2 display “you are not eligible for voting”
 Step5:endif
 Step6: End
Write an algorithm to declare Pass/Fail based on
his/her subject marks
 Inputs to the algorithm:
Input sub_ Mark
 Expected output:
To Display Pass | Fail
Algorithm
 Step1: Start
 Step2: Declare variable sub_Mark
 Step3: Read | input value sub_Mark
 Step4: if sub_Mark greater than or equals to 50
 4.1 display “Passed”
else
 4.2 display “Fail”
 Step5:endif
 Step6: End
Write an algorithm to check leap year
 Inputs to the algorithm:
Input year
 Expected output:
To Display Leap Year or not
Algorithm
 Step1: Start
 Step2: Declare variable year
 Step3: Read | input value year
 Step4: if year %4 is equals to 0 and year %100 is not equals to 0 or year % 400 is equals to 0
 4.1 display “Leap Year”
else
 4.2 display “Common Year”
 Step5:endif
 Step6: End
Write an algorithm to find all roots of a quadratic
equation ax2+bx+c=0.
 Inputs to the algorithm:
a,b,c
 Expected output:
To Display r1, r2 ,rp and ip
Algorithm
 Step 1: Start
 Step 2: Declare variables a, b, c, D, r1, r2, rp , ip;
 Step 3: Calculate discriminant
 3.1 Set D ← b2-4ac
 Step 4: If D≥0
 4.1 Set r1 ← (-b+√D)/2a
 4.2 Set r2 ← (-b-√D)/2a // Display r1 and r2 as roots.
 Else
 4.3 Set rp ← b/2a //Calculate real part and imaginary part
 4.4 Set ip ← root ((-D)/2a)
 4.5 Display rp+j (ip) , rp-j (ip) as roots
 Step 5: Stop
Loop | Repetition algorithm Concepts
 A loop is a sequence that gets executed several times
 A complete execution of a sequence is called an iteration of the loop.
 There are two main loop constructs in programming side - WHILE, FOR and do..While
 WHILE and FOR are sequences of statements that are repeated a number of times
Loop
The sequence is executed as long as the condition is True.
The loop terminates when the condition is False
 Structure
Do the following until (Condition):
do action1
do action2
…..
end
Write an algorithm to print 1 to 100 numbers
(for)

 Inputs to the algorithm:


Input n
 Expected output:
Display 1,2,3,……100
Algorithm
 Step 1: Start
 Step 2: Declare variables n,and i.
 Step 3: Read value of n
 Step 4: Set i←1
 Step 5: Repeat the steps until i equals to n
 5.1: display i
 5.2: increment i
 Step 6: End
Write an algorithm to print 1 to 100 even
numbers
 Inputs to the algorithm:
Input n
 Expected output:
Display 2,4,6……100
Algorithm
 Step 1: Start
 Step 2: Declare variables n,and i.
 Step3: input | read value of n
 Step4: Set i1
 Step5: while i equals to n
 5.1: if remainder of i module 2 equals to 0
 5.1.1 display i

 5.2 Endif
 5.3 increment i
 Step6: Endwhile
 Step 7: End
Write an algorithm to find the factorial of a
number entered by user
 Inputs to the algorithm:
Input n (i.e. factorial of given number(6))
 Expected output:
Factorial of 6 : - 720 (1*2*3*4*5*6)
Algorithm
 Step 1: Start
 Step 2: Declare variables n,factorial and I
 Step3: Read Value n.
 Step4: Set factorial←1
 Step4: Set i←1
 Step 5: Repeat the steps until i equals to n
 5.1 set factorial  factorial*i
 5.2 set increment i
 Step 6: Display factorial
 Step 7: End
Write an algorithm to find the factors of a number
entered by user
 Inputs to the algorithm:
Input fct (i.e. Enter any number to find its factor(6))
 Expected output:
Factors of fct : - 1 2 3 6
Algorithm
 Step 1: Start
 Step 2: Declare variables fct and i
 Step3: Read Value fct.
 Step4: Set i←1
 Step5: Repeat the steps until i greater than fct
 5.1 if fct % i equals to 0 // (remainder of fct/i)
 5.1.1 Display i
 5.2 Endif
 5.3 Set increment i
 Step 6: End
 In the flowcharts, a back arrow hints the presence of a loop.
 A trip around the loop is known as iteration.
 You must ensure that the condition for the termination of the looping must
be satisfied after some finite number of iterations, otherwise it ends up as an
infinite loop,
 You can use a WHILE loop and a FOR loop interchangeably.
 But normally you use a FOR loop when you know the exact number of
iterations of the loop.
 You use a WHILE loop when the number of iterations is not known a priori.
 You can also nest one loop inside another or a conditional inside a loop or
vice versa. It is best to indent your pseudocode to delineate your blocks of
code.
Nested Control Structures
 Combining the use of the control structures with in control Structure
1. a loop within a loop (nested loops)
2. a branch within another branch (nested if)
3. a branch within a loop
4. a loop within a branch
 so forth, is not uncommon.
 Complex algorithms may have more complicated logic structure and deep
level of nesting, in which case it is best to demarcate parts of the algorithm
as separate smaller modules.
Write an algorithm to find the largest among three different numbers
entered by user
Inputs to the algorithm:  Step 1: Start
Input a,b,c  Step 2: Declare variables a, b and c.
Expected output:  Step 3: Read variables a, b and c.
Display highest value
 Step 4: If a greater than b
 4.1 If a greater than c
 4.1.1 Display a is the largest number.
Else
 4.1.2 Display c is the largest number.
 4.2 Endif
Else
 4.3 If b greater than c
 4.3.1 Display b is the largest number.
Else
 4.3.2 Display c is the greatest number.
 4.4 Endif
 Step 5: Endif
 Step 6: End
Write an algorithm to check whether a number entered by user is
prime or not
 Step 1: Start
Inputs to the algorithm:
 Step 2: Declare variables n, i, count.
Enter Checking Number
Expected output:  Step 3: Read n from user
Display Prime | Not Prime  Step 4: Set count←1
 Step 4: Set i←2
 Step 5: Repeat the steps until i less than (n/2)
 5.1 If remainder of n module i equals to 0
 5.1.1 set count←0
 5.2 Endif
 5.3 Set i←i+1
 Step 6: If count equals to 0
 6.1 Display n is not prime
else
 6.2 Display n is prime
 Step 7: Endif
 Step 8: End
Write an algorithm to find the Fibonacci series till term≤1000.

Inputs to the algorithm:  Step 1: Start


Enter Max of Value(1000)  Step 2: Declare variables f1, f2 , temp.
Expected output:
Display 1 1 2 3 5 8 … … … …  Step 3: Set f1 ← 0
 Step 3: Set f2 ← 1
 Step 4: Display f1, f2
 Step 5: Repeat the steps until f2 greater than or equal to 1000
 5.1: Set temp←f2
 5.2: Set f2 ← f2+f1
 5.3: Set f1 ← temp
 5.4: Display f2
 Step 6: Stop

You might also like