Friday, October 19, 2018

C program using stack to check whether given expression is well parenthesized or not.

/*
In any language program mostly syntax error occurs due to unbalancing delimiter such as
(),{},[]. Write C program using stack to check whether given expression is well
parenthesized or not.
*/
#include<stdio.h>
# define size 10
int stack[size];
int top=-1;
char ans;
char pop()
{
    char var;
    if(top==-1)
    {
        printf("\nUnderflow");
        return 0;
    }
    else
    {
        var=stack[top];
        top--;
        return var;
    }
}
    void push(char var)
    {
        if(top+1==size)
        printf("\nOverflow");
        else
        {
            top++;
            stack[top]=var;
        }
    }
    char getval(char input)
    {
        switch(input)
        {
            case '[':
                    return']';
               case '(':
                    return')';
            case '{':
                    return'}';
        }
    }
    int main()
    {
        int i=0;
        char input[20];
        printf("\nEnter the operation: ");
        scanf("%s",input);
        for(i=0;input[i]!='\0';i++)
        {
            if(input[i]=='['||input[i]=='('||input[i]=='{')
            {
                push(input[i]);
            }
            if(input[i]==']'||input[i]==')'||input[i]=='}')
            {
                ans=pop();
           
                if(getval(ans)!=input[i])
                {
                    printf("\nFail\n");
                    return 0;
                }
            }
        }
        if(top==-1)
        {
            printf("\nPass\n");
        }
        else
        {
            printf("\nFail\n");
        }
            return 0;
}
/*
output-
Enter the operation: (A+B)-(A*B}   

Fail
*/


No comments:

Post a Comment