C PROGRAM TO CHECK BALANCED PARENTHESIS - ( { [

Consider the following I/O samples.



SAMPLE INPUT 1: [ { ( ) } ]          

SAMPLE OUTPUT 1 :  VALID


      
SAMPLE INPUT 2: [ { ] }

SAMPLE OUTPUT 1 :  INVALID




 


C PROGRAM:

#include<stdio.h>
#include<string.h>
#define N 100
char stack[N];
int i=-1;

//push parenthesis into stack
void push(char data)                
{
    i++;
    if(i>=N)
        printf("Stack is full");
    else
        stack[i]=data;
}

//pop parenthesis out from the stack
void pop()
{
    if(i == -1)
        printf("Cannot remove");
    else
        i--;
}
char top()
{
    return stack[i];
}
int empty()
{
    if(i == -1)
        return 1;  // stack empty
    else
        return 0;  // stack not empty
}
int main()
{
    char s[100];
    int itr;
    scanf("%s",s);
    for(itr=0;s[itr]!='\0';itr++)
    {
        if(s[itr]=='(' || s[itr]=='{' || s[itr]=='[')
            push(s[itr]);
        else
        {
            if(empty())    
            {
                printf("INVALID");
                return 0;
            }
            else
            {
                char t=top();
                if(t == '(' && s[itr] == ')' || t == '[' && s[itr] == ']' || t == '{' && s[itr] == '}')
                    pop();
                else
                {
                    printf("INVALID");
                    return 0;
                }
            }
        }    
    }
    if(empty())
        printf("BALANCED");
    else
        printf("NOT BALANCED");

}

 

OUTPUT:

 




  

The given source code in C program is short and simple to understand. The source code is well tested in DEV-C++ and is completely error free. 
If you have any feedback about this article and want to improve this, please comment in the comment section.

 

Comments

Popular posts from this blog

HOLLOW INVERTED PYRAMID STAR

HOLLOW PYRAMID STAR PATTERN

INNER REDUCING PATTERN