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

DSA Postfix To Evaluate

The document contains a C program that evaluates postfix expressions using a stack data structure. It defines functions for pushing and popping values from the stack and processes the input expression to compute the result. The program prompts the user to enter a postfix expression and outputs the computed result.

Uploaded by

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

DSA Postfix To Evaluate

The document contains a C program that evaluates postfix expressions using a stack data structure. It defines functions for pushing and popping values from the stack and processes the input expression to compute the result. The program prompts the user to enter a postfix expression and outputs the computed result.

Uploaded by

Aaryan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

NAME – ARYAN KUMAR

MIS -112415033

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

#define MAX 100

typedef struct {
int top;
int items[MAX];
} Stack;

void push(Stack *s, int value);


int pop(Stack *s);
int EPF(char *expression);

void push(Stack *s, int value) {


if (s->top == MAX - 1) {
printf("Stack Overflow\n");
exit(1);
}
s->items[++(s->top)] = value;
}

int pop(Stack *s) {


if (s->top == -1) {
printf("Stack Underflow\n");
exit(1);
}
return s->items[(s->top)--];
}

int EPF(char *expression) {


Stack s;
s.top = -1;

char *token = strtok(expression, " ");


while (token != NULL) {
if (isdigit(token[0]) || (token[0] == '-' && isdigit(token[1])))
{
push(&s, atoi(token));
} else {
int operand2 = pop(&s);
int operand1 = pop(&s);

switch (token[0]) {
case '+':
push(&s, operand1 + operand2);
break;

case '-':
push(&s, operand1 - operand2);
break;

case '*':
push(&s, operand1 * operand2);
break;

case '/':
if (operand2 == 0) {
printf("Division by zero error\n");
exit(1);
}
push(&s, operand1 / operand2);
break;
default:
printf("Invalid operator encountered: %s\n", token);
exit(1);
}
}
token = strtok(NULL, " ");
}
return pop(&s);
}

int main() {
char expression[MAX];
printf("Enter a postfix expression ");
fgets(expression, MAX, stdin);

int result = EPF(expression);


printf("Result: %d\n", result);

return 0;
}

OUTPUT:-
Enter a postfix expression 2 3 4 * +

Result: 14

You might also like