Balanced Parenthesis in C Programming Language

Balanced Parenthesis in C


I am trying to write a program where i implement stacks with arrays and use them to check if a given string has balanced parentheses.

For ex. if inputted '(()){}[()]' ,program would output 'Balanced', otherwise if inputted '({})[' the program would output 'Not balanced'.

This part is the array implementation of the stack.

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

#define MAX 50

int stack[MAX];
int top=-1;

void push(char val){
    if(top==MAX-1){
        printf("stack is already full,error\n");
    
    }else{
        top++;
        stack[top]=val;
    }
}

char pop(){
    if(top==-1){
        printf("not enough elements,error\n");
        exit(1);
    }else{
        top--;
        return stack[top];
    }
}

This part is the implementation of a common method to solve the problem.

int isMatching(char c1, char c2){ 
    if(c1=='{' && c2=='}') 
        return 1; 
        
    else if(c1 =='(' && c2==')') 
        return 1; 
        
    else if(c1=='[' && c2==']') 
        return 1; 
    
    return 0; 
} 

int isBalanced(char str[]){
    int i=0;
    
    while(str[i]!='\0'){
        if(str[i]=='{' || str[i]=='[' || str[i]=='('){
            push(str[i]);
        }
        if(str[i]==')' || str[i] == ']' || str[i]=='}'){ 
            if(stack==NULL){
                return 0; 
            }
            if(!isMatching(pop(), str[i])){
                return 0;
            }
        } 
        i++; 

    }
    
    if(stack==NULL){
        return 1; // balanced parenthesis
    }else{
        return 0; // not balanced parenthesis
    }
}

And this is the main function where the user inputs a string and it's tested if it's 'Balanced' or not.

int main(){
    char str[MAX];
    int flag;
    printf("Enter the string with the brackets and etc.\n");
    fgets(str, sizeof(str),stdin); 
    flag=isBalanced(str);
    if(flag==1){
        printf("Balanced\n");
    }
    else{
        printf("Not balanced\n"); 
    }
    
    return 0;