MIT-Curricular/DS/C/Lab/Week5/PostfixCheck.c

86 lines
1.5 KiB
C
Raw Normal View History

2024-09-03 00:26:38 +05:30
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
2024-09-03 11:27:09 +05:30
void push(int item)
{
if (top >= MAX_SIZE - 1)
{
2024-09-03 00:26:38 +05:30
printf("Stack Overflow\n");
return;
}
stack[++top] = item;
}
2024-09-03 11:27:09 +05:30
int pop()
{
if (top < 0)
{
2024-09-03 00:26:38 +05:30
printf("Stack Underflow\n");
2024-09-03 11:27:09 +05:30
return -1;
2024-09-03 00:26:38 +05:30
}
return stack[top--];
}
2024-09-03 11:27:09 +05:30
int isDigit(char c)
{
2024-09-03 00:26:38 +05:30
return c >= '0' && c <= '9';
}
2024-09-03 11:27:09 +05:30
int evaluatePostfix(char *exp)
{
2024-09-03 00:26:38 +05:30
int i, operand1, operand2, result;
2024-09-03 11:27:09 +05:30
for (i = 0; exp[i] != '\0'; i++)
{
if (isDigit(exp[i]))
{
2024-09-03 00:26:38 +05:30
push(exp[i] - '0');
2024-09-03 11:27:09 +05:30
}
else
{
2024-09-03 00:26:38 +05:30
operand2 = pop();
operand1 = pop();
2024-09-03 11:27:09 +05:30
switch (exp[i])
{
case '+':
push(operand1 + operand2);
break;
case '-':
push(operand1 - operand2);
break;
case '*':
push(operand1 * operand2);
break;
case '/':
if (operand2 == 0)
{
printf("Error: Division by zero\n");
return -1;
}
push(operand1 / operand2);
break;
2024-09-03 00:26:38 +05:30
}
}
}
return pop();
}
2024-09-03 11:27:09 +05:30
int main()
{
2024-09-03 00:26:38 +05:30
char exp[MAX_SIZE];
printf("Enter a postfix expression: ");
2024-09-03 11:27:09 +05:30
gets(exp);
2024-09-03 00:26:38 +05:30
int result = evaluatePostfix(exp);
2024-09-03 11:27:09 +05:30
if (result != -1)
{
2024-09-03 00:26:38 +05:30
printf("Result: %d\n", result);
}
return 0;
2024-09-03 11:27:09 +05:30
}