Showing posts with label Evaluation of Postfix Expression. Show all posts
Showing posts with label Evaluation of Postfix Expression. Show all posts

Tuesday, February 10, 2015

Evaluation of Postfix Expression

AIM:
          To write a C program to evaluate the postfix expression

ALGORITHM:
            Step 1: Start the program.
Step 2: Read the postfix expression from left to right
Step 3: If the symbol read is an operand then push it onto the stack
Step 4: If the operator is read POP two operands and perform arithmetic 
            operations if operator is 
            + then result=operand 1 + operand 2
            -  then result=operand 1 - operand 2
            * then result=operand 1 * operand 2
            /  then result=operand 1 / operand 2
Step 5: Push the result onto the stack
Step 6: Repeat steps 2-5 till the postfix expression is not over
Step 7: Stop the program.

PROGRAM
#include <stdio.h>
#include <string.h>
int top = -1;
int stack[100];
/* push the given data into the stack */
void push (int data) {
stack[++top] = data;
}
/* Pop the top element from the stack */
int pop () {
int data;
if (top == -1)
return -1;
data = stack[top];
stack[top] = 0;
top--;
return (data);
}
int main()
 {
char str[100];
int i, data = -1, operand1, operand2, result;
/* Get the postfix expression from the user */
printf("Enter ur postfix expression:");
fgets(str, 100, stdin);
for (i = 0; i < strlen(str); i++)
 {
if (isdigit(str[i]))
{
/*
* if the i/p char is digit, parse
* character by character to get
* complete operand
*/
data = (data == -1) ? 0 : data;
data = (data * 10) + (str[i] - 48);
continue;
}