FaltuTech.Club : Fane of Advanced Logical Thriving Utopian Technical Club

Check If A Equation Have Balanced Brackets Using Stack In C



#include 
#include 
struct stak{
int top;

char data_array[100];
}string;
void pop(){
string.top--;
}
void push(){
string.top++;
}


void check_if_balanced(char equation[]);
void main(){
char equation[20];
clrscr();

 printf("Enter any equation\n");
 gets(equation);
 check_if_balanced(equation);
 getch();
 }
 
 void check_if_balanced(char equation[]){
 int i=0,j=0,iseven=0;
 string.top=-1;


 while(equation[i]){
	if(equation[i]=='(' ||equation[i]=='{'||equation[i]=='['){
	push();
	string.data_array[j]=equation[i];
	j++;
	iseven++;
	}
	if(equation[i]==')'||equation[i]==']'||equation[i]=='}'){

		switch(equation[i]){
		case ')':
		iseven--;
		if(string.data_array[j-1]=='('){
		pop();
		j--;} break;
		case ']':
		iseven--;
		if(string.data_array[j-1]=='[' ){
		pop();
		j--;} break;

		case '}':
		iseven--;
		if(string.data_array[j-1]=='{'){
		pop();
		j--;} break;
		default:
		break;
		}
	}

 i++;
 }   // End of while
 if(string.top==-1 && iseven==0)
 printf("\nBalanced\n");
 else
 printf("\nNot Balanced\n");

 } // end of function