Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   checks the well formness of the parentheses (http://www.go4expert.com/articles/checks-formness-parentheses-t1631/)

JamesBond 15Oct2006 13:57

checks the well formness of the parentheses
 

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 5Mar2008 18:54

Re: checks the well formness of the parentheses
 
i didnt get you

rahul.mca2001 6Mar2008 13:15

Re: checks the well formness of the parentheses
 
nie code


All times are GMT +5.5. The time now is 21:59.