How to write a c Program To Check The Order Of Opening And Closing Brackets?

How to write a c Program To Check The Order Of Opening And Closing Brackets?
eg- ((()()))
1.how to check whether this patter will be true or false ?

Keep a counter of opening brackets. Initialize it with 0. Increment every time you get a β€˜(’ and decrement and check for negative value every time you get a β€˜)’. If you never encounter a negative value and counter is zero after the sequence is scanned, it is valid, otherwise invalid.

1 Like

This is generally implemented using Stacks. The process goes as follows take a stack of characters. If you get a β€˜(’ insert the character to the Stack and if you get a β€˜)’ pop out one element from the stack. Go on doing the same approach for all the characters in the string. If at any point there is no character to pop from the stack or at last the stack is non empty then the string is invalid otherwise it’s valid.

4 Likes

like that ,
char b[]={"()()((()))()"}, sum=0;
for (int i=0;b[i]!=’\0’;i++)
{
if (b[i]==’(’)
sum++;
if (b[i]==’)’)
sum–;
if (sum<0)
break;
}

google it before posting your homework

1 Like

Looks fine