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:-