Check for balanced parentheses in an expression in C

Check for balanced parentheses in an expression in C
clear printing steps


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

struct Stack
{
    int top;
    int capacity;
    int* array;

};
struct Stack* createStack( int capacity )
{
    struct Stack* stack=(struct Stack*)malloc(sizeof(struct Stack));
    if(!stack)
    {
        return NULL;
    }
    stack->top=-1;
    stack->capacity=capacity;
    stack->array=(int*)malloc(sizeof(int)*stack->capacity);
    if(!stack->array)
        return NULL;

    return stack;
};
void push(struct Stack* stack, char op)
{
        stack->array[++stack->top]=op;
}
int isEmpty(struct Stack* stack)
{
    return stack->top == -1 ;
}
char pop(struct Stack* stack)
{
    if (!isEmpty(stack))
        return stack->array[stack->top--] ;
    return '$';
}

int check_if(char ob,char cb)
{
    if((ob=='(' && cb==')') || (ob=='{' && cb=='}') || (ob=='[' && cb==']') )
        {
            return 1;
        }
        else
        {
            return 0;
        }
}
void pranbal(char* exp)
{
    int i,j,sum;
    struct Stack* stack=createStack(strlen(exp));
    if(!stack)
        return -1;
    for(i=0;exp[i];i++)
    {
        if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[')
            {
                push(stack,exp[i]);
                printf("this %c is pushed\n",exp[i]);
            }
        if(exp[i]==')'|| exp[i]=='}' || exp[i]==']')
        {
            char ob=pop(stack);
            printf("the combo %c %c\n",ob,exp[i]);
            if(!check_if(ob,exp[i]))
            {
                printf("Unbalanced\n");
                exit(0);
            }
        }
    }
    if(isEmpty(stack))
    {
        printf("Balanced Parenthesis\n");
    }
    else
    {
        printf("Unbalanced Parenthesis\n");
    }
}

int main()
{
    char exp[100];
    printf("Enter the elements\n");
    scanf("%s",exp);
    pranbal(exp);
return 0;
}


No comments:

Post a Comment

All Repeated Words In Text File And Their Occurrences In Java

Find All Repeated Words In Text File And Their Occurrences In Java Place your file location in the argument of the FileReader. If t...