# checks the well formness of the parentheses

Discussion in 'C' started by JamesBond, Oct 15, 2006.

1. ### JamesBondNew Member

Joined:
Oct 15, 2006
Messages:
3
1
Trophy Points:
0

### Introduction

The idea is simple just to test whether the expression contains correct sequence of brackets or not.

Code:
```void main()
{
char arr[N];
char *top;
int loop=0,i,l,binary;

printf("Enter expression of brackets for checking its correctness\n");

gets(arr);

top=stack;
l=strlen(arr);

for(i=0;i<l;i++)
{
if(arr[i]=='('||arr[i]=='['||arr[i]=='{')
binary=push(&top,arr[i],&loop);		/**  Returns 0 if incorrect  **/
else if(arr[i]==')'||arr[i]==']'||arr[i]=='}')
binary=pop(&top,arr[i],&loop);		/***  Returns 1 if correct  ***/
if(binary==0)
break;
}

if(top==stack && binary==1)
{
printf("YES. The above expression is Correct\n");
}
else
{
printf("NO. The above expression is Incorrect\n");
}
}
```

### How it is done

Using stack. Just push "{", "[", "(" when found and pop when the closing one is found. Remember while popping you match into the stack content to have the same pair of closing and opening.

### The helper functions

The push Function
Code:
```int push(char **top,char arr,int *loop)     /** PUSH FUNCTION **/
{
if(*loop==N)		/**  loop is must for this checking  **/
return(0);
else
{
(*loop)++;
**top=arr;
(*top)++;
return(1);
}
}
```
The Pop Function
Code:
```int pop(char **top,char arr,int *loop)      /** POP FUNCTION **/
{
if(*loop==0)
return(0);
switch(arr)
{
case ')':
arr='(';
break;
case '}':
arr='{';
break;
case ']':
arr='[';
break;
}
(*top)--;		/**  For checking that the same bracket is closed  **/
if(**top!=arr)
return(0);
else
{
(*loop)--;
return(1);
}
}
```
Note : See the switch case in the pop to gurantee the pairing of braces / brackets

2. ### aisha.ansari84New Member

Joined:
Feb 13, 2008
Messages:
82
1
Trophy Points:
0
i didnt get you

Joined:
Feb 13, 2008
Messages:
103