UNIT I (1)
UNIT I (1)
1.1 Algorithm
Characteristics of an algorithm
Qualities of an algorithm
Representation of algorithm
Algorithms can be expressed in any language from natural languages (like English,
French, etc.) to programming languages (like Basic, Fortran, etc.).
Algorithm is the basis for most of the programs. Each rule in an algorithm is written
in a programming language. All these rules are collectively called a Program.
Algorithm has a starting point and a final point. Between these two points are the
instructions that solve the problem.
Algorithms often have steps that repeat or require decisions (such as logic or
comparison).
Example of Algorithm
Step 1: Start
Step 2: Read 2-numbers A, B.
Step 3: Add 2-numbers and store result in C.
Step 4: Display the result “C”
Step 5: Stop.
Step 1: Start
Step 2: Read limit of n-values i.e., number of values to be added.
Step 3: Read all n-values one by one
Step 4: Calculate sum of n-values and store result in “sum”
Step 5: Calculate average on n-values using formula sum/n.
Step 6: Print sum and average.
Step 7: Stop.
Step 1: Start
Step 2: Read 3 numbers A, B and C.
Step 3: Compare A and B. If A is greater perform Step 4 else perform Step 5
Step 4: Compare A and C. If A is greater, Print “A is Big” else Print “C is Big”.
Step 5: Compare B and C, If B is greater, Print “B is Big” else Print “C is Big”.
Step 6: Stop.
Step 1: Start
Step 2: Read 2 numbers A and B.
Step 3: Compare A and B.
Step 4: If A is greater, print “A is Big” else Print “B is Big”.
Step 5: Stop.
Step 1: Start
Step 2: Read a number “n”
Step 3: Initialize the value of variable “fact” to 1.
Step 4: Set a loop to find the factorial of the given number “n” using formula
fact=fact*i.
Step 5: Print the factorial of the given number
Step 6: Stop.
Practice algorithm for following questions
Statements
State
Control flow
Functions
1.2.1 Statements
Kinds of Statements
Simple Statement
Compound Statement
Simple Statement
Simple statement refers algorithm statement which contains single step or single
action.
Example
Compound Statement
Algorithm may contain one or more statements illustrating single action is called
compound statement. Statements are enclosed between “begin” and “end” keywords.
Example
Block Statement:
begin
….
….
end
do-loop:
do
{ ….
….
}while(condtion)
for-loop:
for(condition)
{ ….
….
}
if-statement:
if(condition)
{ ….
….
}
else
{
….
….
}
switch-statement:
switch (c)
{
case ‘a’: alert();
break;
case ‘q’: quit();
break;
}
while-loop:
while(condition)
do
{
….
….
}
1.2.2 State
Many programming languages have what are called control flow statements; used to
determine what section of code is run in a program at a given time. Control flow is the order
of function calls, instructions, and statements are executed or evaluated when a program is
running.
Program control structures are defined as the program statements that specifies the
order in which statements are executed. A program is not limited to a linear sequence of
instructions. Understanding the logic of the program is very difficult for someone other than
developers. Hence, modification, enhancement and maintenance of these programs were very
difficult.
As the name suggests the sequential control structure is used to perform the actions one
after another in sequential order. It performs process A and then performs process B and so
on. This structure is represented by writing one process after another. The logic flow is top to
bottom approach.
Example
Step 1: Start
Step 2: Read limit of n-values i.e., number of values to be added.
Step 3: Read all n-values one by one
Step 4: Calculate sum of n-values and store result in “sum”
Step 5: Calculate average on n-values using formula sum/n.
Step 6: Print sum and average.
Step 7: Stop.
In the above example flow control is sequential order. All the statements are executed one
after another.
Selection Control Flow
Selection control structures (or) Decision structures allows the program to make a
choice between two alternate paths whether it is true or false. IF...THEN or IF..THEN..ELSE
or a case structures are the selection structures. This logic is used for making decisions.
Example
Step 1: if(a>b)
Step 2: print “a is greater”
Step 3: else
Step 4: print “a is greater”
In the above example flow control is selection order. If Step 1 is true, step 2 will be selected
for execution. If Step 1 is false, step 4 will be selected for execution.
1.2.4 Functions
Functions are “self contained” modules of code that accomplish a specific task.
Functions usually “take in” data, process it, and “return” a result. Once a function is written,
it can be used over and over and over again. Functions can be “called” from the inside of
other functions. Functions “Encapsulate” a task (they combine many instructions into a single
unit of code).
Example
Pseudo code is an outline of a program written in the form that can be easily
converted into programming statements. Pseudo code use styled English language to
represent the process of computer program. Pseudo code is skeleton form of all programming
language.
Pseudo code is a kind of structure English for designing algorithm. Pseudo codes came
from two words. Pseudo and code pseudo means imitation and code refer to instructions,
written in a programming language.
Pseudo code cannot be compiled nor executed, and there are no real formatting or
syntax rules. The benefit of pseudo code is that it enables the programmer to concentrate on
the algorithms without worrying about all the syntactic details of a particular programming
language. In fact, you can write pseudo code without even knowing what programming
language you will use for the final implementation.
There are few standard keywords used for representing various actions. They are,
1. Input READ, GET, INPUT
2. Output PRINT, DISPLAY, SHOW, OUTPUT
3. Calculations CALCULATE, COMPUTE, ADD, SUBTRACT, INITIALIZE
4. Incrementing INCREMENT, DECREMENT
READ A, B
COMPUTE C by adding A with B
PRINT C
STOP
READ n
FOR (i=0;i<n;i++)
READ all inputs a[i]
END FOR
COMPUTE SUM by adding all values
CALCULATE AVG by dividing SUM by n
DISPLAY SUM and AVG
STOP
READ A,B
IF (A>B)
DISPLAY “A is greater”
ELSE
PRINT :B is greater”
STOP
READ A,B,C
IF (A>B)
IF (A>C)
DISPLAY “A is greater”
ELSE IF (B>C)
PRINT “B is greater”
ELSE
PRINT “C is greater”
STOP
SET sum=0
FOR (i=0;i<=100;i++)
CALCULATE sum=sum+i
EN FOR
PRINT sum
STOP
6. Pseudo code to find sum of n-even numbers
READ n
INITIALIZE i=0
SET sum=0
DO WHILE (i<n)
COMPUTE sum=sum+i
i =i+2
END DO
WRITE sum
STOP
READ num
INITIALIZE fact=1
FOR (i=1;i<num;i++)
fact=fact*i
END FOR
OUTPUT fact
STOP
Flow charts are easy to understand diagrams showing how steps in a process fit
together. This makes them useful tools for communicating how processes work, and for
clearly documenting how a particular job is done. Furthermore, the act of mapping a process
out in flow chart format helps you clarify your understanding of the process, and helps you
think about where the process can be improved.
Flowchart Symbols
Advantage / Benefits
Limitations / Disadvantage
In sequence control structure, the steps are executed in linear order one after the other.
Flow of the control is sequential in order from top to bottom.
Start
Read A, B
Flow of given
flowchart is
C =A+ B sequential
Print C
Stop
Start
Read A, B
No
If Print “B is
A>B greater”
Yes
Print “A is greater”
Stop
In the above flowchart, flow of control is not in sequential order. Here if condition is
true, path towards “Yes” branch will be flowed. If condition is false, path towards “No”
branch will be flowed. Hence flow of control is selected based on a specific condition, it is
called as “Selection control flowchart”.
Start
Read n
False
for (i=1;i<n;i++)
Average = sum/n
Stop
Example Flowchart to find greatest of 3-numbers
Start
Read A,B,C
Yes No
If If
A> A>
B C
No Yes
No
If
B>
Print A Print C
C
Yes
Print B
Print C
Stop
Machine Language
Example
10101010
11110000
10001001
01010111
Assembly Language
Assembly languages have the same structure and set of commands as machine
languages, but they enable a programmer to use names instead of numbers. Each type
of CPU has its own machine language and assembly language, so an assembly
language program written for one type of CPU won't run on another. In the early days of
programming, all programs were written in assembly language.
An assembly language is a low-level programming language for microprocessors and
other programmable devices. It is not just a single language, but rather a group of languages.
An assembly language implements a symbolic representation of the machine code needed to
program a given CPU architecture. Assembly language is also known as assembly code
Example
Start
add x,y
sub x,y
…
…
end
High Level Language
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter 2 numbers:");
scanf("%d%d",&a,&b);
if(a>b)
{
printf("%d is greater",a);
}
else
{
printf("%d is greater",b);
}
getch();
}
Algorithms are procedural solutions to problems. These solutions are not answers but
specific instructions for getting answers. Algorithmic problem solving is about the
formulation and solution of problems where the solution involves principals and techniques
that have been developed to assist in the construction of correct algorithms.
Decide on:
Computational means, exact vs.
approximate solving, algorithm design
technique
Design an Algorithm
Prove Correctness
Before designing an algorithm you have to understand completely the problem given.
Read the problem’s description carefully and ask questions if there are any doubts
about the problem, do a few small examples by hand, think about special cases, and ask
questions again if needed. An input to an algorithm specifies an instance of the problem the
algorithm solves. It is important to specify exactly the range of instances the algorithm needs
to handle.
Once you completely understand a problem, you need to ascertain the capabilities of the
computational device the algorithm is intended for.
Sequential algorithms: Instructions are executed one after another, one operation at a time.
Accordingly, algorithms designed to be executed on such machines.
Parallel algorithms: The central assumption of the RAM model does not hold for some
newer computers that can execute operations concurrently, i.e., in parallel.
c) Choosing between Exact and Approximate Problem Solving
First, there are important problems that simply cannot be solved exactly for most of
their instances; examples include extracting square roots, solving nonlinear equations, and
evaluating definite integrals. Second, available algorithms for solving a problem exactly can
be unacceptably slow because of the problem’s intrinsic complexity. This happens, in
particular, for many problems involving a very large number of choices. Third, an
approximation algorithm can be a part of a more sophisticated algorithm that solves a
problem exactly
In the new world of object oriented programming, data structures play an important
role for both design and analysis of algorithms. Data structures can be defined as a particular
scheme of organizing related data items.
Algorithms + Data Structures = Programs
First, they provide guidance for designing algorithms for new problems, i.e., problems
for which there is no known satisfactory algorithm. Second, algorithms are the cornerstone of
computer science. Every science is interested in classifying its principal subject, and
computer science is no exception. Algorithm design techniques make it possible to classify
algorithms according to an underlying design idea; therefore, they can serve as a natural way
to both categorize and study algorithms.
Once an algorithm is designed, you need to specify it in some fashion. Free and also a
step-by-step form is Pseudocode. These are the two options that are most widely used
nowadays for specifying algorithms.
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. This representation technique has
proved to be inconvenient for all but very simple algorithms.
g) Proving an Algorithm’s Correctness
Once an algorithm has been specified, it has to be proved for 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.
h) Analyzing an Algorithm
If users are not satisfied with the algorithm’s efficiency, simplicity, or generality, user
must return to the drawing board and redesign the algorithm. In fact, even if your evaluation
is positive, it is still worth searching for other algorithmic solutions.
i) Coding an Algorithm
Iteration and recursion are key Computer Science techniques used in creating
algorithms and developing software. In simple terms, an iterative function is one that loops to
repeat some part of the code, and a recursive function is one that calls itself again to repeat
the code. Using a simple for loop to display the numbers from one to ten is an iterative
process. Solving the Eight Queens Problem is a simple recursive process.
Recursion Iteration
Repetition is achieved through Iteration is explicitly a repetition
repeated function calls structure
Recursion terminates when a base caseIteration terminates when the loop
is recognized continuation test becomes false
Recursion causes an-
other copy of the function Iteration normally occurs within
and hence a considerable a loop, so the extra memory
memory space is occupied. assignment is omitted.
When a function call itself repeatedly until some specified condition is satisfied is
called as recursion. Recursive functions are commonly used in applications in which the
solution to a problem can be expressed in terms of successively applying the same solution to
subsets of the problem.
A classic example is the recursive method for computing the factorial of a number.
The factorial of an integer n, which is written as n!, is the result of multiplying n by all of the
positive integers less than n.
Factorial of 5 5 * 4 * 3 * 2 * 1 = 120
fact(5) = 5 * fact(4)
fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1
Example:
Definition part of the function factorial is the result of factorial performed on a smaller
integer. By calling itself, it can multiply the number by each positive number less than it and
then return the final result. Recursive functions can be useful in other calculations, such as
calculating Fibonacci numbers or the greatest common divisor
Algorithm Flowchart
Algorithm Flowchart
Pseudocode
Algorithm Flowchart
Algorithm Flowchart
Algorithm Flowchart
Algorithm Flowchart
Algorithm Flowchart
Algorithm Flowchart
Algorithm Flowchart
Step 1 : Start
Step 2 : Initialize value of fact and i to 1 Start
Step 3 : READ the value of n.
Initialize fact,i = 1
Step 4 : If i <= n do the following
else Goto step6.
Read n
Step 4.1 : fact = fact*i
No
Step 4.2 : i=i*+1 If
(i < n)
Step 5 : Goto step4
Yes
fact = fact * i
i=i+1
Step 6 : Print fact
Step 7 : Stop
Algorithm Flowchart
Step 1 : Start
Step 2 : Initialize r=0, sum=0 Start
Step 3 : READ the value of n.
r=0, sum=0
Step 4 : If n > 0 do the following
else Goto step6.
Read n
Step 4.1 : r = n % 10
No
Step 4.2 : sum = sum *10 + r If
(n > 0)
Step 4.3 : n = n / 10
Yes
Step 5 : Goto step4
r = n % 10
sum = sum *10 + r
Step 7 : Stop
Pseudocode
Print sum
Set initial sum=0, i=0
READ the value of n
Stop
WHILE (n > 0)
r = n % 10
Logic: n=7
0, 1, 1, 2, 3, 5, 8
Algorithm Flowchart
Step 1 : Start
Step 2 : Initialize a=0, b=1 Start
Step 3 : READ the value of n.
a = 0, b = 1
Step 4 : FOR (i=1; i < n; i++)
Step 4.1 : WRITE a
Read n
No
Step 4.2 : c = a + b
for(i=1;i<n;i+
Step 4.3 : a = b +)
Step 4.4 : b = c Yes
To find the minimum value into an array of items, take the first element and compare
its value against the values of order elements. Find the minimum.
Algorithm
Example
List[0] 2
List[1] 3
List[2] 5
List[3] 9
List[4] 1
List[5] 6
List[6] 8
List[7] 7
Python Program
x = [2,3,5,9,1,6,8,7]
def my_min(sequence):
low = sequence[0] # need to start with some value
for i in sequence:
if i < low:
low = i
print(low)
my_min(x)
Output
1
1.7.2. Find the insert a card in a list of sorted cards
To insert a card in the sorted card, user must increase the list size with 1. User can
insert a new card in the appropriate position by comparing each element’s value with the new
card. When the position is found, user has to move the remaining elements one position up
and the card can be inserted in appropriate position
Algorithm
Example
List[0] 2
List[1] 3
List[2] 4
List[3] 6
List[4] 8
List[5] 9
Position to be inserted is List[3] hence move elements from List[3] one step down
List[0] 2
List[1] 3
List[2] 4
List[3]
List[4] 6
List[5] 8
List[6] 9
New List
List[0] 2
List[1] 3
List[2] 4
List[3] 5
List[4] 6
List[5] 8
List[6] 9
Python Program
import random
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
number_of_decks = 4
define function to define the cards def
cards_define_function(): cards = deck *
number_of_decks return cards
define the cards
cards = cards_define_function()
define function remove card def
remove_card(string): return
cards.remove(string)
define a function for computer cards def computer_cards():
computer_card_one = random.choice(cards)
remove_card(computer_card_one)
computer_card_two = random.choice(cards)
remove_card(computer_card_two)
computer_total = computer_card_one + computer_card_two return
computer_card_one, computer_card_two, computer_total
define a function for user’s initial cards def user_cards():
user_card_one = random.choice(cards)
remove_card(user_card_one) user_card_two =
random.choice(cards)
remove_card(user_card_two)
user_total = user_card_one + user_card_two return
user_card_one, user_card_two, user_total
define a single random card function
def one_more_card():
extra_card = random.choice(cards)
remove_card(extra_card)
return extra_card
define computer random card function def
computer_new_random_card(): computer_new_card =
random.choice(cards)
remove_card(computer_new_card)
return computer_new_card
define cards lists (user and computer)
computer_cards = list(computer_cards())
user_cards = list(user_cards())
define computer stands on
computer_stands_on = 17
define the showing functions def
computer_show():
print(“Computer has {}”.format(computer_cards)) def
user_show():
print(“You have {}”.format(user_cards)) def
bust():
print(“BUST! You lost, that was easy money for the Computer!”) def
ask_again():
new_answer = input(“Computer stands on {}. Do you want another card?
“.format(computer_stands_on))
return new_answer
define function to ask user (main function) def
ask_user_initial():
answer = input(“Your first card is {}, computer’s first card is {}, type ‘SHOW’ to
show your other card! “
.format(user_cards[0], computer_cards[0]))
if answer != ‘’:
user_show()
while user_cards[len(user_cards)-1] <= 21:
new_answer = ask_again()
if new_answer == ‘yes’ or new_answer == ‘YES’:
extra_card = one_more_card()
user_cards[len(user_cards)-1] += extra_card
print(“Your new card is a {}!”.format(extra_card))
print(“Your new total is {}”.format(user_cards[len(user_cards)-1]))
user_cards.insert(len(user_cards)-1, extra_card)
else:
case 1 while computer total < computer_stands_on -> draw card
computer has to draw its new card/cards
while computer_cards[len(computer_cards)-1] < computer_stands_on:
computer_new_card = computer_new_random_card() print(“Computer has drawn
{}”.format(computer_new_card)) computer_cards[len(computer_cards)-1] +=
computer_new_card computer_cards.insert(len(computer_cards)-1,
computer_new_card)
case 2 else show user’s and computer’s results else:
if computer_cards[len(computer_cards)-1] <= 21:
if computer_cards[len(computer_cards)-1] < user_cards[len(user_cards)-1]:
print(“Your total is {}”.format(user_cards[len(user_cards)-1])) user_show()
print(“Computer has {}”.format(computer_cards)) print(“CONGRATS, it
looks like you won this one! Let’s play again!”) break
elif computer_cards[len(computer_cards)-1] > user_cards[len(user_ cards)-1]:
print(“Your total is {}”.format(user_cards[len(user_cards)-1]))
user_show()
print(“Computer has {}”.format(computer_cards))
print(“OOOOPS, You should have asked for ANOTHER card, computer wins
AGAIN!”)
break
else:
print(“Your total is {}”.format(user_cards[len(user_cards)-1]))
print(“Computer has {}”.format(computer_cards))
print(“This is a PUSH, it was a nice hand both of you played great!”)
break
else:
print(“Your total is {}”.format(user_cards[len(user_cards)-1]))
user_show()
print(“Computer has {}”.format(computer_cards))
print(“CONGRATS, it looks like you won this one! Let’s play again!”)
break
else:
bust()
user_show()
while computer_cards[len(computer_cards)-1] < computer_stands_on:
computer_new_card = computer_new_random_card()
print(“Computer has drawn {}”.format(computer_new_card))
computer_cards[len(computer_cards)-1] += computer_new_card
computer_cards.insert(len(computer_cards)-1, computer_new_card)
computer_show()
ask_user_initial()
Output
Your first card is 2, computer’s first card is 5, type ‘SHOW’ to show your other card! 4
You have [2, 2, 4]
Computer stands on 17. Do you want another card? 2
Computer has drawn 10
Your total is 4
You have [2, 2, 4]
Computer has [5, 10, 10, 25]
CONGRATS, it looks like you won this one! Let’s play again!
1.7.3. Find the guess an integer number in a range:
Algorithm
Program
import random
BOUNDS = (1, 100)
TRIES_ALLOWED = 5
the_number = random.randint(*BOUNDS)
print(“\tWelcome to ‘Guess My Number’!\n”)
print(“I’m thinking of a number between %d and %d.” % BOUNDS)
print(“Try to guess it in as few attempts as possible.\n”)
for tries in range(TRIES_ALLOWED):
guess = int(input(“Take a guess: “))
if guess > the_number:
print(“Lower...”)
elif guess < the_number:
print(“Higher...”)
else:
print(“You guessed it! The number was %d” % (the_number))
print(“And it only took you %d tries!\n\n” % (tries + 1))
break
else:
print(“You failed to guess in time!\n\n”)
Admittedly a contorted way to write a statement that works in both Python 2 and 3...
try:
input(“Press the enter key to exit.”)
except:
pass
Output
def __init__(self):
self.counter = 0
def hanoi(self,n, a, c, b):
if n == 1:
self.counter += 1
print('{0}->{1}'.format(a, b))
else:
self.hanoi(n -1, a, b, c)
self.hanoi(1, a, c, b)
self.hanoi(n-1, b, c, a)
tower=Tower()
tower.hanoi(3,"a", "c", "b")
Output