SlideShare a Scribd company logo
Applications of stack
Checking the validity of an arithmetic expression
Checking an expression is nothing but checking
1. Whether there are equal number of right and left parenthesis.
2. Whether right parenthesis is preceded by a matching left parenthesis.
If both the above conditions are satisfied, expression is valid.
Ex:
 ((A+B) or A+B( are not valid expressions because they violate condition 1.
 )a+b(-c violate condition 2.
 (a+b)) violate both the conditions.
 (a+b) * (c+d) is a valid expression.
Stacks can be used to check this.
Exp: [ ( A + B ) - { C + D } ] - [ F + G ]
Symbol Scanned STACK
[ [
( [, (
A [, (
+ [, (
B [, (
) [
- [
{ [, {
C [, {
+ [, {
D [, {
} [
]
-
[ [
F [
+ [
G [
]
In the above example we see the stack is empty at the end, so the expression is valid.
Sample Code
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[50],stack[50];
int i,len,top=0;
printf("Enter an arithmatic expression:n");
gets(str);
len=strlen(str);
for(i=0;i<len;i++)
{
if(str[i]=='['||str[i]=='{'||str[i]=='(')
{
top++;
stack[top]=str[i];
}
else if(str[i]==']'||str[i]=='}'||str[i]==')')
top--;
}
if(top==0)
printf("The expression is valid.");
else
printf("The expression is not valid.");
getch();
}
Sample Output
Case 1:
Enter an arithmatic expression:
[ ( A + B ) - { C + D } ] - [ F + G ]
The expression is valid.
Case 2:
Enter an arithmatic expression:
[ ( A + B ) - { C + D } ] - [ F + G
The expression is not valid.
Converting an infix arithmetic expression to its postfix form
Expressions are usually represented in what is known as Infix notation, in which each operator is
written between two operands (i.e., A + B).
Polish notation (prefix notation) - It refers to the notation in which the operator is placed before its
two operands. Here no parentheses are required, i.e., +AB.
Reverse Polish notation (postfix notation) - It refers to the analogous notation in which the operator
is placed after its two operands. Again, no parentheses is required in Reverse Polish notation, i.e.,
AB+.
There are 3 levels of precedence for 5 binary operators as given below:
Highest: Exponentiation (^ or ↑)
Next highest: Multiplication (* or x) and division (/ or ÷)
Lowest: Addition (+) and Subtraction (-)
Algorithm for Infix to Postfix
Step 1: Consider the next element in the input.
Step 2: If it is operand, display it.
Step 3: If it is opening parenthesis, insert it on stack.
Step 4: If it is an operator, then
 If stack is empty, insert operator on stack.
 If the top of stack is opening parenthesis, insert the operator on stack
 If it has higher priority than the top of stack, insert the operator on stack.
 Else, delete the operator from the stack and display it, repeat Step 4.
Step 5: If it is a closing parenthesis, delete the operator from stack and display them until an
opening parenthesis is encountered. Delete and discard the opening parenthesis.
Step 6: If there is more input, go to Step 1.
Step 7: If there is no more input, delete the remaining operators to output.
Exp: 3 * 3 / ( 4 – 1 ) + 6 * 2
Expression STACK Postfix expression
3 3
* * 3
3 * 3, 3
/ / 3, 3, *
( / ( 3, 3, *
4 / ( 3, 3, *, 4
- / ( - 3, 3, *, 4
1 / ( - 3, 3, *, 4, 1
) / 3, 3, *, 4, 1, -
+ + 3, 3, *, 4, 1, -, /
6 + 3, 3, *, 4, 1, -, /, 6
* + * 3, 3, *, 4, 1, -, /, 6, 2
2 + * 3, 3, *, 4, 1, -, /, 6, 2
3, 3, *, 4, 1, -, /, 6, 2, *, +
Sample Code
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("n");
e = exp;
while(*e != '0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
Sample Output
Enter the expression : 3*3/(4-1)+6*2
Postfix expression: 3 3 * 4 1 - / 6 2 * +
Evaluating a postfix expression
To evaluate the postfix expression we scan the expression from left to right. The steps involved
in evaluating a postfix expression are:
Step 1: If an operand is encountered, push it on STACK.
Step 2: If an operator “op” is encountered
i. Pop two elements of STACK, where A is the top element and B is the next top element.
ii. Evaluate B op A.
iii. Push the result on STACK.
Step3: The evaluated value is equal to the value at the top of STACK.
Exp: 4 3 2 5 * - +
Input symbol STACK Operation (B op A)
4 4
3 4, 3
2 4, 3, 2
5 4, 3, 2, 5
* 4, 3, 10 [2*5] (A=5, B=2)
- 4, -7 [3-10] (A=10, B=3)
+ -3 [4+(-7)] (A=-7, B=4)
Sample Code
#include <stdio.h>
#include <ctype.h>
#define MAXSTACK 100
#define POSTFIXSIZE 100
int stack[MAXSTACK];
int top = -1;
void push(int item)
{
if (top >= MAXSTACK - 1) {
printf("stack over flow");
return;
}
else {
top = top + 1;
stack[top] = item;
}
}
int pop()
{
int item;
if (top < 0) {
printf("stack under flow");
}
else {
item = stack[top];
top = top - 1;
return item;
}
}
void EvalPostfix(char postfix[])
{
int i;
char ch;
int val;
int A, B;
for (i = 0; postfix[i] != ')'; i++) {
ch = postfix[i];
if (isdigit(ch)) {
push(ch - '0');
}
else if (ch == '+' || ch == '-' || ch == '*' || ch ==
'/') {
A = pop();
B = pop();
switch (ch)
{
case '*':
val = B * A;
break;
case '/':
val = B / A;
break;
case '+':
val = B + A;
break;
case '-':
val = B - A;
break;
}
push(val);
}
}
printf(" n Result of expression evaluation : %d n",
pop());
}
int main()
{
int i;
char postfix[POSTFIXSIZE];
printf("ASSUMPTION: There are only four operators(*, /, +, -
) in an expression and operand is single digit only.n");
printf(" nEnter postfix expression,npress right
parenthesis ')' for end expression : ");
for (i = 0; i <= POSTFIXSIZE - 1; i++) {
scanf("%c", &postfix[i]);
if (postfix[i] == ')')
{
break;
}
}
EvalPostfix(postfix);
return 0;
}
Sample Output
ASSUMPTION: There are only four operators(*, /, +, -) in an expression and operand is single
digit only.
Enter postfix expression,
press right parenthesis ')' for end expression : 4 3 2 5 * - +)
Result of expression evaluation : -3

More Related Content

PPTX
My lecture infix-to-postfix
PPT
Infix prefix postfix
PPT
Application of Stacks
PPT
Circular queues
PPTX
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
PPT
Stack Data Structure V1.0
PDF
Data structures stacks
PPTX
Prefix, Infix and Post-fix Notations
My lecture infix-to-postfix
Infix prefix postfix
Application of Stacks
Circular queues
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
Stack Data Structure V1.0
Data structures stacks
Prefix, Infix and Post-fix Notations

What's hot (19)

DOC
Infix to-postfix examples
PPTX
Stack using Linked List
PPT
03 stacks and_queues_using_arrays
PPTX
Data structures
PPT
Data structure lecture7
PPT
Stack application
PPTX
Application of Stack - Yadraj Meena
PPTX
Stack_Application_Infix_Prefix.pptx
PPT
PPT
Stack Operation In Data Structure
PPT
PPTX
USER DEFINE FUNCTIONS IN PYTHON
PPTX
Function recap
PPTX
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
PPT
Conversion of Infix To Postfix Expressions
PPTX
Expressions using operator in c
PPTX
Decision making and branching
Infix to-postfix examples
Stack using Linked List
03 stacks and_queues_using_arrays
Data structures
Data structure lecture7
Stack application
Application of Stack - Yadraj Meena
Stack_Application_Infix_Prefix.pptx
Stack Operation In Data Structure
USER DEFINE FUNCTIONS IN PYTHON
Function recap
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
Conversion of Infix To Postfix Expressions
Expressions using operator in c
Decision making and branching
Ad

Similar to Applications of stack (20)

PDF
Data structure lab manual
PPTX
Applicationofstack by Ali F.RAshid
PPTX
5.stack
PPTX
Lec5-Stack-bukc-28022024-112316am (1) .pptx
PPTX
DS UNIT1_STACKS.pptx
PDF
The concept of stack is extremely important in computer science and .pdf
PPTX
Lecture 6 data structures and algorithms
PPTX
Data strutcure and annalysis topic stack
PPTX
Topic 2_revised.pptx
PPT
MO 2020 DS Stacks 3 AB.ppt
PPTX
Lecture_04.2.pptx
PPSX
Data structure_Stack Introduction & app.
PPTX
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
PPT
data structure and algorithm by bomboat_3
PPT
Stack in Data Structure
PPT
PPTX
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
PPTX
Infix postfixcoversion
PPTX
COMP1603 Stacks and RPN 2023 Recording (2).pptx
Data structure lab manual
Applicationofstack by Ali F.RAshid
5.stack
Lec5-Stack-bukc-28022024-112316am (1) .pptx
DS UNIT1_STACKS.pptx
The concept of stack is extremely important in computer science and .pdf
Lecture 6 data structures and algorithms
Data strutcure and annalysis topic stack
Topic 2_revised.pptx
MO 2020 DS Stacks 3 AB.ppt
Lecture_04.2.pptx
Data structure_Stack Introduction & app.
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
data structure and algorithm by bomboat_3
Stack in Data Structure
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
Infix postfixcoversion
COMP1603 Stacks and RPN 2023 Recording (2).pptx
Ad

More from A. S. M. Shafi (20)

DOCX
Data Warehouse Schema (Star, Snowflake).docx
PDF
Correlation Analysis in Machine Learning.pdf
PDF
Naive Bayes and Decision Tree Algorithm.pdf
PDF
Frequent Pattern Growth Mining Algorithm.pdf
PDF
Direct Hashing and Pruning Algorithm in Data MIning.pdf
PDF
Association Rule Mining with Apriori Algorithm.pdf
PDF
HITS Algorithm in Data and Web MIning.pdf
PDF
Page Rank Algorithm in Data Mining and Web Application.pdf
PDF
K Nearest Neighbor Classifier in Machine Learning.pdf
PDF
K Means Clustering Algorithm in Machine Learning.pdf
PDF
2D Transformation in Computer Graphics
PDF
3D Transformation in Computer Graphics
PDF
Projection
PDF
2D Transformation
PDF
Line drawing algorithm
PDF
Fragmentation
PDF
File organization
PDF
Bankers algorithm
PDF
RR and priority scheduling
PDF
Fcfs and sjf
Data Warehouse Schema (Star, Snowflake).docx
Correlation Analysis in Machine Learning.pdf
Naive Bayes and Decision Tree Algorithm.pdf
Frequent Pattern Growth Mining Algorithm.pdf
Direct Hashing and Pruning Algorithm in Data MIning.pdf
Association Rule Mining with Apriori Algorithm.pdf
HITS Algorithm in Data and Web MIning.pdf
Page Rank Algorithm in Data Mining and Web Application.pdf
K Nearest Neighbor Classifier in Machine Learning.pdf
K Means Clustering Algorithm in Machine Learning.pdf
2D Transformation in Computer Graphics
3D Transformation in Computer Graphics
Projection
2D Transformation
Line drawing algorithm
Fragmentation
File organization
Bankers algorithm
RR and priority scheduling
Fcfs and sjf

Recently uploaded (20)

PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Lesson notes of climatology university.
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
Trump Administration's workforce development strategy
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Computing-Curriculum for Schools in Ghana
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Final Presentation General Medicine 03-08-2024.pptx
What if we spent less time fighting change, and more time building what’s rig...
Weekly quiz Compilation Jan -July 25.pdf
Anesthesia in Laparoscopic Surgery in India
Supply Chain Operations Speaking Notes -ICLT Program
Lesson notes of climatology university.
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Trump Administration's workforce development strategy
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Chinmaya Tiranga quiz Grand Finale.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
History, Philosophy and sociology of education (1).pptx
A systematic review of self-coping strategies used by university students to ...
Computing-Curriculum for Schools in Ghana
Module 4: Burden of Disease Tutorial Slides S2 2025
Yogi Goddess Pres Conference Studio Updates
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Final Presentation General Medicine 03-08-2024.pptx

Applications of stack

  • 1. Applications of stack Checking the validity of an arithmetic expression Checking an expression is nothing but checking 1. Whether there are equal number of right and left parenthesis. 2. Whether right parenthesis is preceded by a matching left parenthesis. If both the above conditions are satisfied, expression is valid. Ex:  ((A+B) or A+B( are not valid expressions because they violate condition 1.  )a+b(-c violate condition 2.  (a+b)) violate both the conditions.  (a+b) * (c+d) is a valid expression. Stacks can be used to check this. Exp: [ ( A + B ) - { C + D } ] - [ F + G ] Symbol Scanned STACK [ [ ( [, ( A [, ( + [, ( B [, ( ) [ - [ { [, { C [, { + [, { D [, { } [ ] - [ [ F [ + [ G [ ] In the above example we see the stack is empty at the end, so the expression is valid.
  • 2. Sample Code #include<stdio.h> #include<conio.h> #include<string.h> int main() { char str[50],stack[50]; int i,len,top=0; printf("Enter an arithmatic expression:n"); gets(str); len=strlen(str); for(i=0;i<len;i++) { if(str[i]=='['||str[i]=='{'||str[i]=='(') { top++; stack[top]=str[i]; } else if(str[i]==']'||str[i]=='}'||str[i]==')') top--; } if(top==0) printf("The expression is valid."); else printf("The expression is not valid."); getch(); }
  • 3. Sample Output Case 1: Enter an arithmatic expression: [ ( A + B ) - { C + D } ] - [ F + G ] The expression is valid. Case 2: Enter an arithmatic expression: [ ( A + B ) - { C + D } ] - [ F + G The expression is not valid. Converting an infix arithmetic expression to its postfix form Expressions are usually represented in what is known as Infix notation, in which each operator is written between two operands (i.e., A + B). Polish notation (prefix notation) - It refers to the notation in which the operator is placed before its two operands. Here no parentheses are required, i.e., +AB. Reverse Polish notation (postfix notation) - It refers to the analogous notation in which the operator is placed after its two operands. Again, no parentheses is required in Reverse Polish notation, i.e., AB+. There are 3 levels of precedence for 5 binary operators as given below: Highest: Exponentiation (^ or ↑) Next highest: Multiplication (* or x) and division (/ or ÷) Lowest: Addition (+) and Subtraction (-) Algorithm for Infix to Postfix Step 1: Consider the next element in the input. Step 2: If it is operand, display it. Step 3: If it is opening parenthesis, insert it on stack. Step 4: If it is an operator, then  If stack is empty, insert operator on stack.  If the top of stack is opening parenthesis, insert the operator on stack
  • 4.  If it has higher priority than the top of stack, insert the operator on stack.  Else, delete the operator from the stack and display it, repeat Step 4. Step 5: If it is a closing parenthesis, delete the operator from stack and display them until an opening parenthesis is encountered. Delete and discard the opening parenthesis. Step 6: If there is more input, go to Step 1. Step 7: If there is no more input, delete the remaining operators to output. Exp: 3 * 3 / ( 4 – 1 ) + 6 * 2 Expression STACK Postfix expression 3 3 * * 3 3 * 3, 3 / / 3, 3, * ( / ( 3, 3, * 4 / ( 3, 3, *, 4 - / ( - 3, 3, *, 4 1 / ( - 3, 3, *, 4, 1 ) / 3, 3, *, 4, 1, - + + 3, 3, *, 4, 1, -, / 6 + 3, 3, *, 4, 1, -, /, 6 * + * 3, 3, *, 4, 1, -, /, 6, 2 2 + * 3, 3, *, 4, 1, -, /, 6, 2 3, 3, *, 4, 1, -, /, 6, 2, *, + Sample Code #include<stdio.h> #include<ctype.h> char stack[100]; int top = -1;
  • 5. void push(char x) { stack[++top] = x; } char pop() { if(top == -1) return -1; else return stack[top--]; } int priority(char x) { if(x == '(') return 0; if(x == '+' || x == '-') return 1; if(x == '*' || x == '/') return 2; return 0; } int main()
  • 6. { char exp[100]; char *e, x; printf("Enter the expression : "); scanf("%s",exp); printf("n"); e = exp; while(*e != '0') { if(isalnum(*e)) printf("%c ",*e); else if(*e == '(') push(*e); else if(*e == ')') { while((x = pop()) != '(') printf("%c ", x); } else { while(priority(stack[top]) >= priority(*e)) printf("%c ",pop()); push(*e);
  • 7. } e++; } while(top != -1) { printf("%c ",pop()); }return 0; } Sample Output Enter the expression : 3*3/(4-1)+6*2 Postfix expression: 3 3 * 4 1 - / 6 2 * + Evaluating a postfix expression To evaluate the postfix expression we scan the expression from left to right. The steps involved in evaluating a postfix expression are: Step 1: If an operand is encountered, push it on STACK. Step 2: If an operator “op” is encountered i. Pop two elements of STACK, where A is the top element and B is the next top element. ii. Evaluate B op A. iii. Push the result on STACK. Step3: The evaluated value is equal to the value at the top of STACK. Exp: 4 3 2 5 * - + Input symbol STACK Operation (B op A) 4 4 3 4, 3 2 4, 3, 2 5 4, 3, 2, 5 * 4, 3, 10 [2*5] (A=5, B=2)
  • 8. - 4, -7 [3-10] (A=10, B=3) + -3 [4+(-7)] (A=-7, B=4) Sample Code #include <stdio.h> #include <ctype.h> #define MAXSTACK 100 #define POSTFIXSIZE 100 int stack[MAXSTACK]; int top = -1; void push(int item) { if (top >= MAXSTACK - 1) { printf("stack over flow"); return; } else { top = top + 1; stack[top] = item; } } int pop() {
  • 9. int item; if (top < 0) { printf("stack under flow"); } else { item = stack[top]; top = top - 1; return item; } } void EvalPostfix(char postfix[]) { int i; char ch; int val; int A, B; for (i = 0; postfix[i] != ')'; i++) { ch = postfix[i]; if (isdigit(ch)) { push(ch - '0'); }
  • 10. else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') { A = pop(); B = pop(); switch (ch) { case '*': val = B * A; break; case '/': val = B / A; break; case '+': val = B + A; break; case '-': val = B - A; break; } push(val); } }
  • 11. printf(" n Result of expression evaluation : %d n", pop()); } int main() { int i; char postfix[POSTFIXSIZE]; printf("ASSUMPTION: There are only four operators(*, /, +, - ) in an expression and operand is single digit only.n"); printf(" nEnter postfix expression,npress right parenthesis ')' for end expression : "); for (i = 0; i <= POSTFIXSIZE - 1; i++) { scanf("%c", &postfix[i]); if (postfix[i] == ')') { break; } } EvalPostfix(postfix); return 0; } Sample Output
  • 12. ASSUMPTION: There are only four operators(*, /, +, -) in an expression and operand is single digit only. Enter postfix expression, press right parenthesis ')' for end expression : 4 3 2 5 * - +) Result of expression evaluation : -3