C++ In code, every { must have a corresponding } Similarly, every [ must have a
ID: 3816786 • Letter: C
Question
C++
In code, every { must have a corresponding }
Similarly, every [ must have a corresponding ] and every ( must have a corresponding )
Furthermore, the symbols must be “appropriately closed” in the sense that they are closed in the reverse of the order that they are opened.
For example:
{[]} is a legal sequence
{[}] is NOT a legal sequence because the } was closed when the [ was the last character that was opened
[[]] is a legal sequence
[{}{}] is a legal sequence
{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}} is a legal sequence
{ is NOT a legal sequence because the { is never closed
Going further:
for(int i = 0; i < 10; i++){ cout << i; } is a legal sequence
And so on.
How do I write a program that reads in a .cpp file and determines if the {},[],() are legally sequenced?
Explanation / Answer
/*
C++ Program to check for balanced parentheses in an expression using stack.
Given an expression as string comprising of opening and closing characters
of parentheses - (), curly braces - {} and square brackets - [], we need to
check whether symbols are balanced or not.
*/
#include<iostream>
#include<stack>
#include<string>
using namespace std;
// Function to check whether two characters are opening
// and closing of same type.
bool ArePair(char opening,char closing)
{
if(opening == '(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '[' && closing == ']') return true;
return false;
}
bool AreParanthesesBalanced(string exp)
{
stack<char> S;
for(int i =0;i<exp.length();i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
S.push(exp[i]);
else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
if(S.empty() || !ArePair(S.top(),exp[i]))
return false;
else
S.pop();
}
}
return S.empty() ? true:false;
}
int main()
{
/*Code to test the function AreParanthesesBalanced*/
string expression;
cout<<"Enter an expression: "; // input expression from STDIN/Console
cin>>expression;
if(AreParanthesesBalanced(expression))
cout<<"Balanced ";
else
cout<<"Not Balanced ";
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.