199k views
2 votes
Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid.

1 Answer

2 votes

Answer:

Step-by-step explanation:

The program is written in C++

/*

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] == '('

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\\";

}

User Lucidquiet
by
4.9k points