Check for balanced parentheses in an expression

    #include<stdio.h>

    struct stack
    {
        char arr[100];
        int top;
    };
    typedef struct stack stack;
    
    stack push(stack s,char ch)
    {
        s.arr[++(s.top)]=ch;
        return s;
    }
    
    char pop(stack *s)
    {
        return (*s).arr[((*s).top)--];
    }
    
    int compare(char ch1,char ch2)
    {
        if(ch1=='{' && ch2=='}')
           return 1;
        else
        if(ch1=='(' && ch2==')')
           return 1;
        else
        if(ch1=='[' && ch2==']')
           return 1;
        else
           return 0;
    }
    
    int main()
    {
        char exp[100];
        int i,flag=1;
    
        stack s;
        s.top=-1;
    
        printf("Enter any expresion :");
        scanf("%s",&exp);
    
        for(i=0;exp[i];i++)
        {
            if(exp[i]=='{' || exp[i]=='(' || exp[i]=='[')
            {
                s=push(s,exp[i]);
            }
            else
            if(exp[i]=='}' || exp[i]==')' || exp[i]== ']')
            {
               if(s.top==-1)
               {
                  flag=0;
                  break;
               }
               else
               if(!compare(pop(&s),exp[i]))
               {
                  flag=0;
                  break;
               }
            }
         }

         if(s.top!=-1)
         {
            flag=0;
         }
    
         if(flag)
             printf("\nBalanced Parentheses");
          else
             printf("\nUnbalanced Parentheses");
    
         return 0;
    }
Example :

Input :  [()]{}{[()()]()}
OutputBalanced Parentheses

Input[(])
Output :  Unbalanced Parentheses



No comments: