Group
Data Structures: Stacks, Queues in C++
Objective
1. Write a program that takes an input string containing parentheses.
2. Use a stack to track the opening parentheses and match them with the closing parentheses.
3. If at the end of the string, the stack is empty, the parentheses are balanced; otherwise, they are not.
4. Output "Balanced" if the parentheses are balanced and "Not Balanced" otherwise.
Implement a stack that checks if the parentheses in a string are balanced.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for input/output operations
#include <stack> // Include for stack data structure
using namespace std;
// Function to check if the parentheses in a string are balanced
bool areParenthesesBalanced(string expr) {
stack<char> s; // Stack to keep track of opening parentheses
// Traverse through the string
for (int i = 0; i < expr.length(); i++) {
char c = expr[i];
// If the current character is an opening parenthesis, push it onto the stack
if (c == '(') {
s.push(c);
}
// If the current character is a closing parenthesis, check if it matches an opening one
else if (c == ')') {
// If the stack is empty, there is no matching opening parenthesis
if (s.empty()) {
return false;
}
s.pop(); // Pop the matching opening parenthesis from the stack
}
}
// If the stack is empty at the end, the parentheses are balanced
return s.empty();
}
// Main function
int main() {
string expression;
cout << "Enter an expression with parentheses: ";
getline(cin, expression); // Read the entire string input
// Check if the parentheses in the expression are balanced
if (areParenthesesBalanced(expression)) {
cout << "Balanced" << endl; // Output "Balanced" if the parentheses are balanced
} else {
cout << "Not Balanced" << endl; // Output "Not Balanced" if the parentheses are not balanced
}
return 0;
}
Output
Enter an expression with parentheses: (a+b)*(c-d)
Balanced