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 :
[code lang=”c”]
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string in; //in=input expression
cout<<"Enter the Expression : ";
cin>>in;
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++)
{
if(in[k]=='(‘)
{
rop[ro]=k;
ro++;
continue;
}
else if((in[k]==’)’)&&(ro!=0))
{
ro–;
continue;
}
else if(in[k]==’)’)
{
rcp[rc]=k;
rc++;
continue;
}
}
//the following two for loops replaces unbalanced parenthese indexes with ‘#’
for(int i=0;i<ro;i++)
{
in[rop[i]]=’#’;
}
for(int i=0;i<rc;i++)
{
in[rcp[i]]=’#’;
}
cout<<"Balanced Expression : ";
//the following for loop will print the balanced parentheses
for(int i=0;i<n;i++)
{
if(in[i]!=’#’)
{
cout<<in[i];
}
}
return 0;
}
[/code]