If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Below is a C++ implementation of the Parenthesis Matching program using a stack:
cppCopy code
#include <iostream> #include <stack> #include <string> bool isMatching(char open, char close) { return (open == '(' && close == ')') || (open == '[' && close == ']') || (open == '{' && close == '}'); } bool isBalanced(const std::string& expression) { std::stack<char> parenStack; for (char c : expression) { if (c == '(' || c == '[' || c == '{') { parenStack.push(c); } else if (c == ')' || c == ']' || c == '}') { if (parenStack.empty() || !isMatching(parenStack.top(), c)) { return false; // Not balanced } parenStack.pop(); } } return parenStack.empty(); } int main() { std::string expression; std::cout << "Enter an expression with parentheses: "; std::cin >> expression; if (isBalanced(expression)) { std::cout << "The expression is balanced." << std::endl; } else { std::cout << "The expression is not balanced." << std::endl; } return 0; }This program uses a stack to check if the given expression has balanced parentheses. The
isMatchingfunction checks if two parentheses characters match each other. TheisBalancedfunction iterates through each character in the expression, pushes opening parentheses onto the stack, and pops them when a corresponding closing parenthesis is encountered. If the stack is empty at the end, the expression is balanced; otherwise, it is not balanced.In the
mainfunction, the user is prompted to enter an expression with parentheses. The program then calls theisBalancedfunction to determine if the expression has balanced parentheses and prints the result accordingly.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support