[go: up one dir, main page]

0% found this document useful (0 votes)
23 views2 pages

Check Balance and Imbalance Using Stack

The document contains a C++ program that checks if a string of expressions is balanced using a stack data structure. It defines a function 'isBalanced' that verifies matching parentheses, brackets, and braces. The program prompts the user to input an expression and outputs whether it is balanced or imbalanced.

Uploaded by

pranav1256kam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views2 pages

Check Balance and Imbalance Using Stack

The document contains a C++ program that checks if a string of expressions is balanced using a stack data structure. It defines a function 'isBalanced' that verifies matching parentheses, brackets, and braces. The program prompts the user to input an expression and outputs whether it is balanced or imbalanced.

Uploaded by

pranav1256kam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Name:-Pranav Kumar

Roll:-uem228120;
Check balance and imbalance using stack:-
#include <iostream>
#include <stack>
#include <string>
using namespace std;

// Function to check if a string of expressions is balanced


bool isBalanced(const string &expression)
{
stack<char> s;

for (char c : expression)


{
if (c == '(' || c == '{' || c == '[')
{
s.push(c);
}
else if (c == ')' || c == '}' || c == ']')
{
if (s.empty())
{
return false; // Unmatched closing parenthesis
}

char top = s.top();


s.pop();

if ((c == ')' && top != '(') ||


(c == '}' && top != '{') ||
(c == ']' && top != '['))
{
return false; // Mismatched parenthesis
}
}
}
return s.empty(); // Stack should be empty for a balanced
expression
}

int main()
{
string expression;

cout << "Enter an expression: ";


getline(cin, expression);

if (isBalanced(expression))
{
cout << "Expression is balanced." << endl;
}
else
{
cout << "Expression is imbalanced." << endl;
}

return 0;
}

Output:-

You might also like