Professional Documents
Culture Documents
RA2011003010008
CSE A1
Question:
Given string S representing a postfix expression, the task is to evaluate the expression and
find the final value.
Approach:
Input is put into stack and each character is evaluated with switch case.
Scalability:
User inputs the desired data.
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
//Create stack
struct Stack *createStack(int size)
{
struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack));
if (!stack)
return NULL;
stack->top = -1;
stack->size = size;
stack->array = (int *)malloc(stack->size * sizeof(int));
if (!stack->array)
return NULL;
return stack;
}
if (isdigit(exp[i]))
push(stack, exp[i] - '0');
else
{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i])
{
case '+':
push(stack, val2 + val1);
break;
case '-':
push(stack, val2 - val1);
break;
case '*':
push(stack, val2 * val1);
break;
case '/':
push(stack, val2 / val1);
break;
}
}
}
return pop(stack);
}
int main()
{
char exp[10];
int n;
printf("Enter Total Test Cases\n");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%s", exp);
printf("EXPRESSION IN POSTFIX: %d\n", evaluatePostfixExpression(exp));
}
return 0;
}