SlideShare a Scribd company logo
Unit 2: Linear Data Structure
Array- 1D and 2D array,
Stack - Applications of stack: Expression Evaluation - Conversion of Infix to postfix and prefix
expression, Tower of Hanoi.
Queue - Types of Queue: Circular Queue, Double Ended Queue (deQueue), Applications –
Priority Queue using Arrays,
List - Singly linked lists – Doubly linked lists - Circular linked lists
Array
• An array is a collection of similar data elements.
• These data elements have the same data type.
• Array is a non-primitive Linear Data Structures where the elements are stored
linearly or in a sequential manner.
• The elements of the array are stored in consecutive memory locations and are
referenced by an index (also known as the subscript).
Declaration of array
• To declare linear or simple array, you have to specify the name of the data type
and the number of elements inside the square brackets.
type name [size];
type . type of the array you want to declare
Name . name of the array
Size . specific size of the array
• Example of some array:
int num[5];
char name[20];
float max[10];
Declaration of array
• For declaring multi-dimensional array, you have to specify type of array and the
number of rows and columns.
type name [rows] [coloumns];
• Example of multidimensional array:
int arr [3] [3];
float max [5] [4];
Initialization of an array
• Each time when we using array, it is not necessary that the values to be stored
in the array should accept from the user.
• We can also initialize the values when we declare the array.
• Declaration the values of array at designing time is called array initialization.
• Example –
int num[5] = { 2, 8, 7, 6, 0 } ;
int arr[3][3] = {{10, 20, 45}, {42, 79, 81}, {89, 9, 36}}
Calculating the Address of Array Elements
• The array name is a symbolic reference to the address of the first byte of the array.
• When we use the array name, we are actually referring to the first byte of the
array.
• The address of other data elements can simply be calculated using the base
address.
• The formula to perform this calculation is,
Address of data element, A[k] = BA(A) + w(k – lower_bound)
Here, A is the array,
k is the index of the element of which we have to calculate the address,
BA is the base address of the array A,
w is the size of one element in memory, for example, size of int is 2.
Calculating the Address of Array Elements
Example
• Given an array int marks[] = {99,67,78,56,88,90,34,85}, calculate the address of
marks[4] if the base address = 1000.
• We know that storing an integer value requires 2 bytes, therefore, its size is 2
bytes.
marks[4] = 1000 + 2(4 – 0)
= 1000 + 2(4) = 1008
Calculating the Address of Array Elements
• For multidimensional array
• If the array elements are stored in column major order,
Address(A[I][J]) = Base_Address + w{M ( J – 1) + (I – 1)}
• And if the array elements are stored in row major order,
Address(A[I][J]) = Base_Address + w{N ( I – 1) + (J – 1)}
• where w is the number of bytes required to store one element,
• N is the number of columns, M is the number of rows,
• I and J are the subscripts of the array element.
Calculating the Address of Array Elements
Example
• Consider a 20 x 5 two-dimensional array marks which has its base address =
1000 and the size of an element = 2. Now compute the address of the element,
marks[18][ 4] assuming that the elements are stored in row major order.
Address(A[I][J]) = Base_Address + w{N (I – 1) + (J – 1)}
Address(marks[18][4]) = 1000 + 2 {5(18 – 1) + (4 – 1)}
= 1000 + 2 {5(17) + 3}
= 1000 + 2 (88)
= 1000 + 176 = 1176
TMK_DSA_Unit 2 part1(array and stack).pptx
OPERATIONS ON ARRAYS
There are a number of operations that can be preformed on arrays. These
operations include:
• Traversing an array
• Inserting an element in an array
• Searching an element in an array
• Deleting an element from an array
• Merging two arrays
• Sorting an array in ascending or descending order
Sparse Matrix
• A matrix is a two-dimensional data object made of m rows and n columns,
therefore having m x n values. When m=n, we call it a square matrix.
• If a large number of elements of the matrix are zero elements, then it is called
a sparse matrix.
REPRESENTATION OF SPARSE MATRICES using Vector
• Representing a sparse matrix by using a two-dimensional array leads to the
wastage of a substantial amount of space.
• Therefore, an alternative representation must be used for sparse matrices. One
such representation is to store only non- zero elements along with their row
positions and column positions.
• A= vector which contain non-zero element of sparse matrix
• JA=vector stores column indices of elements in A
• The IA vector is of size m+1 stores the cumulative number of non-zero elements
upto ( not including) the i-th row. It is defined by the recursive relation :
• IA[0] = 0
• IA[i] = IA[i-1] + no of non-zero elements in the (i-1) th row of the Matrix
REPRESENTATION OF SPARSE MATRICES using Vector
• the A vector is [ 5 8 3 6]
• JA = [ 0 1 2 1] //Column index of element of A
• IA[0] = 0.
• IA[1] = IA[0] + no of non-zero elements in row 0
i.e 0 + 0 = 0.
Similarly,
IA[2] = IA[1] + 2 = 2
IA[3] = IA[2] + 1 = 3
IA[4] = IA[3]+1 = 4
Therefore IA = [0 0 2 3 4] //no of row +1 elements
REPRESENTATION OF SPARSE MATRICES using Vector
• A = [10 20 30 4 50 60 70 80],
• IA = [0 2 4 7 8]
• JA = [0 1 1 3 2 3 4 5]
REPRESENTATION OF SPARSE MATRICES using linked
list
• Representing a sparse matrix by using a two-dimensional array leads to the wastage of a substantial
amount of space.
• Therefore, an alternative representation must be used for sparse matrices. One such representation is
to store only non- zero elements along with their row positions and column positions.
• That means representing every non-zero element by using triples (i, j, value), where i is a row position
and j is a column position, and store these triples in a linear list.
• It is possible to arrange these triples in the increasing order of row indices, and for the same row index
in the increasing order of column indices.
• Each triple (i, j, value) can be represented by using a node having four fields as shown in the following:
Struct snode{
int row,col,val;
Struct snode *next;
};
REPRESENTATION OF SPARSE MATRICES
• Example
Stack
• Stack is a non-primitive and linear data structure where insertion and deletion
is done at only one end i.e. the TOP (Top of the Stack).
• Stack follows the LIFO (Last In First Out) structure. TOP stores the address of
the topmost element of the stack.
• E.g.:- The example of the stack is stack of plates in a cafeteria where every new
plate is added to the top. Similarly the plate is also taken off the plates.
ARRAY REPRESENTATION OF STACKS
• The stack can be represented as a linear array.
• Every stack has a variable called TOP associated with it, which is used to store
the address of the topmost element of the stack.
• It is this position where the element will be added to or deleted from.
• There is another variable called MAX, which is used to store the maximum
number of elements that the stack can hold.
• If TOP==-1 then it indicates that the stack is empty and if TOP = MAX–1,
then the stack is full.
#define MAX 50
int stack[MAX], top=-1;
Operations on Stack
• A stack supports main three basic operations: push, pop, and peek.
• The push operation adds an element to the top of the stack
• The pop operation removes the element from the top of the stack.
• The peek operation returns the value of the topmost element of the stack.
Other operation
• isEmpty(): It determines whether the stack is empty or not (Underflow).
• isFull(): It determines whether the stack is full or not (Overflow).
• display(): It prints all the elements available in the stack.
PUSH Operation on Stack
• The push operation is used to insert an element into the stack.
• The new element is added at the topmost position of the stack
• Before inserting an element in a stack, we check whether the stack is full(i.e. check the
condition top==MAX-1 where MAX= maximum size of stack).
• If we try to insert the element in a full stack, then the overflow condition occurs (Overflow
message need to print).
• When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top (top is initialized
as -1 to check that the stack is empty).
PUSH Operation on Stack
• Algorithm to insert element in the stack
PUSH(value)
{
//value=data to be inserted
Step1: check that stack is full
If TOP==MAX-1
Write(‘ overflow’)
Return
Step 2: if stack is not full increment top pointer
and insert data into stack
TOP=TOP+1
Stack[TOP]=Value
}
//C code for PUSH operation
void Push(int value)
{
if(TOP==MAX-1)
{
printf(“nStack is full—Overflow”);
return;
}
else
stack[++TOP]=value;
}
Pop Operation on Stack
• The pop operation is used to delete the topmost element from the stack.
• Before deleting the element from the stack, we check whether the stack is empty.
i.e. check the condition top==-1).
• If we try to delete the element in an empty stack, then the underflow condition
occurs (Underflow message need to print).
• If the stack is not empty, we first access the element which is pointed by the top.
• Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
POP Operation on Stack
• Algorithm to delete an element from the stack
POP()
{
//return popped element
Step 1: check stack is empty
If TOP==-1
Write(‘ underflow’)
Return -1
Step 2: if stack is not empty store the value,
Decrement the top and return store value
Value =Stack[TOP]
TOP=TOP-1
return Value
}
//C code for Pop operation
int POP()
{
if(TOP==-1)
{
printf(“nStack is empty—Underflow”);
return -1;
}
else
return(Stack[top--]);
}
Peek Operation on Stack
• Peek is an operation that returns the value of the topmost element of the stack
without deleting it from the stack.
• However, the Peek operation first checks if the stack is empty, i.e., if TOP ==-1, then
an appropriate message is printed, else the value is returned
PEEK Operation on Stack
• Algorithm to return topmost element from the stack
PEEK()
{
//return topmost element
Step 1: check stack is empty
If TOP==-1
Write(‘ underflow’)
Return -1
Step 2: if stack is not empty return the top of stack
value
Value =Stack[TOP]
return Value
}
//C code for Pop operation
int PEEK()
{
if(TOP==-1)
{
printf(“nStack is empty—Underflow”);
return -1;
}
else
return(Stack[top]);
}
Display Operation on Stack
• Display is an operation that display the stack elements starting from topmost
element of the stack and then gradually moving down to the stack.
Algorithm to display elements from the stack
Display()
{
If TOP==-1
Write(‘ underflow’)
Return
For i=TOP to 0
write( stack[i])
}
//C code for Pop operation
void Display()
{
int i;
if(TOP==-1)
{
printf(“nStack is empty—Underflow”);
return;
}
printf(“nStack elements are as below:n”);
for(i=TOP;i>=0;i--)
printf(“%d”,stack[i]);
}
APPLICATIONS OF STACKS
• Reversing a list
• Parentheses checker
• Conversion of an infix expression into a postfix expression
• Evaluation of a postfix expression
• Conversion of an infix expression into a prefix expression
• Evaluation of a prefix expression
• Recursion
• Tower of Hanoi
Reverse a list
• A list of elements can be reversed by reading each elements from an array
starting from the first index and pushing it on a stack.
• Once all the elements have been read, the elements can be popped one at a
time and then stored in the array starting from the first index.
//Algorithm for reverse a list
Reverse(Arr, Size)
For i=0 to length of Arr-1
Push(Arr[i]);
For i=0 to length of Arr-1
Arr[i]=Pop()
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 20
int top = -1;
char stack[MAX];
void push(char item)
{
if(top == (MAX-1))
{
printf("nStack Overflown");
return;
}
stack[++top] =item;
}
char pop()
{
if(top == -1)
{
printf("nStack Underflown");
return(-1);
}
return stack[top--];
}
void reverse(char str[])
{
int i;
//Push string on the stack
for(i=0;i<strlen(str);i++)
push(str[i]);
//Pop characters from the stack and store in string str
for(i=0;i<strlen(str);i++)
str[i]=pop();
}
int main()
{
char str[20];
printf("Enter the string : " );
gets(str);
reverse(str);
printf("nReversed string is : ");
puts(str);
return 0;
}
C code for Reverse a string
Parentheses checker
• Stacks can be used to check the validity of parentheses in any algebraic expression.
• For example, an algebraic expression is valid if for every open bracket there is a corresponding
closing bracket.
For example,
• Input: exp = “[()]{}{[()()]()}”
• Output: Balanced
• Explanation: all the brackets are well-formed
• Input: exp = “[(])”
• Output: Not Balanced
• Explanation: 1 and 4 brackets are not balanced because
• there is a closing ‘]’ before the closing ‘(‘
Parentheses checker
• Following steps are follow to check expression has balanced parenthesis or not
1. Declare a character stack and read the expression.
2. Now traverse the string exp.
1. If the current character is a starting bracket ( ‘(‘ or ‘{‘ or ‘[‘ ) then push it to stack.
2. If the current character is a closing bracket ( ‘)’ or ‘}’ or ‘]’ ) then pop from the stack
and if the popped character is the matching starting bracket then fine.
3. Else brackets are Not Balanced.
3. After complete traversal, if some starting brackets are left in the stack then
the expression is Not balanced, else Balanced.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
char stack[MAX_SIZE];
int top = -1;
void push(char data) {
if (top == MAX_SIZE - 1) {
printf("Overflow stack!n");
return;
}
stack[++top] = data;
}
char pop() {
if (top == -1) {
printf("Empty stack!n");
return(-1);
}
return(stack[top--]);
}
int is_matching_pair(char char1, char char2) {
if (char1 == '(' && char2 == ')') {
return 1;
} else if (char1 == '[' && char2 == ']') {
return 1;
} else if (char1 == '{' && char2 == '}') {
return 1;
} else {
return 0;
}
}
int main() {
char exp[MAX_SIZE];
int i;
printf("Input an expression in parentheses: ");
gets(exp);
for (i = 0; i < strlen(exp); i++)
{
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
push(exp[i]);
else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}')
{
if(!is_matching_pair(pop(), exp[i]))
{
printf("The expression is not balanced.n");
return(0);
}
}
}
if (top==-1)
printf("The expression is balanced.n");
else
printf("The expression is not balanced.n");
return 0;
} C code for balanced parenthesis
checker
Conversion of an Infix Expression into a Postfix Expression
• Polish notation: Polish notation is also called prefix notation. It means that
operations are written before the operands.
• Postfix notation: the operator is placed after the operands for example the
infix expression a+b will be written as ab+ in postfix notation .
• Postfix notation is also called as Reverse Polish Notation or RPN.
• To convert one form of expression to another form, we need to take care
about precedence and associativity of the operator.
Operator Precedence Associativity
+,- 1 Left associative
*, / 2 Left associative
^ 3 Right associative
Conversion of an Infix Expression into a Postfix Expression
The idea to convert infix to postfix expression
Step 1: Scan the infix expression from left to right and repeat the step2 to step 6 until end of expression
Step 2: If the scanned character is an operand, put it in the postfix expression.
Step 3: If the scanned character is a ‘(‘, push it to the stack.
Step 4: If the scanned character is a ‘)’, pop the stack and put it to postfix expression until a ‘(‘ is
encountered, and discard both the parenthesis.
Step 5: if scanned character is operator other than ‘^’(right associative) ,
• If the precedence and associativity of the scanned operator are greater than the precedence and associativity of the
operator in the stack [or the stack is empty or the stack contains a ‘(‘ ], then push it in the stack
• Else Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned
operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then
stop there and push the scanned operator in the stack.)
Step 6: If scanned character is operator ‘^’ , push it on to the top of the stack
Step 7: Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is
not empty.
Step 8: Finally, print the postfix expression.
Step 1: Scan the expression from left to right and for each scanned element do following
Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty. (if pop
element is ‘(‘ print message expression invalid)
Scanned Input Action
Operand Insert it into the postfix expression
‘(‘ opening bracket push it to the stack
‘)’ closing bracket pop the stack and output it until a ‘(‘ is encountered, and discard both the
parenthesis. (if ‘(‘ is not found or stack become empty- print message expression invalid
‘^’ Operator Push ‘^’ on to the stack
Operator other than
‘^’
If(precedence(stack[top]) >=precedence of scanned input
1. Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator. (If we encounter parenthesis while
popping then stop.)
2. After doing that Push the scanned operator to the stack.
If(precedence(stack[top]) < precedence of scanned input
Pushed scanned operator into stack
Infixtopostfix(infix)
Len=length(infix)
Postfix=[]
J=1
For i=0 to len-1
if(isoperand(infix[i]) // if operand then insert into postfix expression
postfix[j]=infix[i]
j=j+1;
else if(infix[i]==‘(‘) // if ‘(‘ push into stack
push(‘(‘)
else if (infix[i]==‘)’) //if input is ‘)’ then pop the stack element until ‘(‘ found and add into postfix
while (top > -1 && stack[top] != '(')
postfix[j] = pop()
j=j+1
if (top > -1 && stack[top] != '(')
return "Invalid Expression";
else
pop(); // pop ‘(‘ on top of the stack
else if(isoperator(infix[i])
//operator other than ‘^’, pop the stack elements until it’s precedence higher or equal
to scanned operator after that push scanned operator into stack
if(infix[i]!=‘^’)
while (top > -1 && precedence(stack[top]) >= precedence(infix[i]) && stack[top]!=‘(‘)
postfix[j] = pop()
j=j+1
//push scanned operator on top of the stack
push(infix[i])
//after scanning infix expression
//pop all the remaining elements for the stack and insert to postfix
while (top > -1)
if (stack[top] == '(')
return "Invalid Expression";
postfix[j] = pop()
j=j+1
return postfix;
x-(y*a/b-(z+d*e)+c)/f
x-(y*a/b-(z+d*e)+c)/f
x-(y*a/b-(z+d*e)+c)/f
TMK_DSA_Unit 2 part1(array and stack).pptx
TMK_DSA_Unit 2 part1(array and stack).pptx
(A+(B*C-(D/E^F)*H))
Convert following infix expression
into postfix expression using stack.
(A-B)/C*D^(E/F)^(G+H)
Convert: a- ( b/c + (d % e* f ) / g) * h
Infix Character scanned Stack Postfix expression
a a
- - a
( - ( a
b - ( ab
/ - ( / ab
c - ( / abc
+ - ( + abc/
( - ( + ( abc/
d - ( + ( abc/d
% - ( + ( % abc/d
e - ( + ( % abc/de
* - ( + ( % * abc/de
Convert: a- ( b/c + (d % e* f ) / g) * h
Infix Character scanned Stack Postfix expression
f - ( + ( % * abc/def
) - ( + abc/def*%
/ - ( + / abc/def*%
g - ( + / abc/def*%g
) - abc/def*%g/+
* - * abc/def*%g/+
h - * abc/def*%g/+h
abc/def*%g/+h*-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char item)
{
if (top == MAX - 1)
{
printf("Stack Overflown");
return;
}
stack[++top] = item;
}
char pop()
{
if (top == -1)
{
printf("Stack Underflown");
return -1;
}
return stack[top--];
}
// Function to return precedence of operators
int precedence(char operator)
{
switch (operator)
{
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default:
return -1;
}
}
int isOperator(char ch)
{
return (ch == '+' || ch == '-' || ch == '*' || ch == '/'
|| ch == '^'|| ch=='%');
}
C code infix to postfix conversion
// function to convert infix expression to postfix expression
char* infixToPostfix(char* infix)
{
int i, j=0;
int len = strlen(infix);
char* postfix = (char*)malloc(sizeof(char) * (len + 2));
for (i = 0; i < len; i++)
{
if (infix[i] == ' ' || infix[i] == 't')
continue;
// If the scanned character is operand add it to the postfix expression
if (isalnum(infix[i]))
postfix[j++] = infix[i];
// if the scanned character is '(' push it in the stack
else if (infix[i] == '(')
push(infix[i]);
/* if the scanned character is ')' pop the stack and add it to the output
string until empty or '(' found*/
else if (infix[i] == ')') {
while (top > -1 && stack[top] != '(')
postfix[j++] = pop();
if (top > -1 && stack[top] != '(')
return "Invalid Expression";
else
pop();
}
// If the scanned character is an operator,
/*pop the stack element until its precedence higher
or equal than input operator or "(" not encontered in
stack
// push it in the stack
else if (isOperator(infix[i]))
{
if(infix[i]!='^')
{
while (top > -1 && precedence(stack[top])
>= precedence(infix[i]) && stack[top]!='(')
postfix[j++] = pop();
}
push(infix[i]);
}
}//for loop
// Pop all remaining elements from the stack
while (top > -1) {
if (stack[top] == '(')
return "Invalid Expression";
postfix[j++] = pop();
}
postfix[j] = '0';
return postfix;
}
int main()
{
char infix[MAX],*postfix;
printf("nEnter the infix expression: ");
gets(infix);
postfix=infixToPostfix(infix);
printf("n Postfix expression: %s", postfix);
free(postfix);
return 0;
}
C code infix to postfix conversion
Evaluating a Postfix Expression
• Given an algebraic expression written in infix notation, the computer first
converts the expression into the equivalent postfix notation and then evaluates
the postfix expression.
• Both these tasks—converting the infix notation into postfix notation and
evaluating the postfix expression—make extensive use of stacks as the primary
tool.
Algorithm to evaluate Postfix Expression
Step 1: Scan the given expression from left to right and repeat the step 2 until
end of the expression
Step2:
2.a If a operand is encountered, push it to Stack
2.b If the operator is encountered (op), pop two elements from stack as A and B ,
Evaluate the expression B op A and push the result of evaluation on the stack
Step 3: When the expression is ended, the number in the stack is the final
answer, return it
Evaluation of Postfix Expression: Example
Consider the expression: exp = “2 3 1 * + 9 -“
Evaluation of Postfix Expression: Example
Consider the expression: exp = “2 3 1 * + 9 -“
Evaluation of Postfix Expression: Example
Consider the expression: exp = “2 3 1 * + 9 -“
Evaluation of Postfix Expression: Example
Consider the expression: exp = “2 3 1 * + 9 -“
Evaluation of Postfix Expression: Example
Consider the expression: exp = “2 3 1 * + 9 -“
There are no more elements to scan, we return the top element from the stack (which is the only
element left in a stack).  So the result becomes -4
Evaluation of Postfix Expression: Example
Consider the expression: exp = “456*+
Input Symbol Operation Stack Calculation
4 Push 4
5 Push 4 5
6 Push 4 5 6
*
Pop 2 Element, Evaluate it and
Push result
4 30 5*6 =30
+ Pop 2 Element, Evaluate it and
Push result
34 4+30=34
No more input POP Empty 12 Result
Evaluation of Postfix Expression: Example
Consider the expression: exp = “532*+4-5+
Input Symbol Operation Stack Calculation
5 Push 5
3 Push 5 3
2 Push 5 3 2
* Pop 2 Element, Evaluate it and
Push result
5 6 3*2 =6
+
Pop 2 Element, Evaluate it and
Push result 11 5+6=11
4 Push 11 4
-
Pop 2 Element, Evaluate it and
Push result
11-4=7
5 Push 7 5
+
Pop 2 Element, Evaluate it and
Push result 12 7+5=12
No more input POP Empty 12 Result
Evaluation of Postfix Expression: Example
Consider the expression: exp = “5 9 3 + 4 2 * * 7 + *”
9 3 4 * 8 + 4 / –
Algorithm to evaluate prefix Expression
There are more than one way to evaluate a prefix expression
Method 1
Step 1: Reverse the expression (now expression become postfix)
Step 2: Scan the given expression from left to right and repeat the step 3 until end of
the expression
Step3:
3.a If a operand is encountered, push it to Stack
3.b If the operator is encountered (op), pop two elements from stack as A and B ,
Evaluate the expression B op A and push the result of evaluation on the stack
Step 4: When the expression is ended, the number in the stack is the final answer,
return it
Algorithm to evaluate prefix Expression
There are more than one way to evaluate a prefix expression
Method 2
Step 1: Scan the given expression from right to left and repeat the step 2 until
end of the expression
Step2:
2.a If a operand is encountered, push it to Stack
2.b If the operator is encountered (op), pop two elements from stack as A and B ,
Evaluate the expression A op B and push the result of evaluation on the stack
Step 3: When the expression scanning completed, the number in the stack is the
final answer, return it
Algorithm to evaluating a Prefix Expression
Solution using Method 2
//Evaluation of postfix/prefix expression
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
int stack[MAX];
int top = -1;
void push(int item) {
if (top == MAX - 1)
{
printf("Stack Overflown");
return;
}
stack[++top] = item;
}
int pop() {
if (top == -1)
{
printf("Stack Underflown");
return -1;
}
return stack[top--];
}
int is_operator(char symbol)
{
if (symbol == '+' || symbol == '-' || symbol == '*'
|| symbol == '/' || symbol=='%' || symbol=='^')
{ return 1; }
return 0;
}
int evaluate_postfix(char* exp)
{
int i = 0,num,top=-1;
int op1, op2, result;
while (exp[i] != '0')
{
if (exp[i] >= '0' && exp[i] <= '9')
{
num = exp[i] - '0';
push(num);
}
else if (is_operator(exp[i]))
{
op2 = pop();
op1 = pop();
switch(exp[i])
{
case '+': result = op1 + op2; break;
case '-': result = op1 - op2; break;
case '*': result = op1 * op2; break;
case '/': result = op1 / op2; break;
case '%': result = op1 % op2; break;
case '^': result = op2 ^ op1; break;
default : break;
}
push(result);
}
i++;
}
result = pop();
return result; }
C code for evaluation of expression
int evaluate_prefix(char* exp)
{
int i = 0,num,len=strlen(exp);
int op1, op2, result,top=-1;
for(i=len-1;i>=0;i--)
{
if (exp[i] >= '0' && exp[i] <= '9')
{
num = exp[i] - '0';
push(num);
}
else if (is_operator(exp[i]))
{
op1 = pop();
op2 = pop();
switch(exp[i])
{
case '+': result = op1 + op2; break;
case '-': result = op1 - op2; break;
case '*': result = op1 * op2; break;
case '/': result = op1 / op2; break;
case '%': result = op1 % op2; break;
case '^': result = op2 ^ op1; break;
default : break;
}
push(result);
}
}
result = pop();
return result;
}
int main() {
char exp[MAX];
int result,ch;
do
{
printf("n1. Evaluate Postfix expression: ");
printf("n2. Evaluate Prefix expression: ");
printf("n3. Exit");
printf("n Enter the Choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("nEnter the Postfix expression: ");
fflush(stdin);
gets(exp);
result = evaluate_postfix(exp);
printf("Result= %dn", result);
break;
case 2: printf("nEnter the Prefix expression: ");
fflush(stdin);
scanf("%s",exp);
result = evaluate_prefix(exp);
printf("Result= %dn", result);
break;
default: break;
}
}while(ch!=3);
return 0;
}
C code for evaluation of expression
Conversion of an Infix Expression into a Prefix Expression
• A prefix notation is another form of expression but it does not require other information
such as precedence and associativity, whereas an infix notation requires information of
precedence and associativity.
• It is also known as polish notation.
• In prefix notation, an operator comes before the operands. The syntax of prefix notation is
given below:
<operator> <operand> <operand>
• For example, if the infix expression is 5+1, then the prefix expression corresponding to this
infix expression is +51.
• If the infix expression is: a * b + c then corresponding prefix expression is *a+bc
Conversion of an Infix Expression into a Prefix Expression
The idea to convert infix to prefix expression
Step 1: Reverse the infix expression. Note while reversing each ‘(‘ will become ‘)’
and each ‘)’ becomes ‘(‘.
Step 2: Convert the reversed infix expression to “nearly” postfix expression.
• While converting to postfix expression, instead of using pop operation to pop operators
with greater than or equal precedence, here we will only pop the operators from stack
that have greater precedence.
Step 3: Reverse the postfix expression.
Step 2: Scan the expression from left to right and for each scanned element do following
Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty. (if pop element is ‘(‘
print message expression invalid)
Scanned Input Action
Operand Insert it into the postfix expression
‘(‘ opening bracket push it to the stack
‘)’ closing bracket pop the stack and output it until a ‘(‘ is encountered, and discard both the
parenthesis. (if ‘(‘ is not found or stack become empty- print message expression invalid
‘^’ Operator If(precedence(stack[top]) = precedence of scanned input
1. pop the top of the stack till the condition is true (If we encounter parenthesis while
popping then stop there and push the scanned operator in the stack.)
2. Push ‘^’ on to the stack
Operator other than
‘^’
If(precedence(stack[top]) >precedence of scanned input
1. Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator. (If we encounter parenthesis while
popping then stop there and push the scanned operator in the stack.)
2. After doing that Push the scanned operator to the stack.
If(precedence(stack[top]) <= precedence of scanned input
Pushed scanned operator into stack
Algorithm Infixtoprefix(infix)
//reverse the expression
Reverse(infix)
//replace “(“ with “)” and vice versa
Brackets(infix)
//convert into posfix
prefix=infixtopostfix(infix)
//reverse the postfix expression
Reverse(prefix)
Return(prefix)
Algorithm Infixtopostfix(infix)
Len=length(infix)
Postfix=[]
J=1
For i=0 to len-1
if(isoperand(infix[i]) // if operand then insert into postfix expression
postfix[j]=infix[i]
j=j+1;
else if(infix[i]==‘(‘) // if ‘(‘ push into stack
push(‘(‘)
else if (infix[i]==‘)’) //if input is ‘)’ then pop the stack element until ‘(‘ found and add into postfix
while (top > -1 && stack[top] != '(')
postfix[j] = pop()
j=j+1
if (top > -1 && stack[top] != '(')
return "Invalid Expression";
else
pop()// pop ‘(‘ on top of the stack
else if(isoperator(infix[i])
if((precedence(stack[top]) == precedence(infix[i])) && infix[i] == '^’)
while((precedence(stack[top]) == precedence(infix[i])) && infix[i] == '^‘ && top > -1 && stack[top]!='(')
postfix[j] = pop()
j=j+1
else if(precedence(stack[top]) > precedence(infix[i]))
while (top > -1 && precedence(stack[top]) > precedence(infix[i]) && stack[top]!='(')
postfix[j] = pop()
j=j+1
push(infix[i])
//after scanning infix expression
//pop all the remaining elements for the stack and insert to postfix
while (top > -1)
if (stack[top] == '(')
return "Invalid Expression";
postfix[j] = pop();
j=j+1
return postfix;
Infix Expression into a Prefix Expression conversion: Example
Consider: K + L - M * N + (O^P) * W/U/V * T + Q
We need first to reverse the expression.
The Reverse expression would be:
Q + T * V/U/W * ( P^O)+ N*M - L + K
Q + T * V/U/W * ) P^O(+ N*M - L + K
Q + T * V/U/W * ) P^O(+ N*M - L + K
Now reverse the result
++-+KL*MN*//*^OPWUVTQ
Infix Expression into a Prefix Expression conversion: Example
Consider: ((a / b) + c) - (d + (e * f ))
We need first to reverse the expression.
The Reverse expression would be:
((f*e)+d)-(c+(b/a))
((f*e)+d)-(c+(b/a))
Input expression Stack Prefix expression
((f*e)+d)-(c+(b/a))
Now reverse the result
-+/abc+d*ef
Input expression Stack Prefix expression
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char item)
{
if (top == MAX - 1)
{
printf("Stack Overflown");
return;
}
stack[++top] = item;
}
char pop()
{
if (top == -1)
{
printf("Stack Underflown");
return -1;
}
return stack[top--];
}
// Function to return precedence of operators
int precedence(char operator)
{
switch (operator)
{
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default:
return -1;
}
}
int isOperator(char ch)
{
return (ch == '+' || ch == '-' || ch == '*' || ch == '/'
|| ch == '^'|| ch=='%');
}
C code infix to prefix conversion
void reverse (char *infix)
{
int size = strlen (infix);
int j = size, i = 0;
char temp[size];
temp[j--] = '0';
while (infix[i] != '0')
{
temp[j] = infix[i];
j--;
i++;
}
strcpy (infix, temp);
}
void brackets (char *infix)
{
int i = 0,len=strlen(infix);
for (int i = 0; i < len; i++)
{
if (infix[i] == '(')
infix[i] = ')';
else if (infix[i] == ')')
infix[i] = '(';
}
}
C code infix to prefix conversion
// function to convert infix expression to postfix expression
char* infixToPostfix(char* infix)
{
int i, j=0;
int len = strlen(infix);
char* postfix = (char*)malloc(sizeof(char) * (len + 2));
for (i = 0; i < len; i++)
{
if (infix[i] == ' ' || infix[i] == 't')
continue;
// If the scanned character is operand add it to the postfix expression
if (isalnum(infix[i]))
postfix[j++] = infix[i];
// if the scanned character is '(' push it in the stack
else if (infix[i] == '(')
push(infix[i]);
/* if the scanned character is ')' pop the stack and add it to the output string until empty or '(' found*/
else if (infix[i] == ')') {
while (top > -1 && stack[top] != '(')
postfix[j++] = pop();
if (top > -1 && stack[top] != '(')
return "Invalid Expression";
else
pop();
}
// If the scanned character is an operator,
/*pop the stack element until its precedence higher l than input operator or "(" not encontered in stack
// push it in the stack
if((precedence(stack[top]) == precedence(infix[i])) && infix[i] == '^')
{
while((precedence(stack[top]) == precedence(infix[i])) && infix[i] == '^')
postfix[j++] = pop();
}
else if(precedence(stack[top]) > precedence(infix[i]))
{
while (top > -1 && precedence(stack[top]) > precedence(infix[i]) && stack[top]!='(')
postfix[j++] = pop();
}
push(infix[i]);
}
}
// Pop all remaining elements from the stack
while (top > -1) {
if (stack[top] == '(')
return "Invalid Expression";
postfix[j++] = pop();
}
postfix[j] = '0';
return postfix;
}
char *infixtoprefix(char *infix)
{
// Reverse String and replace ( with ) and vice versa
// Get Postfix
// Reverse Postfix
char *prefix;
// Reverse infix
reverse(infix);
// Replace ( with ) and vice versa
brackets(infix);
prefix = infixToPostfix(infix);
// Reverse postfix
reverse(prefix);
return prefix;
}
int main()
{
char infix[MAX],*prefix;
printf("nEnter the infix expression: ");
gets(infix);
prefix=infixtoprefix(infix);
printf("n Prefix expression: %s", prefix);
free(prefix);
return 0;
}
C code infix to prefix conversion
Recursion
Recursion
• Since a recursive function repeatedly calls itself, it makes use of the system
stack to temporarily store the return address an local variables of the calling
function.
• Every recursive solution has two major cases. They are
1. Base case, in which the problem is simple enough to be solved directly without making
an further calls to the same function.
2. Recursive case, in which first the problem at hand is divided into simpler sub-parts.
Second the function calls itself but with sub-parts of the problem obtained in the first
step. Third, the result is obtained by combining the solutions of simpler sub-parts.
Recursion- Example- Factorial of n
• let us take an example of calculating factorial of a number.
• To calculate n!, we multiply the number with factorial of the number that is 1 less than
that number i.e n!=n*(n-1)!.
• Iterative implementation
int Factorial(int n)
{
int fact = 1;
for(int count = 2; count <= n; count++)
fact = fact * count;
return fact;
}
Time complexity
T(n)=O(n)
Recursion- Example- Factorial of n
• Recursive implementation
• Every recursive function must have a base case and a recursive case.
• For the factorial function,
• Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1.
• Recursive case of the factorial function will call itself but with a smaller value of
n, this case can be given as
factorial(n) = n × factorial (n–1) int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
Recursion- Example- Factorial of n
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Call Factorial(5) = 5 x factorial(4)
TOP
• When ever function call happen its information like return address,
local and temporary variable stores in stack inform of activation
record – call to function result in push an activation record on
system stack.
• During returning from function its activation record popped from
the stack
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Activation Record of
Factorial(4)
Factorial(5) = 5 x factorial(4)
Call Factorial(4) = 4 x factorial (3)
TOP
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Activation Record of
Factorial(4)
Activation Record of
Factorial(3)
Factorial(5) = 5 x factorial(4)
Factorial(4) = 4 x factorial (3)
Call Factorial(3) = 3 x factorial (2)
TOP
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Activation Record of
Factorial(4)
Activation Record of
Factorial(3)
Activation Record of
Factorial(2)
Factorial(5) = 5 x factorial(4)
Factorial(4) = 4 x factorial (3)
Factorial(3) = 3 x factorial(2)
Call Factorial(2) = 2 x factorial (1)
TOP
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Activation Record of
Factorial(4)
Activation Record of
Factorial(3)
Activation Record of
Factorial(2)
Activation Record of
Factorial(1)
Factorial(5) = 5 x factorial(4)
Factorial(4) = 4 x factorial (3)
Factorial(3) = 3 x factorial(2)
Factorial(2) = 2 x factorial (1)
Call Factorial(1) = 1 x factorial (0)
TOP
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Activation Record of
Factorial(4)
Activation Record of
Factorial(3)
Activation Record of
Factorial(2)
Activation Record of
Factorial(1)
Factorial(5) = 5 x factorial(4)
Factorial(4) = 4 x factorial (3)
Factorial(3) = 3 x factorial(2)
Factorial(2) = 2 x factorial (1)
Factorial(1) = 1 x factorial (0) replace with 1
Factorial(0) = return 1
TOP
int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
So, factorial(0) return 1,
and its information
removed from the stack
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Activation Record of
Factorial(4)
Activation Record of
Factorial(3)
Activation Record of
Factorial(2)
Factorial(5) = 5 x factorial(4)
Factorial(4) = 4 x factorial (3)
Factorial(3) = 3 x factorial(2)
Factorial(2) = 2 x factorial (1)
Factorial(1) = 1 x 1 (return 1)
TOP
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Activation Record of
Factorial(4)
Activation Record of
Factorial(3)
Factorial(5) = 5 x factorial(4)
Factorial(4) = 4 x factorial (3)
Factorial(3) = 3 x factorial(2)
Factorial(2) = 2 x 1
TOP
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Activation Record of
Factorial(4)
Factorial(5) = 5 x factorial(4)
Factorial(4) = 4 x factorial (3)
Factorial(3) = 3 x 2
TOP
Recursion- Example- Factorial of n
System stack
Activation Record of
Factorial(5)
Factorial(5) = 5 x factorial(4)
Factorial(4) = 4 x 6 TOP
Recursion- Example- Factorial of n
System stack
Factorial(5) = 5 x 24 =120 return TOP
Recursion- Example- Fibonacci number
• The Nth Fibonacci number is the sum of the previous two Fibonacci numbers
• 0, 1, 1, 2, 3, 5, 8, 13, …
• Recursive Design:
• Recursive case:
• fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
• Base case:
• fibonacci(1) = 0
• fibonacci(2) = 1
Recursion- Example- Fibonacci number
int fibonacci(int n)
{
int fib;
if (n > 2)
fib = fibonacci(n-1) + fibonacci(n-2);
else if (n == 2)
fib = 1;
else
fib = 0;
return fib;
}
Recursion- Example- Greatest Common Divisor
• The greatest common divisor of two numbers (integers) is the largest integer that
divides both the numbers.
• We can find the GCD of two numbers recursively by using the Euclid’s algorithm
that states
• GCD can be implemented as a recursive function because if b does not divide a,
then we call the same function (GCD) with another set of parameters that are
smaller than the original ones.
• Here we assume that a > b. However if a < b, then interchange a and b in the
formula given above.
Recursion- Example- Greatest Common Divisor
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
return y;
else
return (GCD(y, rem));
}
Recursion- Example- Finding Exponents
• We can also find exponent of a number using recursion. To find xy, the base
case would be when y=0, as we know that any number raised to the power 0 is
1.
• Therefore, the general formula to find xy
can be given as
Recursion- Example- Finding Exponents
int exp_rec(int x, int y)
{
if(y==0)
return 1;
else
return (x * exp_rec(x, y–1));
}
Tower of Hanoi
Tower of Hanoi
Given N discs of decreasing size stacked on one needle
and two empty needles, it is required to stack all the
discs onto a second needle in decreasing order of size.
The third needle may be used as temporary storage.
The movement of discs is restricted by the following
rules :
1. Only one disc can be moved at a time.
2. A disc may be moved from any needle to any other.
3. At no time may a larger disc rest upon a smaller disc.
3
2
1
A B C
Problem
3
2
1
A B C
Solution
3
2
A B C
Step
Move 1: move disk 1 from A to C
1
3 2
A B C
Step
Move 2: move disk 2 from A to B
1
3 2
A B C
Step
Move 3: move disk 1 from C to B
1
3
2
A B C
Step
Move 4: move disk 3 from A to C
1
3
2
A B C
Step
Move 5: move disk 1 from B to A
1
3
2
A B C
Step
Move 6: move disk 2 from B to C
1
3
2
A B C
Step
Move 7: move disk 1 from A to C
1
Algorithm for solving this problem :
The solution of this problem is most clearly seen with the
aid of induction. To move 1 disc, merely move it from
needle A to needle C. To move 2 discs, move the first
disc to needle B, move the second from needle A to
needle C, then move the disc from needle B to needle C.
In general the solution of the problem of moving N disc
from needle A to C has 3 steps :
1. Move N-1 discs from A to B.
2. Move disc N from A to C.
3. Move N-1 discs from B to C.
C program
#include <stdio.h>
#include <conio.h>
Void TowerOfHanoi(char,char,char);
void main ()
{
int N;
char A=‘A’, B=‘B’, C=‘C’;
printf(“ntEnter the No. of discs : “);
scanf ( “%d", & N);
TowerOfHanoi ( N, A, B, C);
}
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(3,A,B,C)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(3,A,B,C)
Print(3 from A to C)
Hanoi(2,B,A,C)
Call Hanio(2,A,C,B)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(2,A,C,B)
Print(2 from A to B)
Hanoi(1,C,A,B)
Print(3 from A to C)
Hanoi(2,B,A,C)
Call Hanio(1,A,B,C)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(1,A,B,C)
Print(1 from A to C)
Hanoi(0,B,A,C)
Print(2 from A to B)
Hanoi(1,C,A,B)
Print(3 from A to C)
Hanoi(2,B,A,C)
Call Hanio(0,A,C,B)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,A,C,B)
Print(1 from A to C)
Hanoi(0,B,A,C)
Print(2 from A to B)
Hanoi(1,C,A,B)
Print(3 from A to C)
Hanoi(2,B,A,C)
RETURN Pop this element
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,A,C,B)
Print(2 from A to B)
Hanoi(1,C,A,B)
Print(3 from A to C)
Hanoi(2,B,A,C)
move disk 1 from A to C
Call Hanoi(0,B,A,C)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,B,A,C)
Print(2 from A to B)
Hanoi(1,C,A,B)
Print(3 from A to C)
Hanoi(2,B,A,C)
RETURN Pop this element
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,B,A,C)
Print(3 from A to C)
Hanoi(2,B,A,C)
move disk 2 from A to B
Call Hanoi(1,C,A,B)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(1,C,A,B)
Print(1 from C to B)
Hanoi(0,A,C,B)
Print(3 from A to C)
Hanoi(2,B,A,C)
Call Hanoi(0,C,B,A)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,C,B,A)
Print(1 from C to B)
Hanoi(0,A,C,B)
Print(3 from A to C)
Hanoi(2,B,A,C)
RETURN Pop this element
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,C,B,A)
Print(3 from A to C)
Hanoi(2,B,A,C)
move disk 1 from C to B
Call Hanoi(0,A,C,B)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,A,C,B)
Print(3 from A to C)
Hanoi(2,B,A,C)
RETURN Pop this element
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,A,C,B)
move disk 3 from A to C
Call Hanoi(2,B,A,C)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(2,B,A,C)
Print(2 from B to C)
Hanoi(1,A,B,C)
Call Hanio(1,B,C,A)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(1,B,C,A)
Print(1 from B to A)
Hanoi(0,C,B,A)
Print(2 from B to C)
Hanoi(1,A,B,C)
Call Hanio(0,B,A,C)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,B,A,C)
Print(1 from B to A)
Hanoi(0,C,B,A)
Print(2 from B to C)
Hanoi(1,A,B,C)
RETURN Pop this element
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,A,C,B)
Print(2 from B to C)
Hanoi(1,A,B,C)
move disk 1 from B to A
Call Hanoi(0,C,B,A)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,C,B,A)
Print(2 from B to C)
Hanoi(1,A,B,C)
RETURN Pop this element
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,C,B,A)
move disk 2 from B to C
Call Hanoi(1,A,B,C)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(1,A,B,C)
Print(1 from A to C)
Hanoi(0,B,A,C)
Call Hanio(0,A,C,B)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,A,C,B)
Print(1 from A to C)
Hanoi(0,B,A,C)
RETURN Pop this element
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,A,C,B)
Print(1 from A to C)
Hanoi(0,B,A,C)
move disk 1 from A to C
Call Hanoi(0,B,A,C)
C program
void TowerOfHanoi ( int N, char A, char B, char C )
{
if ( N != 0 )
{
TowerOfHanoi ( N-1, A, C, B);
printf (“ntMove Disc %d from %c to %c”, N,A,C);
TowerOfHanoi ( N-1, B, A, C);
}
}
Call Hanio(0,B,A,C)
RETURN TO MAIN
TMK_DSA_Unit 2 part1(array and stack).pptx
Number of Disk: 4
Advantage of recursion
• Recursive solutions often tend to be shorter and simpler than non-recursive
ones.
• Code is clearer and easier to use.
• Recursion works similar to the original formula to solve a problem.
• Recursion follows a divide and conquer technique to solve problems.
• In some (limited) instances, recursion may be more efficient.
Drawback of recursion
• For some programmers and readers, recursion is a difficult concept.
• Recursion is implemented using system stack. If the stack space on the system
is limited, recursion to a deeper level will be difficult to implement.
• Aborting a recursive program in midstream can be a very slow process.
• Using a recursive function takes more memory and time to execute as
compared to its nonrecursive counterpart.
• It is difficult to find bugs, particularly while using global variables.

More Related Content

PPTX
Basic of array and data structure, data structure basics, array, address calc...
PDF
M v bramhananda reddy dsa complete notes
PPTX
U2.pptx Advanced Data Structures and Algorithms
PPTX
data structure unit -1_170434dd7400.pptx
PDF
PPT
Arrays and vectors in Data Structure.ppt
PDF
DSA UNIT II ARRAY AND LIST - notes
PPTX
unit 2.pptx
Basic of array and data structure, data structure basics, array, address calc...
M v bramhananda reddy dsa complete notes
U2.pptx Advanced Data Structures and Algorithms
data structure unit -1_170434dd7400.pptx
Arrays and vectors in Data Structure.ppt
DSA UNIT II ARRAY AND LIST - notes
unit 2.pptx

Similar to TMK_DSA_Unit 2 part1(array and stack).pptx (20)

PPTX
هياكلبيانات
PPTX
The document discusses arrays in data structures using Cpp programming langua...
PPTX
DSA Unit II array.pptx
PDF
Data Structures Notes 2021
PPTX
arrays.pptx
PPTX
Data Structures - Array presentation .pptx
PPTX
data structures array and sparse matrics
PPTX
data structures study meterial array and sparse matric
PPTX
PPTX
Data Structure Introduction- Arrays, Matrix, Linked List
PPT
Linear Data Structures, array, stack, queue
PPTX
unit-2-dsa.pptx
PPTX
ADVANCED DATA STRUCTURES AND ALGORITHMS.pptx
PDF
Data Structure Lecture Array and Recursion.pdf
PPTX
Data Structure
PPT
Data Structures: A Foundation for Efficient Programming
PDF
1-Intoduction ------------- Array in C++
PPTX
introduction of Data strutter and algirithm.pptx
DOCX
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
PPT
1st lecture.ppt
هياكلبيانات
The document discusses arrays in data structures using Cpp programming langua...
DSA Unit II array.pptx
Data Structures Notes 2021
arrays.pptx
Data Structures - Array presentation .pptx
data structures array and sparse matrics
data structures study meterial array and sparse matric
Data Structure Introduction- Arrays, Matrix, Linked List
Linear Data Structures, array, stack, queue
unit-2-dsa.pptx
ADVANCED DATA STRUCTURES AND ALGORITHMS.pptx
Data Structure Lecture Array and Recursion.pdf
Data Structure
Data Structures: A Foundation for Efficient Programming
1-Intoduction ------------- Array in C++
introduction of Data strutter and algirithm.pptx
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
1st lecture.ppt
Ad

Recently uploaded (20)

PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Construction Project Organization Group 2.pptx
PDF
Well-logging-methods_new................
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
Artificial Intelligence
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
UNIT 4 Total Quality Management .pptx
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Safety Seminar civil to be ensured for safe working.
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
composite construction of structures.pdf
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Operating System & Kernel Study Guide-1 - converted.pdf
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Construction Project Organization Group 2.pptx
Well-logging-methods_new................
R24 SURVEYING LAB MANUAL for civil enggi
CYBER-CRIMES AND SECURITY A guide to understanding
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Artificial Intelligence
Automation-in-Manufacturing-Chapter-Introduction.pdf
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Model Code of Practice - Construction Work - 21102022 .pdf
UNIT 4 Total Quality Management .pptx
Mechanical Engineering MATERIALS Selection
Safety Seminar civil to be ensured for safe working.
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
composite construction of structures.pdf
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
CH1 Production IntroductoryConcepts.pptx
Ad

TMK_DSA_Unit 2 part1(array and stack).pptx

  • 1. Unit 2: Linear Data Structure Array- 1D and 2D array, Stack - Applications of stack: Expression Evaluation - Conversion of Infix to postfix and prefix expression, Tower of Hanoi. Queue - Types of Queue: Circular Queue, Double Ended Queue (deQueue), Applications – Priority Queue using Arrays, List - Singly linked lists – Doubly linked lists - Circular linked lists
  • 2. Array • An array is a collection of similar data elements. • These data elements have the same data type. • Array is a non-primitive Linear Data Structures where the elements are stored linearly or in a sequential manner. • The elements of the array are stored in consecutive memory locations and are referenced by an index (also known as the subscript).
  • 3. Declaration of array • To declare linear or simple array, you have to specify the name of the data type and the number of elements inside the square brackets. type name [size]; type . type of the array you want to declare Name . name of the array Size . specific size of the array • Example of some array: int num[5]; char name[20]; float max[10];
  • 4. Declaration of array • For declaring multi-dimensional array, you have to specify type of array and the number of rows and columns. type name [rows] [coloumns]; • Example of multidimensional array: int arr [3] [3]; float max [5] [4];
  • 5. Initialization of an array • Each time when we using array, it is not necessary that the values to be stored in the array should accept from the user. • We can also initialize the values when we declare the array. • Declaration the values of array at designing time is called array initialization. • Example – int num[5] = { 2, 8, 7, 6, 0 } ; int arr[3][3] = {{10, 20, 45}, {42, 79, 81}, {89, 9, 36}}
  • 6. Calculating the Address of Array Elements • The array name is a symbolic reference to the address of the first byte of the array. • When we use the array name, we are actually referring to the first byte of the array. • The address of other data elements can simply be calculated using the base address. • The formula to perform this calculation is, Address of data element, A[k] = BA(A) + w(k – lower_bound) Here, A is the array, k is the index of the element of which we have to calculate the address, BA is the base address of the array A, w is the size of one element in memory, for example, size of int is 2.
  • 7. Calculating the Address of Array Elements Example • Given an array int marks[] = {99,67,78,56,88,90,34,85}, calculate the address of marks[4] if the base address = 1000. • We know that storing an integer value requires 2 bytes, therefore, its size is 2 bytes. marks[4] = 1000 + 2(4 – 0) = 1000 + 2(4) = 1008
  • 8. Calculating the Address of Array Elements • For multidimensional array • If the array elements are stored in column major order, Address(A[I][J]) = Base_Address + w{M ( J – 1) + (I – 1)} • And if the array elements are stored in row major order, Address(A[I][J]) = Base_Address + w{N ( I – 1) + (J – 1)} • where w is the number of bytes required to store one element, • N is the number of columns, M is the number of rows, • I and J are the subscripts of the array element.
  • 9. Calculating the Address of Array Elements Example • Consider a 20 x 5 two-dimensional array marks which has its base address = 1000 and the size of an element = 2. Now compute the address of the element, marks[18][ 4] assuming that the elements are stored in row major order. Address(A[I][J]) = Base_Address + w{N (I – 1) + (J – 1)} Address(marks[18][4]) = 1000 + 2 {5(18 – 1) + (4 – 1)} = 1000 + 2 {5(17) + 3} = 1000 + 2 (88) = 1000 + 176 = 1176
  • 11. OPERATIONS ON ARRAYS There are a number of operations that can be preformed on arrays. These operations include: • Traversing an array • Inserting an element in an array • Searching an element in an array • Deleting an element from an array • Merging two arrays • Sorting an array in ascending or descending order
  • 12. Sparse Matrix • A matrix is a two-dimensional data object made of m rows and n columns, therefore having m x n values. When m=n, we call it a square matrix. • If a large number of elements of the matrix are zero elements, then it is called a sparse matrix.
  • 13. REPRESENTATION OF SPARSE MATRICES using Vector • Representing a sparse matrix by using a two-dimensional array leads to the wastage of a substantial amount of space. • Therefore, an alternative representation must be used for sparse matrices. One such representation is to store only non- zero elements along with their row positions and column positions. • A= vector which contain non-zero element of sparse matrix • JA=vector stores column indices of elements in A • The IA vector is of size m+1 stores the cumulative number of non-zero elements upto ( not including) the i-th row. It is defined by the recursive relation : • IA[0] = 0 • IA[i] = IA[i-1] + no of non-zero elements in the (i-1) th row of the Matrix
  • 14. REPRESENTATION OF SPARSE MATRICES using Vector • the A vector is [ 5 8 3 6] • JA = [ 0 1 2 1] //Column index of element of A • IA[0] = 0. • IA[1] = IA[0] + no of non-zero elements in row 0 i.e 0 + 0 = 0. Similarly, IA[2] = IA[1] + 2 = 2 IA[3] = IA[2] + 1 = 3 IA[4] = IA[3]+1 = 4 Therefore IA = [0 0 2 3 4] //no of row +1 elements
  • 15. REPRESENTATION OF SPARSE MATRICES using Vector • A = [10 20 30 4 50 60 70 80], • IA = [0 2 4 7 8] • JA = [0 1 1 3 2 3 4 5]
  • 16. REPRESENTATION OF SPARSE MATRICES using linked list • Representing a sparse matrix by using a two-dimensional array leads to the wastage of a substantial amount of space. • Therefore, an alternative representation must be used for sparse matrices. One such representation is to store only non- zero elements along with their row positions and column positions. • That means representing every non-zero element by using triples (i, j, value), where i is a row position and j is a column position, and store these triples in a linear list. • It is possible to arrange these triples in the increasing order of row indices, and for the same row index in the increasing order of column indices. • Each triple (i, j, value) can be represented by using a node having four fields as shown in the following: Struct snode{ int row,col,val; Struct snode *next; };
  • 17. REPRESENTATION OF SPARSE MATRICES • Example
  • 18. Stack • Stack is a non-primitive and linear data structure where insertion and deletion is done at only one end i.e. the TOP (Top of the Stack). • Stack follows the LIFO (Last In First Out) structure. TOP stores the address of the topmost element of the stack. • E.g.:- The example of the stack is stack of plates in a cafeteria where every new plate is added to the top. Similarly the plate is also taken off the plates.
  • 19. ARRAY REPRESENTATION OF STACKS • The stack can be represented as a linear array. • Every stack has a variable called TOP associated with it, which is used to store the address of the topmost element of the stack. • It is this position where the element will be added to or deleted from. • There is another variable called MAX, which is used to store the maximum number of elements that the stack can hold. • If TOP==-1 then it indicates that the stack is empty and if TOP = MAX–1, then the stack is full. #define MAX 50 int stack[MAX], top=-1;
  • 20. Operations on Stack • A stack supports main three basic operations: push, pop, and peek. • The push operation adds an element to the top of the stack • The pop operation removes the element from the top of the stack. • The peek operation returns the value of the topmost element of the stack. Other operation • isEmpty(): It determines whether the stack is empty or not (Underflow). • isFull(): It determines whether the stack is full or not (Overflow). • display(): It prints all the elements available in the stack.
  • 21. PUSH Operation on Stack • The push operation is used to insert an element into the stack. • The new element is added at the topmost position of the stack • Before inserting an element in a stack, we check whether the stack is full(i.e. check the condition top==MAX-1 where MAX= maximum size of stack). • If we try to insert the element in a full stack, then the overflow condition occurs (Overflow message need to print). • When the new element is pushed in a stack, first, the value of the top gets incremented, i.e., top=top+1, and the element will be placed at the new position of the top (top is initialized as -1 to check that the stack is empty).
  • 22. PUSH Operation on Stack • Algorithm to insert element in the stack PUSH(value) { //value=data to be inserted Step1: check that stack is full If TOP==MAX-1 Write(‘ overflow’) Return Step 2: if stack is not full increment top pointer and insert data into stack TOP=TOP+1 Stack[TOP]=Value } //C code for PUSH operation void Push(int value) { if(TOP==MAX-1) { printf(“nStack is full—Overflow”); return; } else stack[++TOP]=value; }
  • 23. Pop Operation on Stack • The pop operation is used to delete the topmost element from the stack. • Before deleting the element from the stack, we check whether the stack is empty. i.e. check the condition top==-1). • If we try to delete the element in an empty stack, then the underflow condition occurs (Underflow message need to print). • If the stack is not empty, we first access the element which is pointed by the top. • Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
  • 24. POP Operation on Stack • Algorithm to delete an element from the stack POP() { //return popped element Step 1: check stack is empty If TOP==-1 Write(‘ underflow’) Return -1 Step 2: if stack is not empty store the value, Decrement the top and return store value Value =Stack[TOP] TOP=TOP-1 return Value } //C code for Pop operation int POP() { if(TOP==-1) { printf(“nStack is empty—Underflow”); return -1; } else return(Stack[top--]); }
  • 25. Peek Operation on Stack • Peek is an operation that returns the value of the topmost element of the stack without deleting it from the stack. • However, the Peek operation first checks if the stack is empty, i.e., if TOP ==-1, then an appropriate message is printed, else the value is returned
  • 26. PEEK Operation on Stack • Algorithm to return topmost element from the stack PEEK() { //return topmost element Step 1: check stack is empty If TOP==-1 Write(‘ underflow’) Return -1 Step 2: if stack is not empty return the top of stack value Value =Stack[TOP] return Value } //C code for Pop operation int PEEK() { if(TOP==-1) { printf(“nStack is empty—Underflow”); return -1; } else return(Stack[top]); }
  • 27. Display Operation on Stack • Display is an operation that display the stack elements starting from topmost element of the stack and then gradually moving down to the stack. Algorithm to display elements from the stack Display() { If TOP==-1 Write(‘ underflow’) Return For i=TOP to 0 write( stack[i]) } //C code for Pop operation void Display() { int i; if(TOP==-1) { printf(“nStack is empty—Underflow”); return; } printf(“nStack elements are as below:n”); for(i=TOP;i>=0;i--) printf(“%d”,stack[i]); }
  • 28. APPLICATIONS OF STACKS • Reversing a list • Parentheses checker • Conversion of an infix expression into a postfix expression • Evaluation of a postfix expression • Conversion of an infix expression into a prefix expression • Evaluation of a prefix expression • Recursion • Tower of Hanoi
  • 29. Reverse a list • A list of elements can be reversed by reading each elements from an array starting from the first index and pushing it on a stack. • Once all the elements have been read, the elements can be popped one at a time and then stored in the array starting from the first index. //Algorithm for reverse a list Reverse(Arr, Size) For i=0 to length of Arr-1 Push(Arr[i]); For i=0 to length of Arr-1 Arr[i]=Pop()
  • 30. #include<stdio.h> #include<string.h> #include<stdlib.h> #define MAX 20 int top = -1; char stack[MAX]; void push(char item) { if(top == (MAX-1)) { printf("nStack Overflown"); return; } stack[++top] =item; } char pop() { if(top == -1) { printf("nStack Underflown"); return(-1); } return stack[top--]; } void reverse(char str[]) { int i; //Push string on the stack for(i=0;i<strlen(str);i++) push(str[i]); //Pop characters from the stack and store in string str for(i=0;i<strlen(str);i++) str[i]=pop(); } int main() { char str[20]; printf("Enter the string : " ); gets(str); reverse(str); printf("nReversed string is : "); puts(str); return 0; } C code for Reverse a string
  • 31. Parentheses checker • Stacks can be used to check the validity of parentheses in any algebraic expression. • For example, an algebraic expression is valid if for every open bracket there is a corresponding closing bracket. For example, • Input: exp = “[()]{}{[()()]()}” • Output: Balanced • Explanation: all the brackets are well-formed • Input: exp = “[(])” • Output: Not Balanced • Explanation: 1 and 4 brackets are not balanced because • there is a closing ‘]’ before the closing ‘(‘
  • 32. Parentheses checker • Following steps are follow to check expression has balanced parenthesis or not 1. Declare a character stack and read the expression. 2. Now traverse the string exp. 1. If the current character is a starting bracket ( ‘(‘ or ‘{‘ or ‘[‘ ) then push it to stack. 2. If the current character is a closing bracket ( ‘)’ or ‘}’ or ‘]’ ) then pop from the stack and if the popped character is the matching starting bracket then fine. 3. Else brackets are Not Balanced. 3. After complete traversal, if some starting brackets are left in the stack then the expression is Not balanced, else Balanced.
  • 33. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_SIZE 100 char stack[MAX_SIZE]; int top = -1; void push(char data) { if (top == MAX_SIZE - 1) { printf("Overflow stack!n"); return; } stack[++top] = data; } char pop() { if (top == -1) { printf("Empty stack!n"); return(-1); } return(stack[top--]); } int is_matching_pair(char char1, char char2) { if (char1 == '(' && char2 == ')') { return 1; } else if (char1 == '[' && char2 == ']') { return 1; } else if (char1 == '{' && char2 == '}') { return 1; } else { return 0; } } int main() { char exp[MAX_SIZE]; int i; printf("Input an expression in parentheses: "); gets(exp); for (i = 0; i < strlen(exp); i++) { if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{') push(exp[i]); else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}') { if(!is_matching_pair(pop(), exp[i])) { printf("The expression is not balanced.n"); return(0); } } } if (top==-1) printf("The expression is balanced.n"); else printf("The expression is not balanced.n"); return 0; } C code for balanced parenthesis checker
  • 34. Conversion of an Infix Expression into a Postfix Expression • Polish notation: Polish notation is also called prefix notation. It means that operations are written before the operands. • Postfix notation: the operator is placed after the operands for example the infix expression a+b will be written as ab+ in postfix notation . • Postfix notation is also called as Reverse Polish Notation or RPN. • To convert one form of expression to another form, we need to take care about precedence and associativity of the operator. Operator Precedence Associativity +,- 1 Left associative *, / 2 Left associative ^ 3 Right associative
  • 35. Conversion of an Infix Expression into a Postfix Expression The idea to convert infix to postfix expression Step 1: Scan the infix expression from left to right and repeat the step2 to step 6 until end of expression Step 2: If the scanned character is an operand, put it in the postfix expression. Step 3: If the scanned character is a ‘(‘, push it to the stack. Step 4: If the scanned character is a ‘)’, pop the stack and put it to postfix expression until a ‘(‘ is encountered, and discard both the parenthesis. Step 5: if scanned character is operator other than ‘^’(right associative) , • If the precedence and associativity of the scanned operator are greater than the precedence and associativity of the operator in the stack [or the stack is empty or the stack contains a ‘(‘ ], then push it in the stack • Else Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) Step 6: If scanned character is operator ‘^’ , push it on to the top of the stack Step 7: Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty. Step 8: Finally, print the postfix expression.
  • 36. Step 1: Scan the expression from left to right and for each scanned element do following Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty. (if pop element is ‘(‘ print message expression invalid) Scanned Input Action Operand Insert it into the postfix expression ‘(‘ opening bracket push it to the stack ‘)’ closing bracket pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis. (if ‘(‘ is not found or stack become empty- print message expression invalid ‘^’ Operator Push ‘^’ on to the stack Operator other than ‘^’ If(precedence(stack[top]) >=precedence of scanned input 1. Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. (If we encounter parenthesis while popping then stop.) 2. After doing that Push the scanned operator to the stack. If(precedence(stack[top]) < precedence of scanned input Pushed scanned operator into stack
  • 37. Infixtopostfix(infix) Len=length(infix) Postfix=[] J=1 For i=0 to len-1 if(isoperand(infix[i]) // if operand then insert into postfix expression postfix[j]=infix[i] j=j+1; else if(infix[i]==‘(‘) // if ‘(‘ push into stack push(‘(‘) else if (infix[i]==‘)’) //if input is ‘)’ then pop the stack element until ‘(‘ found and add into postfix while (top > -1 && stack[top] != '(') postfix[j] = pop() j=j+1 if (top > -1 && stack[top] != '(') return "Invalid Expression"; else pop(); // pop ‘(‘ on top of the stack
  • 38. else if(isoperator(infix[i]) //operator other than ‘^’, pop the stack elements until it’s precedence higher or equal to scanned operator after that push scanned operator into stack if(infix[i]!=‘^’) while (top > -1 && precedence(stack[top]) >= precedence(infix[i]) && stack[top]!=‘(‘) postfix[j] = pop() j=j+1 //push scanned operator on top of the stack push(infix[i]) //after scanning infix expression //pop all the remaining elements for the stack and insert to postfix while (top > -1) if (stack[top] == '(') return "Invalid Expression"; postfix[j] = pop() j=j+1 return postfix;
  • 44. (A+(B*C-(D/E^F)*H)) Convert following infix expression into postfix expression using stack. (A-B)/C*D^(E/F)^(G+H)
  • 45. Convert: a- ( b/c + (d % e* f ) / g) * h Infix Character scanned Stack Postfix expression a a - - a ( - ( a b - ( ab / - ( / ab c - ( / abc + - ( + abc/ ( - ( + ( abc/ d - ( + ( abc/d % - ( + ( % abc/d e - ( + ( % abc/de * - ( + ( % * abc/de
  • 46. Convert: a- ( b/c + (d % e* f ) / g) * h Infix Character scanned Stack Postfix expression f - ( + ( % * abc/def ) - ( + abc/def*% / - ( + / abc/def*% g - ( + / abc/def*%g ) - abc/def*%g/+ * - * abc/def*%g/+ h - * abc/def*%g/+h abc/def*%g/+h*-
  • 47. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <conio.h> #define MAX 100 char stack[MAX]; int top = -1; void push(char item) { if (top == MAX - 1) { printf("Stack Overflown"); return; } stack[++top] = item; } char pop() { if (top == -1) { printf("Stack Underflown"); return -1; } return stack[top--]; } // Function to return precedence of operators int precedence(char operator) { switch (operator) { case '+': case '-': return 1; case '*': case '/': case '%': return 2; case '^': return 3; default: return -1; } } int isOperator(char ch) { return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^'|| ch=='%'); } C code infix to postfix conversion
  • 48. // function to convert infix expression to postfix expression char* infixToPostfix(char* infix) { int i, j=0; int len = strlen(infix); char* postfix = (char*)malloc(sizeof(char) * (len + 2)); for (i = 0; i < len; i++) { if (infix[i] == ' ' || infix[i] == 't') continue; // If the scanned character is operand add it to the postfix expression if (isalnum(infix[i])) postfix[j++] = infix[i]; // if the scanned character is '(' push it in the stack else if (infix[i] == '(') push(infix[i]); /* if the scanned character is ')' pop the stack and add it to the output string until empty or '(' found*/ else if (infix[i] == ')') { while (top > -1 && stack[top] != '(') postfix[j++] = pop(); if (top > -1 && stack[top] != '(') return "Invalid Expression"; else pop(); } // If the scanned character is an operator, /*pop the stack element until its precedence higher or equal than input operator or "(" not encontered in stack // push it in the stack else if (isOperator(infix[i])) { if(infix[i]!='^') { while (top > -1 && precedence(stack[top]) >= precedence(infix[i]) && stack[top]!='(') postfix[j++] = pop(); } push(infix[i]); } }//for loop // Pop all remaining elements from the stack while (top > -1) { if (stack[top] == '(') return "Invalid Expression"; postfix[j++] = pop(); } postfix[j] = '0'; return postfix; }
  • 49. int main() { char infix[MAX],*postfix; printf("nEnter the infix expression: "); gets(infix); postfix=infixToPostfix(infix); printf("n Postfix expression: %s", postfix); free(postfix); return 0; } C code infix to postfix conversion
  • 50. Evaluating a Postfix Expression • Given an algebraic expression written in infix notation, the computer first converts the expression into the equivalent postfix notation and then evaluates the postfix expression. • Both these tasks—converting the infix notation into postfix notation and evaluating the postfix expression—make extensive use of stacks as the primary tool.
  • 51. Algorithm to evaluate Postfix Expression Step 1: Scan the given expression from left to right and repeat the step 2 until end of the expression Step2: 2.a If a operand is encountered, push it to Stack 2.b If the operator is encountered (op), pop two elements from stack as A and B , Evaluate the expression B op A and push the result of evaluation on the stack Step 3: When the expression is ended, the number in the stack is the final answer, return it
  • 52. Evaluation of Postfix Expression: Example Consider the expression: exp = “2 3 1 * + 9 -“
  • 53. Evaluation of Postfix Expression: Example Consider the expression: exp = “2 3 1 * + 9 -“
  • 54. Evaluation of Postfix Expression: Example Consider the expression: exp = “2 3 1 * + 9 -“
  • 55. Evaluation of Postfix Expression: Example Consider the expression: exp = “2 3 1 * + 9 -“
  • 56. Evaluation of Postfix Expression: Example Consider the expression: exp = “2 3 1 * + 9 -“ There are no more elements to scan, we return the top element from the stack (which is the only element left in a stack).  So the result becomes -4
  • 57. Evaluation of Postfix Expression: Example Consider the expression: exp = “456*+ Input Symbol Operation Stack Calculation 4 Push 4 5 Push 4 5 6 Push 4 5 6 * Pop 2 Element, Evaluate it and Push result 4 30 5*6 =30 + Pop 2 Element, Evaluate it and Push result 34 4+30=34 No more input POP Empty 12 Result
  • 58. Evaluation of Postfix Expression: Example Consider the expression: exp = “532*+4-5+ Input Symbol Operation Stack Calculation 5 Push 5 3 Push 5 3 2 Push 5 3 2 * Pop 2 Element, Evaluate it and Push result 5 6 3*2 =6 + Pop 2 Element, Evaluate it and Push result 11 5+6=11 4 Push 11 4 - Pop 2 Element, Evaluate it and Push result 11-4=7 5 Push 7 5 + Pop 2 Element, Evaluate it and Push result 12 7+5=12 No more input POP Empty 12 Result
  • 59. Evaluation of Postfix Expression: Example Consider the expression: exp = “5 9 3 + 4 2 * * 7 + *” 9 3 4 * 8 + 4 / –
  • 60. Algorithm to evaluate prefix Expression There are more than one way to evaluate a prefix expression Method 1 Step 1: Reverse the expression (now expression become postfix) Step 2: Scan the given expression from left to right and repeat the step 3 until end of the expression Step3: 3.a If a operand is encountered, push it to Stack 3.b If the operator is encountered (op), pop two elements from stack as A and B , Evaluate the expression B op A and push the result of evaluation on the stack Step 4: When the expression is ended, the number in the stack is the final answer, return it
  • 61. Algorithm to evaluate prefix Expression There are more than one way to evaluate a prefix expression Method 2 Step 1: Scan the given expression from right to left and repeat the step 2 until end of the expression Step2: 2.a If a operand is encountered, push it to Stack 2.b If the operator is encountered (op), pop two elements from stack as A and B , Evaluate the expression A op B and push the result of evaluation on the stack Step 3: When the expression scanning completed, the number in the stack is the final answer, return it
  • 62. Algorithm to evaluating a Prefix Expression Solution using Method 2
  • 63. //Evaluation of postfix/prefix expression #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100 int stack[MAX]; int top = -1; void push(int item) { if (top == MAX - 1) { printf("Stack Overflown"); return; } stack[++top] = item; } int pop() { if (top == -1) { printf("Stack Underflown"); return -1; } return stack[top--]; } int is_operator(char symbol) { if (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/' || symbol=='%' || symbol=='^') { return 1; } return 0; } int evaluate_postfix(char* exp) { int i = 0,num,top=-1; int op1, op2, result; while (exp[i] != '0') { if (exp[i] >= '0' && exp[i] <= '9') { num = exp[i] - '0'; push(num); } else if (is_operator(exp[i])) { op2 = pop(); op1 = pop(); switch(exp[i]) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case '*': result = op1 * op2; break; case '/': result = op1 / op2; break; case '%': result = op1 % op2; break; case '^': result = op2 ^ op1; break; default : break; } push(result); } i++; } result = pop(); return result; } C code for evaluation of expression
  • 64. int evaluate_prefix(char* exp) { int i = 0,num,len=strlen(exp); int op1, op2, result,top=-1; for(i=len-1;i>=0;i--) { if (exp[i] >= '0' && exp[i] <= '9') { num = exp[i] - '0'; push(num); } else if (is_operator(exp[i])) { op1 = pop(); op2 = pop(); switch(exp[i]) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case '*': result = op1 * op2; break; case '/': result = op1 / op2; break; case '%': result = op1 % op2; break; case '^': result = op2 ^ op1; break; default : break; } push(result); } } result = pop(); return result; } int main() { char exp[MAX]; int result,ch; do { printf("n1. Evaluate Postfix expression: "); printf("n2. Evaluate Prefix expression: "); printf("n3. Exit"); printf("n Enter the Choice: "); scanf("%d",&ch); switch(ch) { case 1: printf("nEnter the Postfix expression: "); fflush(stdin); gets(exp); result = evaluate_postfix(exp); printf("Result= %dn", result); break; case 2: printf("nEnter the Prefix expression: "); fflush(stdin); scanf("%s",exp); result = evaluate_prefix(exp); printf("Result= %dn", result); break; default: break; } }while(ch!=3); return 0; } C code for evaluation of expression
  • 65. Conversion of an Infix Expression into a Prefix Expression • A prefix notation is another form of expression but it does not require other information such as precedence and associativity, whereas an infix notation requires information of precedence and associativity. • It is also known as polish notation. • In prefix notation, an operator comes before the operands. The syntax of prefix notation is given below: <operator> <operand> <operand> • For example, if the infix expression is 5+1, then the prefix expression corresponding to this infix expression is +51. • If the infix expression is: a * b + c then corresponding prefix expression is *a+bc
  • 66. Conversion of an Infix Expression into a Prefix Expression The idea to convert infix to prefix expression Step 1: Reverse the infix expression. Note while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘. Step 2: Convert the reversed infix expression to “nearly” postfix expression. • While converting to postfix expression, instead of using pop operation to pop operators with greater than or equal precedence, here we will only pop the operators from stack that have greater precedence. Step 3: Reverse the postfix expression.
  • 67. Step 2: Scan the expression from left to right and for each scanned element do following Once the scanning is over, Pop the stack and add the operators in the postfix expression until it is not empty. (if pop element is ‘(‘ print message expression invalid) Scanned Input Action Operand Insert it into the postfix expression ‘(‘ opening bracket push it to the stack ‘)’ closing bracket pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis. (if ‘(‘ is not found or stack become empty- print message expression invalid ‘^’ Operator If(precedence(stack[top]) = precedence of scanned input 1. pop the top of the stack till the condition is true (If we encounter parenthesis while popping then stop there and push the scanned operator in the stack.) 2. Push ‘^’ on to the stack Operator other than ‘^’ If(precedence(stack[top]) >precedence of scanned input 1. Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. (If we encounter parenthesis while popping then stop there and push the scanned operator in the stack.) 2. After doing that Push the scanned operator to the stack. If(precedence(stack[top]) <= precedence of scanned input Pushed scanned operator into stack
  • 68. Algorithm Infixtoprefix(infix) //reverse the expression Reverse(infix) //replace “(“ with “)” and vice versa Brackets(infix) //convert into posfix prefix=infixtopostfix(infix) //reverse the postfix expression Reverse(prefix) Return(prefix)
  • 69. Algorithm Infixtopostfix(infix) Len=length(infix) Postfix=[] J=1 For i=0 to len-1 if(isoperand(infix[i]) // if operand then insert into postfix expression postfix[j]=infix[i] j=j+1; else if(infix[i]==‘(‘) // if ‘(‘ push into stack push(‘(‘) else if (infix[i]==‘)’) //if input is ‘)’ then pop the stack element until ‘(‘ found and add into postfix while (top > -1 && stack[top] != '(') postfix[j] = pop() j=j+1 if (top > -1 && stack[top] != '(') return "Invalid Expression"; else pop()// pop ‘(‘ on top of the stack
  • 70. else if(isoperator(infix[i]) if((precedence(stack[top]) == precedence(infix[i])) && infix[i] == '^’) while((precedence(stack[top]) == precedence(infix[i])) && infix[i] == '^‘ && top > -1 && stack[top]!='(') postfix[j] = pop() j=j+1 else if(precedence(stack[top]) > precedence(infix[i])) while (top > -1 && precedence(stack[top]) > precedence(infix[i]) && stack[top]!='(') postfix[j] = pop() j=j+1 push(infix[i]) //after scanning infix expression //pop all the remaining elements for the stack and insert to postfix while (top > -1) if (stack[top] == '(') return "Invalid Expression"; postfix[j] = pop(); j=j+1 return postfix;
  • 71. Infix Expression into a Prefix Expression conversion: Example Consider: K + L - M * N + (O^P) * W/U/V * T + Q We need first to reverse the expression. The Reverse expression would be: Q + T * V/U/W * ( P^O)+ N*M - L + K
  • 72. Q + T * V/U/W * ) P^O(+ N*M - L + K
  • 73. Q + T * V/U/W * ) P^O(+ N*M - L + K Now reverse the result ++-+KL*MN*//*^OPWUVTQ
  • 74. Infix Expression into a Prefix Expression conversion: Example Consider: ((a / b) + c) - (d + (e * f )) We need first to reverse the expression. The Reverse expression would be: ((f*e)+d)-(c+(b/a))
  • 76. ((f*e)+d)-(c+(b/a)) Now reverse the result -+/abc+d*ef Input expression Stack Prefix expression
  • 77. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <conio.h> #define MAX 100 char stack[MAX]; int top = -1; void push(char item) { if (top == MAX - 1) { printf("Stack Overflown"); return; } stack[++top] = item; } char pop() { if (top == -1) { printf("Stack Underflown"); return -1; } return stack[top--]; } // Function to return precedence of operators int precedence(char operator) { switch (operator) { case '+': case '-': return 1; case '*': case '/': case '%': return 2; case '^': return 3; default: return -1; } } int isOperator(char ch) { return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^'|| ch=='%'); } C code infix to prefix conversion
  • 78. void reverse (char *infix) { int size = strlen (infix); int j = size, i = 0; char temp[size]; temp[j--] = '0'; while (infix[i] != '0') { temp[j] = infix[i]; j--; i++; } strcpy (infix, temp); } void brackets (char *infix) { int i = 0,len=strlen(infix); for (int i = 0; i < len; i++) { if (infix[i] == '(') infix[i] = ')'; else if (infix[i] == ')') infix[i] = '('; } } C code infix to prefix conversion
  • 79. // function to convert infix expression to postfix expression char* infixToPostfix(char* infix) { int i, j=0; int len = strlen(infix); char* postfix = (char*)malloc(sizeof(char) * (len + 2)); for (i = 0; i < len; i++) { if (infix[i] == ' ' || infix[i] == 't') continue; // If the scanned character is operand add it to the postfix expression if (isalnum(infix[i])) postfix[j++] = infix[i]; // if the scanned character is '(' push it in the stack else if (infix[i] == '(') push(infix[i]); /* if the scanned character is ')' pop the stack and add it to the output string until empty or '(' found*/ else if (infix[i] == ')') { while (top > -1 && stack[top] != '(') postfix[j++] = pop(); if (top > -1 && stack[top] != '(') return "Invalid Expression"; else pop(); }
  • 80. // If the scanned character is an operator, /*pop the stack element until its precedence higher l than input operator or "(" not encontered in stack // push it in the stack if((precedence(stack[top]) == precedence(infix[i])) && infix[i] == '^') { while((precedence(stack[top]) == precedence(infix[i])) && infix[i] == '^') postfix[j++] = pop(); } else if(precedence(stack[top]) > precedence(infix[i])) { while (top > -1 && precedence(stack[top]) > precedence(infix[i]) && stack[top]!='(') postfix[j++] = pop(); } push(infix[i]); } } // Pop all remaining elements from the stack while (top > -1) { if (stack[top] == '(') return "Invalid Expression"; postfix[j++] = pop(); } postfix[j] = '0'; return postfix; }
  • 81. char *infixtoprefix(char *infix) { // Reverse String and replace ( with ) and vice versa // Get Postfix // Reverse Postfix char *prefix; // Reverse infix reverse(infix); // Replace ( with ) and vice versa brackets(infix); prefix = infixToPostfix(infix); // Reverse postfix reverse(prefix); return prefix; } int main() { char infix[MAX],*prefix; printf("nEnter the infix expression: "); gets(infix); prefix=infixtoprefix(infix); printf("n Prefix expression: %s", prefix); free(prefix); return 0; } C code infix to prefix conversion
  • 83. Recursion • Since a recursive function repeatedly calls itself, it makes use of the system stack to temporarily store the return address an local variables of the calling function. • Every recursive solution has two major cases. They are 1. Base case, in which the problem is simple enough to be solved directly without making an further calls to the same function. 2. Recursive case, in which first the problem at hand is divided into simpler sub-parts. Second the function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is obtained by combining the solutions of simpler sub-parts.
  • 84. Recursion- Example- Factorial of n • let us take an example of calculating factorial of a number. • To calculate n!, we multiply the number with factorial of the number that is 1 less than that number i.e n!=n*(n-1)!. • Iterative implementation int Factorial(int n) { int fact = 1; for(int count = 2; count <= n; count++) fact = fact * count; return fact; } Time complexity T(n)=O(n)
  • 85. Recursion- Example- Factorial of n • Recursive implementation • Every recursive function must have a base case and a recursive case. • For the factorial function, • Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1. • Recursive case of the factorial function will call itself but with a smaller value of n, this case can be given as factorial(n) = n × factorial (n–1) int Factorial(int n) { if (n==0) // base case return 1; else return n * Factorial(n-1); }
  • 87. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Call Factorial(5) = 5 x factorial(4) TOP • When ever function call happen its information like return address, local and temporary variable stores in stack inform of activation record – call to function result in push an activation record on system stack. • During returning from function its activation record popped from the stack
  • 88. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Activation Record of Factorial(4) Factorial(5) = 5 x factorial(4) Call Factorial(4) = 4 x factorial (3) TOP
  • 89. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Activation Record of Factorial(4) Activation Record of Factorial(3) Factorial(5) = 5 x factorial(4) Factorial(4) = 4 x factorial (3) Call Factorial(3) = 3 x factorial (2) TOP
  • 90. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Activation Record of Factorial(4) Activation Record of Factorial(3) Activation Record of Factorial(2) Factorial(5) = 5 x factorial(4) Factorial(4) = 4 x factorial (3) Factorial(3) = 3 x factorial(2) Call Factorial(2) = 2 x factorial (1) TOP
  • 91. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Activation Record of Factorial(4) Activation Record of Factorial(3) Activation Record of Factorial(2) Activation Record of Factorial(1) Factorial(5) = 5 x factorial(4) Factorial(4) = 4 x factorial (3) Factorial(3) = 3 x factorial(2) Factorial(2) = 2 x factorial (1) Call Factorial(1) = 1 x factorial (0) TOP
  • 92. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Activation Record of Factorial(4) Activation Record of Factorial(3) Activation Record of Factorial(2) Activation Record of Factorial(1) Factorial(5) = 5 x factorial(4) Factorial(4) = 4 x factorial (3) Factorial(3) = 3 x factorial(2) Factorial(2) = 2 x factorial (1) Factorial(1) = 1 x factorial (0) replace with 1 Factorial(0) = return 1 TOP int Factorial(int n) { if (n==0) // base case return 1; else return n * Factorial(n-1); } So, factorial(0) return 1, and its information removed from the stack
  • 93. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Activation Record of Factorial(4) Activation Record of Factorial(3) Activation Record of Factorial(2) Factorial(5) = 5 x factorial(4) Factorial(4) = 4 x factorial (3) Factorial(3) = 3 x factorial(2) Factorial(2) = 2 x factorial (1) Factorial(1) = 1 x 1 (return 1) TOP
  • 94. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Activation Record of Factorial(4) Activation Record of Factorial(3) Factorial(5) = 5 x factorial(4) Factorial(4) = 4 x factorial (3) Factorial(3) = 3 x factorial(2) Factorial(2) = 2 x 1 TOP
  • 95. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Activation Record of Factorial(4) Factorial(5) = 5 x factorial(4) Factorial(4) = 4 x factorial (3) Factorial(3) = 3 x 2 TOP
  • 96. Recursion- Example- Factorial of n System stack Activation Record of Factorial(5) Factorial(5) = 5 x factorial(4) Factorial(4) = 4 x 6 TOP
  • 97. Recursion- Example- Factorial of n System stack Factorial(5) = 5 x 24 =120 return TOP
  • 98. Recursion- Example- Fibonacci number • The Nth Fibonacci number is the sum of the previous two Fibonacci numbers • 0, 1, 1, 2, 3, 5, 8, 13, … • Recursive Design: • Recursive case: • fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) • Base case: • fibonacci(1) = 0 • fibonacci(2) = 1
  • 99. Recursion- Example- Fibonacci number int fibonacci(int n) { int fib; if (n > 2) fib = fibonacci(n-1) + fibonacci(n-2); else if (n == 2) fib = 1; else fib = 0; return fib; }
  • 100. Recursion- Example- Greatest Common Divisor • The greatest common divisor of two numbers (integers) is the largest integer that divides both the numbers. • We can find the GCD of two numbers recursively by using the Euclid’s algorithm that states • GCD can be implemented as a recursive function because if b does not divide a, then we call the same function (GCD) with another set of parameters that are smaller than the original ones. • Here we assume that a > b. However if a < b, then interchange a and b in the formula given above.
  • 101. Recursion- Example- Greatest Common Divisor int GCD(int x, int y) { int rem; rem = x%y; if(rem==0) return y; else return (GCD(y, rem)); }
  • 102. Recursion- Example- Finding Exponents • We can also find exponent of a number using recursion. To find xy, the base case would be when y=0, as we know that any number raised to the power 0 is 1. • Therefore, the general formula to find xy can be given as
  • 103. Recursion- Example- Finding Exponents int exp_rec(int x, int y) { if(y==0) return 1; else return (x * exp_rec(x, y–1)); }
  • 105. Tower of Hanoi Given N discs of decreasing size stacked on one needle and two empty needles, it is required to stack all the discs onto a second needle in decreasing order of size. The third needle may be used as temporary storage. The movement of discs is restricted by the following rules : 1. Only one disc can be moved at a time. 2. A disc may be moved from any needle to any other. 3. At no time may a larger disc rest upon a smaller disc.
  • 108. 3 2 A B C Step Move 1: move disk 1 from A to C 1
  • 109. 3 2 A B C Step Move 2: move disk 2 from A to B 1
  • 110. 3 2 A B C Step Move 3: move disk 1 from C to B 1
  • 111. 3 2 A B C Step Move 4: move disk 3 from A to C 1
  • 112. 3 2 A B C Step Move 5: move disk 1 from B to A 1
  • 113. 3 2 A B C Step Move 6: move disk 2 from B to C 1
  • 114. 3 2 A B C Step Move 7: move disk 1 from A to C 1
  • 115. Algorithm for solving this problem : The solution of this problem is most clearly seen with the aid of induction. To move 1 disc, merely move it from needle A to needle C. To move 2 discs, move the first disc to needle B, move the second from needle A to needle C, then move the disc from needle B to needle C. In general the solution of the problem of moving N disc from needle A to C has 3 steps : 1. Move N-1 discs from A to B. 2. Move disc N from A to C. 3. Move N-1 discs from B to C.
  • 116. C program #include <stdio.h> #include <conio.h> Void TowerOfHanoi(char,char,char); void main () { int N; char A=‘A’, B=‘B’, C=‘C’; printf(“ntEnter the No. of discs : “); scanf ( “%d", & N); TowerOfHanoi ( N, A, B, C); } void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } }
  • 117. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(3,A,B,C)
  • 118. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(3,A,B,C) Print(3 from A to C) Hanoi(2,B,A,C) Call Hanio(2,A,C,B)
  • 119. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(2,A,C,B) Print(2 from A to B) Hanoi(1,C,A,B) Print(3 from A to C) Hanoi(2,B,A,C) Call Hanio(1,A,B,C)
  • 120. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(1,A,B,C) Print(1 from A to C) Hanoi(0,B,A,C) Print(2 from A to B) Hanoi(1,C,A,B) Print(3 from A to C) Hanoi(2,B,A,C) Call Hanio(0,A,C,B)
  • 121. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,A,C,B) Print(1 from A to C) Hanoi(0,B,A,C) Print(2 from A to B) Hanoi(1,C,A,B) Print(3 from A to C) Hanoi(2,B,A,C) RETURN Pop this element
  • 122. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,A,C,B) Print(2 from A to B) Hanoi(1,C,A,B) Print(3 from A to C) Hanoi(2,B,A,C) move disk 1 from A to C Call Hanoi(0,B,A,C)
  • 123. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,B,A,C) Print(2 from A to B) Hanoi(1,C,A,B) Print(3 from A to C) Hanoi(2,B,A,C) RETURN Pop this element
  • 124. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,B,A,C) Print(3 from A to C) Hanoi(2,B,A,C) move disk 2 from A to B Call Hanoi(1,C,A,B)
  • 125. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(1,C,A,B) Print(1 from C to B) Hanoi(0,A,C,B) Print(3 from A to C) Hanoi(2,B,A,C) Call Hanoi(0,C,B,A)
  • 126. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,C,B,A) Print(1 from C to B) Hanoi(0,A,C,B) Print(3 from A to C) Hanoi(2,B,A,C) RETURN Pop this element
  • 127. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,C,B,A) Print(3 from A to C) Hanoi(2,B,A,C) move disk 1 from C to B Call Hanoi(0,A,C,B)
  • 128. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,A,C,B) Print(3 from A to C) Hanoi(2,B,A,C) RETURN Pop this element
  • 129. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,A,C,B) move disk 3 from A to C Call Hanoi(2,B,A,C)
  • 130. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(2,B,A,C) Print(2 from B to C) Hanoi(1,A,B,C) Call Hanio(1,B,C,A)
  • 131. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(1,B,C,A) Print(1 from B to A) Hanoi(0,C,B,A) Print(2 from B to C) Hanoi(1,A,B,C) Call Hanio(0,B,A,C)
  • 132. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,B,A,C) Print(1 from B to A) Hanoi(0,C,B,A) Print(2 from B to C) Hanoi(1,A,B,C) RETURN Pop this element
  • 133. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,A,C,B) Print(2 from B to C) Hanoi(1,A,B,C) move disk 1 from B to A Call Hanoi(0,C,B,A)
  • 134. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,C,B,A) Print(2 from B to C) Hanoi(1,A,B,C) RETURN Pop this element
  • 135. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,C,B,A) move disk 2 from B to C Call Hanoi(1,A,B,C)
  • 136. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(1,A,B,C) Print(1 from A to C) Hanoi(0,B,A,C) Call Hanio(0,A,C,B)
  • 137. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,A,C,B) Print(1 from A to C) Hanoi(0,B,A,C) RETURN Pop this element
  • 138. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,A,C,B) Print(1 from A to C) Hanoi(0,B,A,C) move disk 1 from A to C Call Hanoi(0,B,A,C)
  • 139. C program void TowerOfHanoi ( int N, char A, char B, char C ) { if ( N != 0 ) { TowerOfHanoi ( N-1, A, C, B); printf (“ntMove Disc %d from %c to %c”, N,A,C); TowerOfHanoi ( N-1, B, A, C); } } Call Hanio(0,B,A,C) RETURN TO MAIN
  • 142. Advantage of recursion • Recursive solutions often tend to be shorter and simpler than non-recursive ones. • Code is clearer and easier to use. • Recursion works similar to the original formula to solve a problem. • Recursion follows a divide and conquer technique to solve problems. • In some (limited) instances, recursion may be more efficient.
  • 143. Drawback of recursion • For some programmers and readers, recursion is a difficult concept. • Recursion is implemented using system stack. If the stack space on the system is limited, recursion to a deeper level will be difficult to implement. • Aborting a recursive program in midstream can be a very slow process. • Using a recursive function takes more memory and time to execute as compared to its nonrecursive counterpart. • It is difficult to find bugs, particularly while using global variables.