Sunday, 14 August 2016

Lab Program 5a Evaluation of Suffix Expression 15CSL38 Data Structures in C Lab

Lab Program 5a:

Design, Develop and Implement a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^


 #include<stdio.h>
#include<stdlib.h>
#include<math.h>

int i, top = -1;
int op1, op2, res, s[20];
char postfix[90], symb;

void push(int item)
{
            top = top+1;
            s[top] = item;
}

int pop()
{
            int item;
            item  =  s[top];
            top = top-1;
            return item;
}

void main()
{
            printf("\nEnter a valid postfix expression:\n");
            scanf("%s", postfix);
            for(i=0; postfix[i]!='\0'; i++)
            {
                        symb = postfix[i];
                        if(isdigit(symb))
                        {
                                    push(symb - '0');
                        }
                        else
                        {
                                    op2 = pop();
                                    op1 = pop();
                                    switch(symb)
                                    {
                                                case '+':            push(op1+op2);
                                                                        break;
                                                case '-':             push(op1-op2);
                                                                        break;
                                                case '*':            push(op1*op2);
                                                                        break;
                                                case '/':             push(op1/op2);
                                                                        break;
                                                case '%':           push(op1%op2);
                                                                        break;
                                                case '$':
                                                case '^':            push(pow(op1, op2));
                                                                        break;
                                                default :   push(0);
                                    }
                        }
            }
            res = pop();
            printf("\n Result = %d", res);
}

Output:

To compile in Linux: gcc –lm 5.c

Enter a valid postfix expression:
623+-382/+*2$3+
Result = 52


Enter a valid postfix expression:
42$3*3-84/11+/+
Result = 46

Also Credits to: 
Manoj Taleka  (manoj89biet@gmail.com)
Yashaswini Jogi (jogi.yash@gmail.com)