#include <iostream>
#include <stack>
#include <string>
bool areParenthesesBalanced(const std::string& expression);
int main() {
std::string expression;
std::cout << "Enter an expression with parentheses: ";
std::cin >> expression;
if (areParenthesesBalanced(expression)) {
std::cout << "The parentheses are balanced." << std::endl;
} else {
std::cout << "The parentheses are not balanced." << std::endl;
}
return 0;
}
bool areParenthesesBalanced(const std::string& expression) {
std::stack<char> parenthesesStack;
for (char ch : expression) {
if (ch == '(' || ch == '[' || ch == '{') {
parenthesesStack.push(ch);
} else if (ch == ')' || ch == ']' || ch == '}') {
if (parenthesesStack.empty()) {
return false; // Unmatched closing parenthesis
}
char top = parenthesesStack.top();
parenthesesStack.pop();
if ((ch == ')' && top != '(') ||
(ch == ']' && top != '[') ||
(ch == '}' && top != '{')) {
return false; // Mismatched closing parenthesis
}
}
}
return parenthesesStack.empty(); // Check for any unmatched opening parenthesis
}