0% found this document useful (0 votes)
3 views3 pages

Multi-Digit Postfix Expression Evaluator

The document contains a C program that evaluates multi-digit postfix expressions. It utilizes a stack to process numbers and operators, allowing the user to input a postfix expression with spaces between elements. The program computes the result and outputs it to the user.

Uploaded by

Samuel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Multi-Digit Postfix Expression Evaluator

The document contains a C program that evaluates multi-digit postfix expressions. It utilizes a stack to process numbers and operators, allowing the user to input a postfix expression with spaces between elements. The program computes the result and outputs it to the user.

Uploaded by

Samuel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Supports multi-digit postfix Evaluation

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int stack[50];
int top = -1;
void push(int x) {
stack[++top] = x;
}
int pop() {
return stack[top--];
}
int main() {
char exp[200];
char *token;
int n1, n2, n3;
printf("Enter POSTFIX expression (use spaces between
numbers/operators):\n");
fgets(exp, sizeof(exp), stdin);
// remove newline
exp[strcspn(exp, "\n")] = '\0';
// split into tokens
token = strtok(exp, " ");
while (token != NULL) {
// if operator (+ - * /)
if (strlen(token) == 1 &&
(*token == '+' || *token == '-' ||
*token == '*' || *token == '/')) {

n1 = pop();
n2 = pop();

switch (*token) {
case '+': n3 = n2 + n1; break;
case '-': n3 = n2 - n1; break;
case '*': n3 = n2 * n1; break;
case '/': n3 = n2 / n1; break;
}
push(n3);
} else {
// multi-digit number
push(atoi(token));
}
token = strtok(NULL, " ");
}
printf("\nThe result = %d\n", pop());
return 0;
}

You might also like