hi all
i have a question and plz i really need your help
the question is >>>>
A string of characters has balanced parenthesis if each right parentheses occurring in the string is matched with a preceding left parentheses in the same way each right brace in a C++ program is matched with a preceding left brace. Write a program that uses a stack to determine whether a string entered at the keyboard has balanced parentheses.
and this is what i did >>>>
Code:
#include <iostream>
#include <string.h>
using namespace std;
#define SIZE 100
char C1='(';
char C2=')';
class stack {
private:
char stackChar[SIZE]; // Holds the stack
int top;
public:
stack()
{ top= 0; }
void push(char ch)
{
if(top==SIZE)
{
cout << "Stack is FULL!!"<<endl;
}
stackChar[top] = ch;
top++;
}
char pop(char ch)
{
if(top==0)
{
cout << "Stack is EMPTY!!" <<endl;
return 0;
}
top--;
return stackChar[top];
}
bool balanced (char *ch, char s)
{
int count=0;
while(*ch!= '\0')
{
if(*ch==C1)
{
push(C1);
count++;
}
if(*ch==C2)
{
pop(C1);
count--;
}
}
if (count==0)
return true;
else
return false;
}
};
int main()
{
stack St;
char S1[SIZE]= "My name is (( lady bird ))";
char S2[SIZE]= "(Im (23) years old ))";
char *ch;
cin.getline(S1,SIZE);
if (St.balanced (ch, S1))
cout<<"The first string is balanced "<<endl;
else
cout<<"The first string is unbalanced "<<endl;
cin.getline(S2,SIZE);
if (St.balanced (ch, S2))
cout<<"The second string is balanced "<<endl;
else
cout<<"The second string is unbalanced "<<endl;
return 0;
}