Question

In: Computer Science

: In this assignment you will write a C++ program that evaluates an arithmetic expression (represented...

: In this assignment you will write a C++ program that evaluates an arithmetic expression (represented with an infix notation), then outputs this expression in prefix form and also outputs the result of the calculation. The program will first convert the input infix expression to a prefix expression (using the Stack ADT) and then calculate the result (again, using the Stack ADT). The details are provided in the following sections.

Solutions

Expert Solution

The code below will convert an infix expression to postfix and evaluate the postfix expression.

To convert an infix to prefix the following steps will takes place;

1) Reverse the infix expression i.e A+B*C will become C*B+A. Note while reversing each ‘(‘ will become ‘)’ and each ‘)’   becomes ‘(‘.

2) Obtain the postfix expression of the modified expression i.e CB*A+.

3) Reverse the postfix expression. Hence in the example prefix is +A*BC.

The code below will convert a infix to prefix and evaluate the prefix:

Try this code with any other expressions, Note that only enter single digit expressions(0.....9).

//program to convert infix to prefix and evaluate prefix 
#include <bits/stdc++.h> 
using namespace std; 

//function to checking for operator
bool isOperator(char c) 
{ 
        return (!isalpha(c) && !isdigit(c)); 
} 

//function to get the priority between operators
int getPriority(char C) 
{ 
        if (C == '-' || C == '+') 
                return 1; 
        else if (C == '*' || C == '/') 
                return 2; 
        else if (C == '^') 
                return 3; 
        return 0; 
} 

//function for converting infix to postfix
string infixToPostfix(string infix) 
{ 
        infix = '(' + infix + ')'; 
        int l = infix.size(); 
        stack<char> char_stack; 
        string output; 

        for (int i = 0; i < l; i++) { 
                // If the scanned character is an operand, add it to output
                if (isalpha(infix[i]) || isdigit(infix[i])) 
                        output += infix[i]; 

                // If the scanned character is an ‘(‘, push it to the stack
                else if (infix[i] == '(') 
                        char_stack.push('('); 

                // If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered. 
                else if (infix[i] == ')') { 
                        while (char_stack.top() != '(') { 
                                output += char_stack.top(); 
                                char_stack.pop(); 
                        } 
                        // Remove '(' from the stack 
                        char_stack.pop(); 
                } 

                // Operator found 
                else { 
                        if (isOperator(char_stack.top())) { 
                                while (getPriority(infix[i]) 
                                <= getPriority(char_stack.top())) { 
                                        output += char_stack.top(); 
                                        char_stack.pop(); 
                                } 
                                // Push current Operator on stack 
                                char_stack.push(infix[i]); 
                        } 
                } 
        } 
        return output; 
} 

string infixToPrefix(string infix) 
{ 
        int l = infix.size(); 
        // Reverse infix 
        reverse(infix.begin(), infix.end()); 
        // Replace ( with ) and vice versa 
        for (int i = 0; i < l; i++) { 
                if (infix[i] == '(') { 
                        infix[i] = ')'; 
                        i++; 
                } 
                else if (infix[i] == ')') { 
                        infix[i] = '('; 
                        i++; 
                } 
        } 
    //get postfix
        string prefix = infixToPostfix(infix); 
        // Reverse postfix 
        reverse(prefix.begin(), prefix.end()); 

        return prefix; 
} 

/**Evaluation of Prefix **/
bool isOperand(char c) 
{ 
    // If the character is a digit then it must be an operand 
    return isdigit(c); 
} 
  
double evaluatePrefix(string exprsn) 
{ 
    stack<double> Stack; 
    for (int j = exprsn.size() - 1; j >= 0; j--) { 
        // Push operand to Stack 
        if (isOperand(exprsn[j])) 
        // To convert exprsn[j] to digit subtract '0' from exprsn[j].
            Stack.push(exprsn[j] - '0'); 
  
        else { 
            // Operator encountered; Pop two elements from Stack 
            double o1 = Stack.top(); 
            Stack.pop(); 
            double o2 = Stack.top(); 
            Stack.pop(); 
  
            // Use switch case to operate on o1 and o2 and perform o1 O o2. 
            switch (exprsn[j]) { 
            case '+': 
                Stack.push(o1 + o2); 
                break; 
            case '-': 
                Stack.push(o1 - o2); 
                break; 
            case '*': 
                Stack.push(o1 * o2); 
                break; 
            case '/': 
                Stack.push(o1 / o2); 
                break; 
            } 
        } 
    } 
    return Stack.top(); 
} 

// main code 
int main() 
{ 
    //string to store expression(infix)
        string s = ("9*8-4");
        string p;     //string to store expression(prefix)
        cout << "Orginal Expression: " << s << std::endl;
        p = infixToPrefix(s);    //calling infix to prefix convert
        cout << "Prefix Notation: " <<p << std::endl;
        //calling prefix evaluation and printing reusult
        cout << "Evaluation result of prefix: " << evaluatePrefix(p) << std::endl; 
        return 0; 
} 

OUTPUT:


Related Solutions

write a program that evaluates the following arithmetic expression: ((A+B)/C)*((D-A)+E). Assign test values to the variables...
write a program that evaluates the following arithmetic expression: ((A+B)/C)*((D-A)+E). Assign test values to the variables and display the resulting value.
Write a program (preferably in Java) that, given an arithmetic expression, first transforms it to a...
Write a program (preferably in Java) that, given an arithmetic expression, first transforms it to a postfix form, and then computes its value (by using stack-based algorithms). Assume that all the numbers in the arithmetic expression are one-digit numbers, i.e., each of these numbers is either 0, or 1, or 2, ..., or 9. For example, your program should correctly process expressions like 2+3*4, but there is no need to process expressions like 11+22.
Write an ASM program that evaluates the following expression, using variables: Z = (-A - B)...
Write an ASM program that evaluates the following expression, using variables: Z = (-A - B) - (-C - D) 1. Declare and initialize the memory variable A to 32-bit signed integer value 543210 and variable B to 16-bit signed integer value -3210. 2. Declare the memory variables C and D and read in their values from the keyboard as 32-bit signed integer value 43210 and 8-bit signed integer values -10, respectively. a. You should display a message asking for...
Write a C++ function that takes in an arithmetic expression in prefix notation and converts it...
Write a C++ function that takes in an arithmetic expression in prefix notation and converts it into a binary tree, such that each operation is stored in a node whose left subtree stores the left operand, and whose right subtree stores the right operand.
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
Write a program that performs the following two tasks in java Reads an arithmetic expression in...
Write a program that performs the following two tasks in java Reads an arithmetic expression in an infix form, stores it in a queue (infix queue) and converts it to a postfix form (saved in a postfix queue). Evaluates the postfix expression. Use linked lists to implement the Queue and Stack ADTs. DO NOT USE BUILT IN JAVA CLASSES
In C++ For this assignment, you will write a program to count the number of times...
In C++ For this assignment, you will write a program to count the number of times the words in an input text file occur. The WordCount Structure Define a C++ struct called WordCount that contains the following data members: An array of 31 characters named word An integer named count Functions Write the following functions: int main(int argc, char* argv[]) This function should declare an array of 200 WordCount objects and an integer numWords to track the number of array...
For this computer assignment, you are to write a C++ program to implement a class for...
For this computer assignment, you are to write a C++ program to implement a class for binary trees. To deal with variety of data types, implement this class as a template. Most of the public member functions of the BinaryTree class call private member functions of the class (with the same name). These private member functions can be implemented as either recursive or non-recursive, but clearly, recursive versions of these functions are preferable because of their short and simple implementations...
For this computer assignment, you are to write a C++ program to implement a class for...
For this computer assignment, you are to write a C++ program to implement a class for binary trees. To deal with variety of data types, implement this class as a template. Most of the public member functions of the BinaryTree class call private member functions of the class (with the same name). These private member functions can be implemented as either recursive or non-recursive, but clearly, recursive versions of these functions are preferable because of their short and simple implementations...
For this week’s lab assignment, you will write a program called lab9.c. You will write a...
For this week’s lab assignment, you will write a program called lab9.c. You will write a program so that it contains two functions, one for each conversion. The program will work the same way and will produce the same exact output. The two prototypes should be the following: int btod(int size, char inputBin[size]); int dtob(int inputDec); The algorithm for the main() function should be the following: 1. Declare needed variables 2. Prompt user to enter a binary number 3. Use...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT