Open In App

Algorithms Quiz | SP Contest 3 | Question 10

Like Article
Like
Save
Share
Report

Given below is a C++ function to evaluate a postfix expression represented as a string. The below code contains proper comments and some statements are marked specially. Find the statements which will lead to incorrect output.




// C++ function to evaluate a given postfix expression
int evaluatePostfix(char* exp)
{
    // Create a stack of capacity equal to expression size
    stack<int> st;
    int i;
   
    // Scan all characters one by one
    for (i = 0; exp[i]; ++i)
    {
        // If the scanned character is an operand (number here),
        // push it to the stack.
        // The isdigit() function is used to check if a particular 
        // character in the given input string is a digit or not.
        if (isdigit(exp[i]))
            st.push(exp[i]);    // Statement 1
   
        //  If the scanned character is an operator, pop two
        // elements from stack apply the operator
        else
        {
            int val1 = st.top();    // Statement 2
            st.pop();
            int val2 = st.top();
            st.pop();
              
            switch (exp[i])        // Statement 3            
            {
             case '+': st.push(val2 + val1); break;
             case '-': st.push(val2 - val1); break;
             case '*': st.push(val2 * val1); break;
             case '/': st.push(val2/val1);   break;
            }
        }
    }
      
    return st.top();
}


(A) Statement 2
(B) Statement 1
(C) Statement 3 & Statement 1
(D) None of the above


Answer: (B)

Explanation: https://www.geeksforgeeks.org/stack-set-4-evaluation-postfix-expression/

Quiz of this Question



Last Updated : 25 Jul, 2018
Like Article
Save Article
Share your thoughts in the comments
Similar Reads