C PROGRAM FOR BALANCED EXPRESSION

Consider the following I/O samples.



SAMPLE INPUT 1: [10+(6-2)/{3-1}]       

SAMPLE OUTPUT 1 :  VALID


      
SAMPLE INPUT 2: (([a-z]+{c-d}/a)-d)/n)

SAMPLE OUTPUT 1 :  INVALID






 

C PROGRAM:


#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX_SIZE 100

int top=-1;
char arr[MAX_SIZE];
int isEmpty()
{
    if(top == -1)
        return true;
    else
        return false;
}

int isFull()
{
    if(top == MAX_SIZE-1)
        return true;
    else
        return false;
}

void push(char item)
{
    if(isFull())
        printf("Stack is full");
    else
        top++;
        arr[top] = item;
}

void pop()
{
    if(isEmpty())
        printf("Stack is empty");
    else
        top--;
}

char gettop()
{
    return arr[top];
}

int pair(char opening,char closing)
{
if(opening == '(' && closing == ')') 
    return true;
else if(opening == '{' && closing == '}') 
    return true;
else if(opening == '[' && closing == ']') 
    return true;
return false;
}

int main()
{
    char expr[MAX_SIZE];
    int length=0,i,j;
    scanf("%s",expr);
    length = strlen(expr);
    for(i=0;i<length;i++)
    {
        if(expr[i] == '(' || expr[i] == '{' || expr[i] == '[')
                push(expr[i]);
        else if(expr[i] == ')' || expr[i] == '}' || expr[i] == ']')
        {
            
            if(isEmpty() || !pair(gettop(),expr[i]))
            {
                printf("\nNOT BALANCED");
                return 0;
            }
            else
            {
                pop();
            }
        }
    }
    if(isEmpty())
        printf("\nBALANCED");
    else
        printf("\nNOT 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