MIT-Curricular/DS/C/Lab/Week6/PrefixCheck.c

91 lines
1.6 KiB
C
Raw Permalink Normal View History

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