checks the well formness of the parentheses

JamesBond's Avatar author of checks the well formness of the parentheses
This is an article on checks the well formness of the parentheses in C.

Introduction



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

Code: C
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: C
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: C
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
aisha.ansari84's Avatar, Join Date: Feb 2008
Contributor
i didnt get you
rahul.mca2001's Avatar, Join Date: Feb 2008
Ambitious contributor
nie code