Question

//C++ Problem description In this problem, we consider expressions containing brackets that are properly nested. These...

//C++

Problem description

In this problem, we consider expressions containing brackets that are properly nested. These expressions are obtained by juxtaposition of properly nested expressions in a pair of matching brackets, the left one an opening and the right one a closing bracket.

( a + $ ( b = ) ( a ) )         is properly nested
( a + $ ) b = ) ( a ( )         is not

In this problem we have several pairs of brackets, so we have to impose a second condition on the expression: the matching brackets should be of the same kind. Consequently '(())' is okay, but '([))' is not. The pairs of brackets are:

(       )
[       ]
{       }
<    >
(*      *)

The two characters '(*' should be interpreted as one symbol, not as an opening bracket '(' followed immediately by an asterisk, and similarly for '*)'.

Write a C++ program that checks whether expressions are properly nested. If the expression is not properly nested, your program should determine the position of the offending bracket, that is the length of the shortest prefix of the expression that can not be extended to a properly nested expression. Don't forget '(*' counts as one, as does '*)'. the characters that are not brackets also count as one.

I expect you to make full use of the STL in your solution to this problem (i.e., your first choice should be to make use of existing functionality provided by the STL). Hint: the std::stack template class is handy.

This program should be fully documented (as required by the syllabus) and neatly and consistently formatted. Grading on these will be strictly enforced.

Input specification

The input is read from the standard input stream. Each line contains an expression to be checked followed by an end-of-line marker. No line contains more than 3000 characters. The input ends with a standard end-of-file marker.

Output specification

The output is written to the standard output stream. Each line contains the result of the check of the corresponding input line, that is 'YES' (in upper case), if the expression is okay, and 'NO' (in upper case) if the expression is not okay. This is followed by a space and the position of the error.

Sample input

(*a++(*)
(*a{+}*)

Sample output

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


Find the code for the above question below, read the comments provided in the code for better understanding. If found helpful please do upvote this.
Please refer to the screenshot of the code to understand the indentation of the code.

Copyable Code

#include <iostream> //standard c++ header file

#include <stack>    //for stack operations

using namespace std;

//this method returns a positive integer if error is found

//else a negative number -1

int BalanceCheck(string exp)

{

    //stack to hold the brackets

    stack<char> s;

    char x;

    int last_brack=-1;//to store the index of last opening bracket

    //loop through the expression

    for (int i = 0; i < exp.length(); i++)

    {

        //if the current elemenet is a opening bracket

        //push it into the stack

        if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{')

        {

            s.push(exp[i]);

            last_brack=i;

            continue;

        }

        //if the current element is  closing bracket

        switch (exp[i])

        {

            //if the element is closing bracket the  get the top of stack and

            //match it

        case ')':

            x = s.top();

            s.pop();

            if (x == '{' || x == '[')

                return last_brack;

            break;

        case '}':

            x = s.top();

            s.pop();

            if (x == '(' || x == '[')

                return last_brack;

            break;

        case ']':

            x = s.top();

            s.pop();

            if (x == '(' || x == '{')

                return last_brack;

            break;

        }

    }

    //if the stack is empty

    if (s.empty())

        return -1;

    else

        return last_brack;

}

//main driver code of the porgram

int main()

{

    string exp = "(*a++(*)";

    //call method to check balanced or not

    int ind = BalanceCheck(exp);

    //if value returned is negative then it's balanced else not

    if(ind>=0){

        //ind +1 because array indexing starts from 0

        cout<<"NO "<<ind+1<<"\n";

    }

    else

        cout<<"YES\n";

    return 0;

}

Screenshot

char x; { 1 #include <iostream> //standard c++ header file 2 #include <stack> //for stack operations 3 4 using namespace std;

Output

NO 6

Add a comment
Know the answer?
Add Answer to:
//C++ Problem description In this problem, we consider expressions containing brackets that are properly nested. These...
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 C++ program that reads string expressions from an input file "prefix.txt" containing prefix expressions...

    Write a C++ program that reads string expressions from an input file "prefix.txt" containing prefix expressions (one expression per input line). For each prefix expression read from the input file, the program should: (1) convert the expression to a fully parenthesized infix expression and (2) find the value of the expression. Use a stack to solve the problem. Assume the expressions contain only integer numbers and the *,/, +, - operators. Generate the results in an output file "results.txt" in...

  • Drawing Characters C++ Problem Description Annie is trying to draw character lines that she would like...

    Drawing Characters C++ Problem Description Annie is trying to draw character lines that she would like to use as decorations in her text messages to her friends. She has a list of integer and character pairs that she uses as basis for drawing out the lines. Write a program that will help her accomplish the task more quickly. Input Format The input begins with an integer N indicating the number of integer and character pairs that follows. The succeeding lines...

  • Drawing Characters C++ (NOT ALLOW ARRAY AND STRING) Problem Description Annie is trying to draw character...

    Drawing Characters C++ (NOT ALLOW ARRAY AND STRING) Problem Description Annie is trying to draw character lines that she would like to use as decorations in her text messages to her friends. She has a list of integer and character pairs that she uses as basis for drawing out the lines. Write a program that will help her accomplish the task more quickly. Input Format The input begins with an integer N indicating the number of integer and character pairs...

  • IMPLEMENT IN C++ Implement a symbol balance checker function for the Pascal programming language. Pascal allows...

    IMPLEMENT IN C++ Implement a symbol balance checker function for the Pascal programming language. Pascal allows for the following pairs: {}, (), [], begin end . All programs will begin with the word "begin" and end with the word "end". Your function should receive an ifstream object which is already open and will return true, all of the symbols match, or false, they do not. You do not have to worry about comments in the program but you do have...

  • C++ HTML files use tags enclosed in angle brackets to denote formatting instructions. For ex- ample,...

    C++ HTML files use tags enclosed in angle brackets to denote formatting instructions. For ex- ample, indicates bold, indicates italics, etc. If a web browser is displaying an HTML document that contains ‘<’ or ‘>’ then it may mistake these symbols for tags. This is a common problem with C++ files, which contain many <’s and >’s. For example, the line “#include ” may result in the browser interpreting as a tag. To avoid this problem, HTML uses special symbols...

  • For this project you will implement a simple calculator. Your calculator is going to parse infix...

    For this project you will implement a simple calculator. Your calculator is going to parse infix algebraic expressions, create the corresponding postfix expressions and then evaluate the postfix expressions. The operators it recognizes are: +, -, * and /. The operands are integers. Your program will either evaluate individual expressions or read from an input file that contains a sequence of infix expressions (one expression per line). When reading from an input file, the output will consist of two files:...

  • C++Language: The question is not allowed to use STL. Also, plz use noskipws and push_back for the question.The input is...

    C++Language: The question is not allowed to use STL. Also, plz use noskipws and push_back for the question.The input is more than one, so the code should be able to run more than once Strings are vectors words on that line and the line itself. What's a word? It is a series of alphabetic characters, separated by whitespace other non-alphabetic characters. Write a program that reads from cin and tor each line, outputs number Pretty easy huh, well, you aren't...

  • The goal is to create a code for implementing a Columns game using pygame Your program...

    The goal is to create a code for implementing a Columns game using pygame Your program will read its input via the Python shell (i.e., using the built-in input() function), printing no prompts to a user with no extraneous output other than precisely what is specified below. The intent here is not to write a user-friendly user interface; what you're actually doing is building a tool for testing your game mechanics, which we'll then be using to automatically test them....

  • Read Section 6.1.5 (p.235) on the Parenthesis Matching problem. They gave 5 examples: the first t...

    Please help with this. The hint refers to the attached picture. Read Section 6.1.5 (p.235) on the Parenthesis Matching problem. They gave 5 examples: the first two are " correct", and the remaining 3 "incorrect". Notice that the last one is actually "fixable". You just have to append the string")" to the input to get a properly matched expression! Here is another example: the string (O[(is incorrect, but is fixable if you append )]) Thus we want to classify the...

  • C++ Write a program that asks for a number and then prints as many lines as...

    C++ Write a program that asks for a number and then prints as many lines as the user inputs. Each line contains as many pairs of characters ("*#") as the number of this line. It should look like the right half of a pyramid. Your version of the program must print the same result as the expected output. To to this lab, you must use two do-while loops. Two exceptions: When the user inputs a number less than 1, then...

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