SlideShare a Scribd company logo
1 of 32
The STACK
Unit 3
Simple as it sounds
Fig. stack of items
Ashim Lamichhane 2
Definition
• A stack is an ordered collection of items into which new items
may be inserted and from which items may be deleted at one end,
called the top of the stack.
• Stack is a linear data structure where all the insertions and deletions
are done at end rather than in the middle.
• Stacks are also called Last in First Out (LIFO) lists.
Ashim Lamichhane 3
Intro
• We may come across situations, where insertion or deletion is
required only at one end, either at the beginning or end of the list.
• The suitable data structures to fulfil such requirements are stacks and
queues.
• For ex. a stack of plates, a stack of coins, a stack of books etc.
Ashim Lamichhane 4
Stack as an abstract data type
• A stack of elements of type T is a finite sequence of elements together
with the operations
1. CreateEmptyStack(S): create or make stack S be an empty stack
2. Push(S,x): Insert x at one end of the stack, called its top
3. Top(S): If stack S is not empty; then retrieve the element at its top
4. Pop(S): If stack S is not empty; then delete the element at its top
5. IsFull(S): Determine if S is full or not. Return true if S is full stack; return false
otherwise
6. IsEmpty(S): Determine if S is empty or not. Return true if S is an empty stack;
return false otherwise.
Ashim Lamichhane 5
Ashim Lamichhane 6
Example of Push Pop
Ashim Lamichhane 7
Thing to consider
• Stack underflow happens when
we try to pop (remove) an item from
the stack, when nothing is actually
there to remove.
• Stack overflow happens when we
try to push one more item onto our
stack than it can actually hold.
Ashim Lamichhane 8
Stack As a Linked List
• The stack as linked list is represented as a single linked list.
• Each node in the list contains data and a pointer to the next node.
• The structure defined to represent stack is as follows:
struct node{
int data;
node *next;
};
Fig. Stack as a linked list
Ashim Lamichhane 9
Infix, Postfix and Prefix
• 2+3 <operand><operator><operand>
• A-b
• (P*2)
Operands are basic objects on which operation is performed
INFIX
<operand><operator><operand>
• (2+3) * 4 (2+3) * 4
• (P+Q)*(R+S) (P+Q) * (R+S)
Common expressions
Ashim Lamichhane 10
Infix
• What about 4+6*2and what about 4+6+2
• To clear ambiguity we remember school Mathematics
• Order of precedence
1. Parentheses (Brackets)
2. Order (Exponents)
3. Division
4. Multiplication
5. Addition
6. Subtraction
• So 4+6*2 | 2*6/2 -3 +7 | {(2*6)/2}-(3+7)
=4+12 | = 2*3-3+7 | = ???
=16 | = 6-3+7 | = ??
| = 3+7=10 | = ?
Ashim Lamichhane 11
Prefix (polish notation)
• In prefix notation the operator proceeds the two operands. i.e. the
operator is written before the operands.
<operator><operand><operand>
infix prefix
2+3 +23
p-q -pq
a+b*c +a*bc
Ashim Lamichhane 12
Postfix (Reverse Polish Notation)
• In postfix notation the operators are written after the operands so it is
called the postfix notation (post means after).
<operand><operand><operator>
infix prefix postfix
2+3 +23 23+
p-q -pq pq-
a+b*c +a*bc abc*+
Human-readable Good for machines
Ashim Lamichhane 13
Conversion of Infix to Postfix Expression
• While evaluating an infix expression, there is an evaluation order according to
which the operations are executed
• Brackets or Parentheses
• Exponentiation
• Multiplication or Division
• Addition or Subtraction
• The operators with same priority are evaluated from left to right.
• Eg:
• A+B+C means (A+B)+C
Ashim Lamichhane 14
Evaluation of Prefix and Postfix Expressions
• Suppose an expression
a*b+c*d-e
• We can write this as:
{(a*b)+(c*d)}-e
• As we want to change it into postfix expression
{(ab*)+(cd*)}-e
{(ab*)(cd*)+}-e
{(ab*)(cd*)+} e-
• Final form
ab*cd*+e-
Ashim Lamichhane 15
Evaluation of Postfix Expressions
• Suppose we have a postfix expression
ab*cd*+e-
• And we want to evaluate it so lets say
a=2, b=3,c=5,d=4,e=9
• We can solve this as,
2 3 * 5 4 * + 9 – <operand><operand><operator>
6 5 4 * + 9 –
6 20 + 9 –
26 9 –
17
Ashim Lamichhane 16
Evaluation of Postfix Expressions
• From above we get,
2 3 * 5 4 * + 9 –
Stack
EvaluatePostfix(exp)
{
create a stack S
for i=0 to length (exp) -1
{
if (exp[i] is operand)
PUSH(exp[i])
elseif (exp[i] is operator)
op2 <- pop()
op1 <- pop()
res– Perform(exp[i],op1,op2)
PUSH(res)
}
return top of STACK
}
2
3
Ashim Lamichhane 17
Evaluation of Prefix expressions
• An expression: 2*3 +5*4-9
• Can be written as:
{(2*3)+(5*4)}-9
{(*2 3)+(*5 4)}-9
{+(*2 3) (*5 4)}-9
-{+(*2 3) (*5 4)}9
• We can get Rid of Paranthesis
-+*2 3 *5 4 9
Ashim Lamichhane 18
Evaluation of Prefix expressions
• We have to scan it from right
-+*2 3 *5 4 9
Stack
9
4
5
Stack
9
20
6
Stack
9
26
Stack
17
Ashim Lamichhane 19
Algorithm to convert Infix to Postfix
Ashim Lamichhane 20
Examples:
1. A * B + C becomes A B * C +
NOTE:
• When the '+' is read, it has lower precedence than the '*', so the '*' must be printed first.
Ashim Lamichhane 21
current symbol Opstack Poststack
A A
* * A
B * AB
+ + AB* {pop and print the '*' before pushing the '+'}
C + AB*C
AB*C+
Examples:
2. A * (B + C) becomes A B C + *
NOTE:
• Since expressions in parentheses must be done first, everything on the stack is saved and the left
parenthesis is pushed to provide a marker.
• When the next operator is read, the stack is treated as though it were empty and the new operator
(here the '+' sign) is pushed on.
• Then when the right parenthesis is read, the stack is popped until the corresponding left parenthesis is
found.
• Since postfix expressions have no parentheses, the parentheses are not printed.
Ashim Lamichhane 22
current symbol Opstack Poststack
A A
* * A
( *( A
B *( AB
+ *(+ AB
C *(+ ABC
) * ABC+
ABC+*
Ashim Lamichhane 23
Classwork
• A - B + C
• A * B ^ C + D
• A * (B + C * D) + E
Ashim Lamichhane 24
References
• For Code Check Github
• For Assignment Check Github
Ashim Lamichhane 25
Recursion
• Recursion is a process by which a function calls itself repeatedly, until
some specified condition has been satisfied
• The process is used for repetitive computations in which each action is
stated in terms of a previous result.
• To solve a problem recursively, two conditions must be satisfied.
• First, the problem must be written in a recursive form
• Second the problem statement must include a stopping condition
Ashim Lamichhane 26
Factorial of an integer number using recursive function
void main(){
int n;
long int facto;
scanf(“%d”,&n);
facto=factorial(n);
printf(“%d!=%ld”,n,facto);
}
long int factorial(int n){
if(n==0){
return 1;
}else{
return n*factorial(n-1);
}
Factorial(5)=
5*Factorial(4)=
5*(4*Factorial(3))=
5*(4*(3*Factorial(2)))=
5*(4*(3*(2*Factorial(1))))=
5*(4*(3*(2*(1*Factorial(0)))))=
5*(4*(3*(2*(1*1))))= 5*(4*(3*(2*1)))=
5*(4*(3*2))= 5*(4*6)= 5*24=
120
Ashim Lamichhane 27
Recursion Pros and Cons
• Pros
• The code may be much easier to write.
• To solve some problems which are naturally recursive such as tower of Hanoi.
• Cons
• Recursive functions are generally slower than non-recursive functions.
• May require a lot of memory to hold intermediate results on the system stack.
• It is difficult to think recursively so one must be very careful when writing
recursive functions.
Ashim Lamichhane 28
Tower of Hanoi Problem
Ashim Lamichhane 29
Tower of Hanoi Problem
• The mission is to move all the disks to some another tower without
violating the sequence of arrangement.
• The below mentioned are few rules which are to be followed for tower
of hanoi −
• Only one disk can be moved among the towers at any given time.
• Only the "top" disk can be removed.
• No large disk can sit over a small disk.
Ashim Lamichhane 30
A recursive algorithm for Tower of Hanoi can be driven as follows −
Ashim Lamichhane 31
THE END
Ashim Lamichhane 32

More Related Content

What's hot

Selection sort
Selection sortSelection sort
Selection sort
Jay Patel
 

What's hot (20)

Selection sort
Selection sortSelection sort
Selection sort
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
Data structure by Digvijay
Data structure by DigvijayData structure by Digvijay
Data structure by Digvijay
 
Data structures
Data structuresData structures
Data structures
 
Linklist
LinklistLinklist
Linklist
 
Single linked list
Single linked listSingle linked list
Single linked list
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Data Structure and Algorithms
Data Structure and Algorithms Data Structure and Algorithms
Data Structure and Algorithms
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
Stack
StackStack
Stack
 
Hash table
Hash tableHash table
Hash table
 
Array in c++
Array in c++Array in c++
Array in c++
 

Viewers also liked

Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
greatqadirgee4u
 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_MX
 
Friedman two way analysis of variance by
Friedman two way analysis of  variance byFriedman two way analysis of  variance by
Friedman two way analysis of variance by
Iybaro Reyes
 
Lecture 10 data structures and algorithms
Lecture 10 data structures and algorithmsLecture 10 data structures and algorithms
Lecture 10 data structures and algorithms
Aakash deep Singhal
 

Viewers also liked (20)

Queues
QueuesQueues
Queues
 
Linked List
Linked ListLinked List
Linked List
 
Sorting
SortingSorting
Sorting
 
Searching
SearchingSearching
Searching
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structure
 
Algorithm big o
Algorithm big oAlgorithm big o
Algorithm big o
 
Unit 11. Graphics
Unit 11. GraphicsUnit 11. Graphics
Unit 11. Graphics
 
Algorithm Introduction
Algorithm IntroductionAlgorithm Introduction
Algorithm Introduction
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Friedman two way analysis of variance by
Friedman two way analysis of  variance byFriedman two way analysis of  variance by
Friedman two way analysis of variance by
 
Polish nootation
Polish nootationPolish nootation
Polish nootation
 
Lecture 10 data structures and algorithms
Lecture 10 data structures and algorithmsLecture 10 data structures and algorithms
Lecture 10 data structures and algorithms
 
ARM procedure calling conventions and recursion
ARM procedure calling conventions and recursionARM procedure calling conventions and recursion
ARM procedure calling conventions and recursion
 
Program activation records
Program activation recordsProgram activation records
Program activation records
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Dsa circular queue
Dsa circular queueDsa circular queue
Dsa circular queue
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 

Similar to The Stack And Recursion

Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
Kumar
 

Similar to The Stack And Recursion (20)

Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
Stack
StackStack
Stack
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Data structures
Data structures Data structures
Data structures
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
Data Structure and Algorithms Stacks
Data Structure and Algorithms StacksData Structure and Algorithms Stacks
Data Structure and Algorithms Stacks
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - Notes
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Stack
StackStack
Stack
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Stack application
Stack applicationStack application
Stack application
 

More from Ashim Lamichhane

More from Ashim Lamichhane (8)

Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
 
Unit 4. Operators and Expression
Unit 4. Operators and Expression  Unit 4. Operators and Expression
Unit 4. Operators and Expression
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
 
Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer   Unit 1. Problem Solving with Computer
Unit 1. Problem Solving with Computer
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

The Stack And Recursion

  • 2. Simple as it sounds Fig. stack of items Ashim Lamichhane 2
  • 3. Definition • A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one end, called the top of the stack. • Stack is a linear data structure where all the insertions and deletions are done at end rather than in the middle. • Stacks are also called Last in First Out (LIFO) lists. Ashim Lamichhane 3
  • 4. Intro • We may come across situations, where insertion or deletion is required only at one end, either at the beginning or end of the list. • The suitable data structures to fulfil such requirements are stacks and queues. • For ex. a stack of plates, a stack of coins, a stack of books etc. Ashim Lamichhane 4
  • 5. Stack as an abstract data type • A stack of elements of type T is a finite sequence of elements together with the operations 1. CreateEmptyStack(S): create or make stack S be an empty stack 2. Push(S,x): Insert x at one end of the stack, called its top 3. Top(S): If stack S is not empty; then retrieve the element at its top 4. Pop(S): If stack S is not empty; then delete the element at its top 5. IsFull(S): Determine if S is full or not. Return true if S is full stack; return false otherwise 6. IsEmpty(S): Determine if S is empty or not. Return true if S is an empty stack; return false otherwise. Ashim Lamichhane 5
  • 7. Example of Push Pop Ashim Lamichhane 7
  • 8. Thing to consider • Stack underflow happens when we try to pop (remove) an item from the stack, when nothing is actually there to remove. • Stack overflow happens when we try to push one more item onto our stack than it can actually hold. Ashim Lamichhane 8
  • 9. Stack As a Linked List • The stack as linked list is represented as a single linked list. • Each node in the list contains data and a pointer to the next node. • The structure defined to represent stack is as follows: struct node{ int data; node *next; }; Fig. Stack as a linked list Ashim Lamichhane 9
  • 10. Infix, Postfix and Prefix • 2+3 <operand><operator><operand> • A-b • (P*2) Operands are basic objects on which operation is performed INFIX <operand><operator><operand> • (2+3) * 4 (2+3) * 4 • (P+Q)*(R+S) (P+Q) * (R+S) Common expressions Ashim Lamichhane 10
  • 11. Infix • What about 4+6*2and what about 4+6+2 • To clear ambiguity we remember school Mathematics • Order of precedence 1. Parentheses (Brackets) 2. Order (Exponents) 3. Division 4. Multiplication 5. Addition 6. Subtraction • So 4+6*2 | 2*6/2 -3 +7 | {(2*6)/2}-(3+7) =4+12 | = 2*3-3+7 | = ??? =16 | = 6-3+7 | = ?? | = 3+7=10 | = ? Ashim Lamichhane 11
  • 12. Prefix (polish notation) • In prefix notation the operator proceeds the two operands. i.e. the operator is written before the operands. <operator><operand><operand> infix prefix 2+3 +23 p-q -pq a+b*c +a*bc Ashim Lamichhane 12
  • 13. Postfix (Reverse Polish Notation) • In postfix notation the operators are written after the operands so it is called the postfix notation (post means after). <operand><operand><operator> infix prefix postfix 2+3 +23 23+ p-q -pq pq- a+b*c +a*bc abc*+ Human-readable Good for machines Ashim Lamichhane 13
  • 14. Conversion of Infix to Postfix Expression • While evaluating an infix expression, there is an evaluation order according to which the operations are executed • Brackets or Parentheses • Exponentiation • Multiplication or Division • Addition or Subtraction • The operators with same priority are evaluated from left to right. • Eg: • A+B+C means (A+B)+C Ashim Lamichhane 14
  • 15. Evaluation of Prefix and Postfix Expressions • Suppose an expression a*b+c*d-e • We can write this as: {(a*b)+(c*d)}-e • As we want to change it into postfix expression {(ab*)+(cd*)}-e {(ab*)(cd*)+}-e {(ab*)(cd*)+} e- • Final form ab*cd*+e- Ashim Lamichhane 15
  • 16. Evaluation of Postfix Expressions • Suppose we have a postfix expression ab*cd*+e- • And we want to evaluate it so lets say a=2, b=3,c=5,d=4,e=9 • We can solve this as, 2 3 * 5 4 * + 9 – <operand><operand><operator> 6 5 4 * + 9 – 6 20 + 9 – 26 9 – 17 Ashim Lamichhane 16
  • 17. Evaluation of Postfix Expressions • From above we get, 2 3 * 5 4 * + 9 – Stack EvaluatePostfix(exp) { create a stack S for i=0 to length (exp) -1 { if (exp[i] is operand) PUSH(exp[i]) elseif (exp[i] is operator) op2 <- pop() op1 <- pop() res– Perform(exp[i],op1,op2) PUSH(res) } return top of STACK } 2 3 Ashim Lamichhane 17
  • 18. Evaluation of Prefix expressions • An expression: 2*3 +5*4-9 • Can be written as: {(2*3)+(5*4)}-9 {(*2 3)+(*5 4)}-9 {+(*2 3) (*5 4)}-9 -{+(*2 3) (*5 4)}9 • We can get Rid of Paranthesis -+*2 3 *5 4 9 Ashim Lamichhane 18
  • 19. Evaluation of Prefix expressions • We have to scan it from right -+*2 3 *5 4 9 Stack 9 4 5 Stack 9 20 6 Stack 9 26 Stack 17 Ashim Lamichhane 19
  • 20. Algorithm to convert Infix to Postfix Ashim Lamichhane 20
  • 21. Examples: 1. A * B + C becomes A B * C + NOTE: • When the '+' is read, it has lower precedence than the '*', so the '*' must be printed first. Ashim Lamichhane 21 current symbol Opstack Poststack A A * * A B * AB + + AB* {pop and print the '*' before pushing the '+'} C + AB*C AB*C+
  • 22. Examples: 2. A * (B + C) becomes A B C + * NOTE: • Since expressions in parentheses must be done first, everything on the stack is saved and the left parenthesis is pushed to provide a marker. • When the next operator is read, the stack is treated as though it were empty and the new operator (here the '+' sign) is pushed on. • Then when the right parenthesis is read, the stack is popped until the corresponding left parenthesis is found. • Since postfix expressions have no parentheses, the parentheses are not printed. Ashim Lamichhane 22 current symbol Opstack Poststack A A * * A ( *( A B *( AB + *(+ AB C *(+ ABC ) * ABC+ ABC+*
  • 24. Classwork • A - B + C • A * B ^ C + D • A * (B + C * D) + E Ashim Lamichhane 24
  • 25. References • For Code Check Github • For Assignment Check Github Ashim Lamichhane 25
  • 26. Recursion • Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied • The process is used for repetitive computations in which each action is stated in terms of a previous result. • To solve a problem recursively, two conditions must be satisfied. • First, the problem must be written in a recursive form • Second the problem statement must include a stopping condition Ashim Lamichhane 26
  • 27. Factorial of an integer number using recursive function void main(){ int n; long int facto; scanf(“%d”,&n); facto=factorial(n); printf(“%d!=%ld”,n,facto); } long int factorial(int n){ if(n==0){ return 1; }else{ return n*factorial(n-1); } Factorial(5)= 5*Factorial(4)= 5*(4*Factorial(3))= 5*(4*(3*Factorial(2)))= 5*(4*(3*(2*Factorial(1))))= 5*(4*(3*(2*(1*Factorial(0)))))= 5*(4*(3*(2*(1*1))))= 5*(4*(3*(2*1)))= 5*(4*(3*2))= 5*(4*6)= 5*24= 120 Ashim Lamichhane 27
  • 28. Recursion Pros and Cons • Pros • The code may be much easier to write. • To solve some problems which are naturally recursive such as tower of Hanoi. • Cons • Recursive functions are generally slower than non-recursive functions. • May require a lot of memory to hold intermediate results on the system stack. • It is difficult to think recursively so one must be very careful when writing recursive functions. Ashim Lamichhane 28
  • 29. Tower of Hanoi Problem Ashim Lamichhane 29
  • 30. Tower of Hanoi Problem • The mission is to move all the disks to some another tower without violating the sequence of arrangement. • The below mentioned are few rules which are to be followed for tower of hanoi − • Only one disk can be moved among the towers at any given time. • Only the "top" disk can be removed. • No large disk can sit over a small disk. Ashim Lamichhane 30
  • 31. A recursive algorithm for Tower of Hanoi can be driven as follows − Ashim Lamichhane 31