Answer to Question #235783 in C++ for Jorden

Question #235783
declare a character stack
while ( more input is available)
{
read a character
if ( the character is a '(' )
push it on the stack
else if ( the character is a ')' and the stack is not empty )
pop a character off the stack
else
print "unbalanced" and exit
}
print "balanced
write c++ code for the above
1
Expert's answer
2021-09-12T11:54:16-0400


#include <iostream>
#include<stack>
using namespace std;
 


bool checkingBrackets(string expression)
{ 
    stack<char> str;
    char k;
 
   
    for (int n = 0; n < expression.length(); n++)
    {
        if (expression[n] == '(' || expression[n] == '['
            || expression[n] == '{')
        {
            
            str.push(expression[n]);
            continue;
        }
 
        
        if (str.empty())
            return false;
 
        switch (expression[n]) {
        case ')':
             
           
            k = str.top();
            str.pop();
            if (k == '{' || k == '[')
                return false;
            break;
 
        case '}':
 
          
            k = str.top();
            str.pop();
            if (k == '(' || k == '[')
                return false;
            break;
 
        case ']':
 
            
            k = str.top();
            str.pop();
            if (k == '(' || k == '{')
                return false;
            break;
        }
    }
 
    
    return (str.empty());
}
 
// Testing code
int main()
{
    string expression = "{()}[]";
 
    
    if (checkingBrackets(expression))
        cout << "Balanced";
    else
        cout << "Not Balanced";
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS