shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
I have used 4 variables as follows
A=2, B=3, C=4, D=5
with the expression as AB+CD+* and I got the following
Code:
Enter the total number of variables you will use
4

Assign values to each of them

Assign value to A       2

Assign value to B       3

Assign value to C       4

Assign value to D       5

Enter a postfix expression using above variables
AB+CD+*
Result is 45
. I don't see any problem. Can you please clarify a bit more.
abdo's Avatar, Join Date: Sep 2007
Newbie Member
can you make this evaluates a postfix in java....
please cuz i saw it more easier for me to understand it.....
thank you
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
If you have understood it you should be able to convert it into any other language and then post it here for others to see.
keshaj's Avatar, Join Date: Jun 2007
Newbie Member
i need a progrm in this....InFix to PostFix and PostFix expression evaluation.....program in c.... i really need ur help..
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by keshaj
i need a progrm in this....InFix to PostFix and PostFix expression evaluation.....program in c.... i really need ur help..
Did you read the article content. If not you should and you will get what you are looking for.
bloom_star7's Avatar, Join Date: Sep 2007
Newbie Member
Shabbir,

In the 4th point you mentioed i think it should be operator not operand.

4.If the scanned character is an Operator[not Operand] and the stack is not empty, compare the precedence of the character with the element on top of the stack (topStack). If topStack has higher precedence over the scanned character Pop the stack else Push the scanned character to stack. Repeat this step as long as stack is not empty and topStack has precedence over the character.

May be i am wrong. Please let me konw if i missed something.
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Yes it should be Operator as the precedence of the operand does not mean anything. Thanks for pointing it out and I have corrected that in the main article.
abdo's Avatar, Join Date: Sep 2007
Newbie Member
i try to do this....i want to know if i use this program, is that correct?
Q:
How to write a java program taht evaluates a postfix expression by using concept of stack?
--------------------------------------------
Code:
public class PostfixEval 
{

   public static void main(String[] args) 
    {
      
      TextIO.putln("This program can evaluate postfix expressions such as\n");
      TextIO.putln("        2 2 +");
      TextIO.putln("or");
      TextIO.putln("        7.3 89.2 + 9 1.83 * 2 + /\n");
      TextIO.putln("The operators +, -, *, /, and ^ can be used.\n\n");
      
      while (true) 
        {
             // Get and process one line of input from the user.
        TextIO.putln("\n\n\nEnter a postfix expression or press return to end:\n");
        TextIO.put("? ");
        skipSpaces();
        if (TextIO.peek() == '\n') 
          {
               // If the line is empty (except for spaces), we are done.
            break;
        }
        readAndEvaluate(); // Process the input.
        TextIO.getln(); // Discard the end-of-line.
      }
      
      TextIO.putln("\n\nExiting program.");
      
   } // end main();
   
   
   static void skipSpaces() 
    {
        // Skip past any spaces and tabs on the current input line.
        // When this routine returns, the next character is either
        // the end-of-line character, '\n', or is a non-blank.
      while (TextIO.peek() == ' ' || TextIO.peek() == '\t') 
        {
        TextIO.getAnyChar();
      }
   }
   
   
   static void readAndEvaluate()
     {
        // Read one line of input and process it as a postfix expression.
        // If the input is not a legal postfix expression, then an error
        // message is displayed. Otherwise, the value of the expression
        // is displayed. It is assumed that the first character on
        // the input line is a non-blank. (This is checked in the
        // main() routine.)
       
      NumberStack stack; // For evaluating the expression.
      
      stack = new NumberStack(); // Make a new, empty stack.
      
      TextIO.putln();
      
      while (TextIO.peek() != '\n') 
        {
      
          if ( Character.isDigit(TextIO.peek()) ) 
             {
                  // The next item in input is a number. Read it and
                  // save it on the stack.
              double num = TextIO.getDouble();
              stack.push(num);
              TextIO.putln("   Pushed constant " + num);
          }
          else 
             {
                 // Since the next item is not a number, the only thing
                 // it can legally be is an operator. Get the operator
                 // and perform the operation.
              char op; // The operator, which must be +, -, *, /, or ^.
              double x,y;     // The operands, from the stack, for the operation.
              double answer; // The result, to be pushed onto the stack.
              op = TextIO.getChar();
              if (op != '+' && op != '-' && op != '*' && op != '/' && op != '^') 
                  {
                      // The character is not one of the acceptable operations.
                  TextIO.putln("\nIllegal operator found in input: " + op);
                  return;
              }
              if (stack.isEmpty()) 
                  {
                  TextIO.putln("   Stack is empty while trying to evaluate " + op);
                  TextIO.putln("\nNot enough numbers in expression!");
                  return;
              }
              y = stack.pop();
              if (stack.isEmpty()) 
                  {
                  TextIO.putln("   Stack is empty while trying to evaluate " + op);
                  TextIO.putln("\nNot enough numbers in expression!");
                  return;
              }
              x = stack.pop();
              switch (op) 
                  {
                 case '+': answer = x + y; break;
                 case '-': answer = x - y; break;
                 case '*': answer = x * y; break;
                 case '/': answer = x / y; break;
                 default:   answer = Math.pow(x,y); // (op must be '^'.)
              }
              stack.push(answer);
              TextIO.putln("   Evaluated " + op + " and pushed " + answer);
          }
          
          skipSpaces();
      
      } // end while
      
      // If we get to this point, the input has been read successfully.
      // If the expression was legal, then the value of the expression is
      // on the stack, and it is the only thing on the stack.
      
      if (stack.isEmpty()) 
        { // Impossible if the input is really non-empty.
          TextIO.putln("No expression provided.");
          return;
      }
       
      double value = stack.pop(); // Value of the expression.
      TextIO.putln("   Popped " + value + " at end of expression.");

      if (stack.isEmpty() == false) {
          TextIO.putln("   Stack is not empty.");
          TextIO.putln("\nNot enough operators for all the numbers!");
          return;
      }

      TextIO.putln("\nValue = " + value);
      
      
   } // end readAndEvaluate()


} // end class PostfixEval
-----------------------------------------------------------------------
Attached the question,i know for you is simple, but i really need your help...Thank you

Last edited by shabbir; 17Sep2007 at 09:19.. Reason: Code Block
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by abdo
Attached the question,i know for you is simple, but i really need your help...Thank you
You are posting Java question in a C-C++ article and I do not expect you would get any help relating to the same but anyway best of luck. You should have read Before you make a query ( Link in upper right corner ) for some better responses.

Now also about your query I think the code given in the article is simple enough for the Java programmer to convert it into Java but I am not a Java expert.
sarah24's Avatar, Join Date: Sep 2007
Newbie Member
i need some help pls help me...
i have written a code for postfix expression evaluation but what if all the data and expressions to be evaluated are in text file..
pls tell me how can i modify my code ..
Code:
#include <iostream>
#include <stack> 
#include <string>
using namespace std;

void main()
{
    int i, choice = 1;
    string postfixExp;
    char token;
    float value, value1, value2;
    stack<float> s; //Declare a stack of floats

   

    while (choice != 0)
    {
        cout << "1. Evaluate a postfix expression" << endl;
        cout << "0. Exit " << endl;
        cout << "Enter the number for the option: ";

        cin >> choice;
        switch(choice)
        {
            case 1: cout << "Evaluate a postfix expression\n";
                    cout << "Enter the expression: ";
                    cin >> postfixExp;
                    i = 0;
                    token = postfixExp[i];
                    while((i < postfixExp.size()) && (token != '='))
                    {
                        if(isdigit(token))
                        {
                            value = token - '0';
                            s.push(value);
                        }
                        else
                        {
                            value2 = s.top();
                            s.pop();
                            value1 = s.top();
                            s.pop();
                            switch(token)
                            {
                                case '+': value = value1 + value2;
                                          break;
                                case '-': value = value1 - value2;
                                          break;
                                case '*': value = value1*value2;
                                          break;
                                case '/': value = value1/value2;
                                          break;
                            }
                            s.push(value);
                        }
               i++;
               token = postfixExp[i];
                    }
                    value = s.top();
                    s.pop();
                    cout << postfixExp << " " << value << endl;         
                    break;

            case 0: cout << "Exiting the program\n";
                    break;

            default: cout << "Invalid option\n";
                    break;
        }
     cout << endl;
    }
}

Last edited by shabbir; 27Sep2007 at 21:56.. Reason: Code block