Program to Check the Balanced Parentheses in given Expression

Program to Check the Balanced Parentheses in given Expression

This program will Check for Balanced parentheses in the given Expression and Removes the Unbalanced Parentheses .

For a well balanced parentheses in a expression there should be no close parentheses at beginning and no open parentheses at the ending . Also inner parentheses should have their respective matching parentheses in correct order .

Input :

Output :

Logic To Check for Well Balanced Parentheses :

  • Get the Expression as a String From the user .
  • Using two integer array mark position of open parentheses in one array and closed parentheses in another array .
  • Store the index of open parenthese if open paranthese is found .
  • If a closed parenthese is found and open paranthese is already stored in the array remove the open paranthese index .
  • If a closed parenthese is found and no open paranthese is available in the array store the index .
  • Now the indexes of unbalanced parentheses are identified and their positions are marked with ‘#’ symbol .
  • Finally print the expression without printing ‘#’ which is the balanced expression .

Program :

using namespace std;
int main()
    string in;          //in=input expression
    cout<<"Enter the Expression : ";
    int n=in.size();    //expression count
    //ro,rc are used as indexes for rop,rcp
    int ro=0,rc=0;      //ro=remove_opened,rc=remove_closed
    //rop,rcp are int arrays
    int rop[n];         //rop=remove_opened_parantheses
    int rcp[n];         //rcp=remove_closed_parantheses

    //the following for loop finds the indexes of unbalanceed parantheses
    //and store in respective rop,rcp arrays.

    for(int k=0;k<n;k++)
        else if((in[k]==')')&&(ro!=0))
        else if(in[k]==')')

    //the following two for loops replaces unbalanced parenthese indexes with '#'

    for(int i=0;i<ro;i++)
    for(int i=0;i<rc;i++)
    cout<<"Balanced Expression : ";

    //the following for loop will print the balanced parentheses

    for(int i=0;i<n;i++)
    return 0;


A Programmer who have his programming skills on C,C++, Java and also interested in Android Development. He follows the famous quotes by Linus Torvalds ” Talk is cheap, Show me the code “ .

One thought on “Program to Check the Balanced Parentheses in given Expression

  1. I do not even know how I ended up here, but I thought this post was good.
    I don’t know who you are but definitely you’re going to a
    famous blogger if you are not already 😉 Cheers!

Leave a Reply

Your email address will not be published.

20 + 12 =