Postfix Temp
Postfix Temp
h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int stack[SIZE];
int top = -1;
// Skip spaces
if (isspace(symbol)) {
i++;
continue;
}
switch (symbol) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/':
if (operand2 == 0) {
printf("Division by zero!\n");
exit(1);
}
result = operand1 / operand2;
break;
case '^': result = (int)pow(operand1, operand2); break;
}
push(result);
}
else {
printf("Invalid character: %c\n", symbol);
exit(1);
}
i++;
}
return pop(); // The result is the only value left in the stack
}
int main() {
char expression[SIZE];
printf("Enter Postfix Expression: ");
fgets(expression, sizeof(expression), stdin);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define SIZE 100
int pop() {
if (top < 0)
{
printf("Stack Underflow!\n");
exit(1);
}
return stack[top--];
}
while (expr[i])
{
if (isspace(expr[i]))
{
i++;
continue;
}
if (expr[i] == '-')
{
i++;
}
while (isdigit(expr[i]))
{
num = num * 10 + (expr[i++] - '0');
}
push(num);
}
else if (strchr("+-*/^", expr[i]))
{
int b = pop(), a = pop();
int result;
switch (expr[i])
{
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/':
if (b == 0)
{
printf("Division by zero!\n");
exit(1);
}
result = a / b;
break;
case '^': result = (int)pow(a, b); break;
default:
printf("Invalid operator: %c\n", expr[i]);
exit(1);
}
push(result);
}
else
{
printf("Invalid character: %c\n", expr[i]);
exit(1);
}
i++;
}
return pop(); // The result is the only value left in the stack
}
int main() {
char expr[SIZE];
printf("Enter Postfix Expression: ");
fgets(expr, SIZE, stdin);