Explain the evaluation of expressions of stacks in C language


Stack is a linear data structure, where data is inserted and removed only at one end.

Algorithms

Given below is an algorithm for Push ( ) −

  • Check for stack overflow.
if (top = = n-1)
printf("stack over flow");
  • Otherwise, insert an element into the stack.
top ++
a[top] = item

Given below is an algorithm for Pop ( )

  • Check for stack underflow.
if ( top = = -1)
printf( "stack under flow");

Otherwise, delete an element from the stack.

item = a[top]
top --

Given below is an algorithm for Display ( )

if (top == -1)
printf ("stack is empty");

Otherwise, follow the below mentioned algorithm.

for (i=0; i<top; i++)
printf ("%d", a[i]);

Application of stacks

Let us understand the conversions of expressions of stacks in C language.

Expression − It is a legal combination of operands and operations.

Types of expressions

There are three types of expressions in C language on which the conversions and valuation can be carried out. They are explained below −

  • Infix expression − Operator is in between the operands. For example, A+B

  • Prefix expression − Operator is before the operands. For example, +AB

  • Postfix expression − Operator is after the operands. For example, AB+

Evaluation of postfix expression

Algorithm

Scan the input string from left to right.

For each input symbol,

  • If it is a digit then, push it on to the stack.

  • If it is an operator then, pop out the top most two contents from the stack and apply the operator on them. Later on, push the result on to stack.

  • If the input symbol is ‘\0’, empty the stack.

Program

Following is the C program for an evaluation of postfix expression −

 Live Demo

#include<stdio.h>
int top = -1, stack [100];
main ( ){
   char a[50], ch;
   int i,op1,op2,res,x;
   void push (int);
   int pop( );
   int eval (char, int, int);
   printf("enter a postfix expression:");
   gets (a);
   for(i=0; a[i]!='\0'; i++){
      ch = a[i];
      if (ch>='0' && ch<='9')
         push('0');
      else{
         op2 = pop ( );
         op1 = pop ( );
         res = eval (ch, op1, op2);
         push (res);
      }
   }
   x = pop ( );
   printf("evaluated value = %d", x);
   getch ( );
}
void push (int n){
   top++;
   stack [top] = n;
}
int pop ( ){
   int res ;
   res = stack [top];
   top--;
   return res;
}
int eval (char ch, int op1, int op2){
   switch (ch){
      case '+' : return (op1+op2);
      case '-' : return (op1-op2);
      case '*' : return (op1*op2);
      case '/' : return (op1/op2);
   }
}

Output

When the above program is executed, it produces the following result −

Run 1:
enter a postfix expression:45+
evaluated value = 9
Run 2:
enter a postfix expression: 3 5 2 * +
evaluated value = 13

Updated on: 24-Mar-2021

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements