In: Computer Science
Consider the following code. Explain what this code does and determine the output. Let us discuss.
#include <iostream>
using namespace std;
int top;
void check (char str[ ], int n, char stack [ ])
{
for(int i = 0 ; i < n ; i++ )
{
if (str [ i ] == ‘(’)
{
top = top + 1;
stack[ top ] = ‘ ( ’;
}
if(str[ i ] == ‘)’ )
{
if(top == -1 )
{
top = top -1 ;
break ;
}
else
{
top = top -1 ;
}
}
}
if(top == -1)
cout << “String is balanced!” << endl;
else
cout << “String is unbalanced!” << endl ;
}
int main ( )
{
char str[ ] = { ‘(‘ , ‘a’ , ‘+’, ‘ ( ’, ‘b ’ , ‘-’ , ‘ c’ ,‘)’ , ‘
) ’} ;
char str1 [ ] = { ‘(’ , ‘(’ , ‘a’ , ‘ + ’ , ‘ b’ , ‘)’ } ;
char stack [ 15 ] ;
top = -1;
check (str , 9 , stack ); //Passing balanced string
top = -1 ;
check(str1 , 5 , stack) ; //Passing unbalanced string
}

/*
In the provide code the code checks the given expression is
balanced or not. for this
here we are using a check function that identifies the expression
and give the proper
output. for this in function check. we are using stack array as a
stack for push the braces {[()]} for operation
and if the braces come in expression then it will go to stack. if
the operator comes +-/*then
it will pop the expression and match from another stack symbol. and
finally it tells us .. it is
balanced or not
*/
#include <iostream>
using namespace std;
int top;
void check (char str[ ], int n, char stack [ ])
{
for(int i = 0 ; i < n ; i++ )
{
if (str [ i ] == '(')
{
top = top + 1;
stack[ top ] = ' ( ';
}
if(str[ i ] == ')' )
{
if(top == -1 )
{
top = top -1 ;
break ;
}
else
{
top = top -1 ;
}
}
}
if(top == -1)
cout << "String is balanced!" << endl;
else
cout << "String is unbalanced!" << endl ;
}
int main ( )
{
char str[ ] = { '(' , 'a' , '+', ' ( ', 'b ' , '-' , ' c' ,')' , ' ) '} ;
char str1 [ ] = { '(' , '(' , 'a' , ' + ' , ' b' , ')' } ;
char stack [ 15 ] ;
top = -1;
check (str , 9 , stack ); //Passing balanced string
top = -1 ;
check(str1 , 5 , stack) ; //Passing unbalanced string
}