Question

C++ Stack Program Write a program that uses stacks to evaluate an arithmetic expression in infix...

C++ Stack Program

Write a program that uses stacks to evaluate an arithmetic expression in infix notation. The program should NOT convert the infix to postfix and then evaluate the postfix.

The program takes as input a numeric expression in infix notation, such as 3+4*2, and outputs the result.

1a)   Operators are +, -, *, /

1b) Assume that the expression is formed correctly so that each operation has two arguments.

1c) The expression can have parenthesis, for example: 3*(4-2)+6

1d) The expression can have negative numbers.

1e) The expression can have spaces in it, for example: 3 * (4-2) +6

Here are some useful functions that you may need:

               char cin.peek(); -- returns the next character of the cin input stream ( without reading it)

               bool isdigit(char c); -- returns true if c is one of the digits ‘0’ through ‘9’, false otherwise

               cin.ignore(); -- reads and discards the next character from the cin input stream

               cin.get(char &c); -- reads a character in c ( could be a space or the new line )

Test your program with a variety of arithmetic expressions.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <bits/stdc++.h>

using namespace std;

// Function to find precedence of

// operators.

int precedence(char op){

    if(op == '+'||op == '-')

    return 1;

    if(op == '*'||op == '/')

    return 2;

    return 0;

}

// Function to perform arithmetic operations.

int applyOp(int a, int b, char op){

    switch(op){

        case '+': return a + b;

        case '-': return a - b;

        case '*': return a * b;

        case '/': return a / b;

    }

    return 0;

}

// Function that returns value of

// expression after evaluation.

int evaluate(string input){

    int i;

    

    // stack to store integer values.

    stack <int> values;

    

    // stack to store operators.

    stack <char> ops;

    char prev='#';

    for(i = 0; i < input.length(); i++){

        

        // Current token is a whitespace,

        // skip it.

        if(input[i] == ' ')

            continue;

        

        // Current token is an opening

        // brace, push it to 'ops'

        else if(input[i] == '('){

            prev='(';

            ops.push(input[i]);

        }

        

        // Current token is a number, push

        // it to stack for numbers.

        else if(isdigit(input[i])){

            prev='1';

            int val = 0;

            

            // There may be more than one

            // digits in number.

            while(i < input.length() &&

                        isdigit(input[i]))

            {

                val = (val*10) + (input[i]-'0');

                i++;

            }

            i--;

            values.push(val);

        }

        

        // Closing brace encountered, solve

        // entire brace.

        else if(input[i] == ')')

        {

            prev=')';

            while(!ops.empty() && ops.top() != '(')

            {

                int val2 = values.top();

                values.pop();

                

                int val1 = values.top();

                values.pop();

                

                char op = ops.top();

                ops.pop();

                

                values.push(applyOp(val1, val2, op));

            }

            

            // pop opening brace.

            if(!ops.empty())

            ops.pop();

        }

        // if starting number is negative

        else if(input[i]=='-' && prev=='#')   {

             int num=-1;

             i++;

             int val = 0;

            

            // There may be more than one

            // digits in number.

            while(i < input.length() &&

                        isdigit(input[i]))

            {

                val = (val*10) + (input[i]-'0');

                i++;

            }

            i--;

            val=val*num;

            

            values.push(val);

        }

        // starting number after an opening bracket is negative

        else if(input[i]=='-' && prev=='(')   {

               int num=-1;

             i++;

             int val = 0;

            

            // There may be more than one

            // digits in number.

            while(i < input.length() &&

                        isdigit(input[i]))

            {

                val = (val*10) + (input[i]-'0');

                i++;

            }

            i--;

            val=val*num;

            values.push(val);

        }

        // if number after an operator is negative

        else if(input[i]=='-' && (prev=='-' || prev=='+' || prev=='*' || prev=='/'))  {

                   int num=-1;

             i++;

             int val = 0;

            

            // There may be more than one

            // digits in number.

            while(i < input.length() &&

                        isdigit(input[i]))

            {

                val = (val*10) + (input[i]-'0');

                i++;

            }

            i--;

            val=val*num;

            values.push(val);

        }

        // Current token is an operator.

        else

        {

            // While top of 'ops' has same or greater

            // precedence to current token, which

            // is an operator. Apply operator on top

            // of 'ops' to top two elements in values stack.

            if(input[i]=='-')  prev='-';

            if(input[i]=='+')  prev='+';

            if(input[i]=='*')  prev='*';

            if(input[i]=='/') prev='/';

            while(!ops.empty() && precedence(ops.top())

                                >= precedence(input[i])){

                int val2 = values.top();

                values.pop();

                

                int val1 = values.top();

                values.pop();

                

                char op = ops.top();

                ops.pop();

                

                values.push(applyOp(val1, val2, op));

            }

            

            // Push current token to 'ops'.

            ops.push(input[i]);

        }

    }

    

    // Entire expression has been parsed at this

    // point, apply remaining ops to remaining

    // values.

    while(!ops.empty()){

        int val2 = values.top();

        values.pop();

                

        int val1 = values.top();

        values.pop();

                

        char op = ops.top();

        ops.pop();

              

        values.push(applyOp(val1, val2, op));

    }

    

    // Top of 'values' contains result, return it.

    return values.top();

}

int main() {

    string input;

    getline(cin,input);

    cout << evaluate(input) << "\n";

    return 0;

}

Add a comment
Know the answer?
Add Answer to:
C++ Stack Program Write a program that uses stacks to evaluate an arithmetic expression in infix...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program in c++ to convert an expression written in infix notation to be converted...

    Write a program in c++ to convert an expression written in infix notation to be converted to postfix notation. The program must do the following: a. Read a string of characters representing an expression in infix notation. The '$' is to be added at the end of the string to mark its ending. Each character is a letter, digit, +,-,*, or /. If a character is any other character an error must be signaled and the program is terminated b....

  • Using Java- Write a program that takes an arithmetic expression in an infix form, converts it...

    Using Java- Write a program that takes an arithmetic expression in an infix form, converts it to a postfix form and then evaluates it. Use linked lists for the infix and postfix queues and the operator and value stacks. You must use sperate Stack and Queue classes with a driver class to run the program. example Input : 111++ Output : (1+ (1+ 1)) Answer: 3

  • Write a program to convert an expression written in infix notation to be converted to postfix...

    Write a program to convert an expression written in infix notation to be converted to postfix notation. The program must do the following: a. Read a string of characters representing an expression in infix notation. The '$' is to be added at the end of the string to mark its ending. Each character is a letter, digit, +,-,*, or /. If a character is any other character an error must be signaled and the program is terminated b. Use stacks...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are...

    We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are written in-between the operands). In a computer’s language, however, it is preferred to have the operators on the right side of the operands, i.e. 5 2 +. For more complex expressions that include parenthesis and multiple operators, a compiler has to convert the expression into postfix first and then evaluate the resulting postfix. Write a program that takes an “infix” expression as input, uses...

  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • Write a java program for the following: Your program reads an infix expression represented by a...

    Write a java program for the following: Your program reads an infix expression represented by a string S from the standard input (the keyboard). Then your program converts the infix expression into a postfix expression P using the algorithm. Next, your program evaluates the postfix expression P to produce a single result R. At last, your program displays the original infix expression S, the corresponding postfix expression P and the final result R on the standard output ( the screen...

  • Total point: 15 Introduction: For this assignment you have to write a c program that will...

    Total point: 15 Introduction: For this assignment you have to write a c program that will take an infix expression as input and display the postfix expression of the input. After converting the postfix expression, the program should evaluate the expression from the postfix and display the result. What should you submit? Write all the code in a single file and upload the .c file. Problem We as humans write math expression in infix notation, e.g. 5 + 2 (the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT