Balanced Expression

☞ Given an expression examine whether the pairs and the orders of '{', '}', '(', ')', '[', ']' are correct in expression. The program should print "Balanced" when you follow order in expression otherwise print "Not Balanced".
Sample Input1
1
{[()]}
Sample Output1
Balanced
Sample Input2
2
({[]})
)([]{})
Sample Output2
Balanced
Not Balanced
Program
#include<stdio.h>
#include<string.h>
int main() {
    char str[100][100],top[50];
    int i,j,t=0,tc;
    scanf("%d",&tc);
    scanf("\n");
    for(i=0;i<tc;i++)
        fgets(str[i],100,stdin);
    for(i=0;i<tc;i++){
        t=0;
        for(j=0;j<strlen(str[i])-1;j++){
            if(str[i][j]=='{'||str[i][j]=='('||str[i][j]=='[')
                top[t++]=str[i][j];
            else{
                if((str[i][j]=='}' && top[t-1]=='{') || (str[i][j]==']' && top[t-1]=='[') || (str[i][j]==')' && top[t-1]=='(')){
                   top[t-1]='\0';
                   t--;
                } 
                else    break;
            }
        }
        if(t==0)    printf("Balanced\n");
        else        printf("Not balanced\n");
    }
}
Test Program

No comments:

Post a Comment

Total Pageviews