BALANCING PARENTHESES IN AN EQUATION from

By | August 7, 2018

To check if the parentheses in a equation are balanced or not

Algorithm:

  • get the equation in a string variable
  • read one character at a time from left to right
  • push the character to stack if it is either  ‘(‘ or ‘{‘ or ‘[‘.
  • if the top element in stack is either ‘(‘ or ‘{‘ or ‘[‘ and the corresponding character read is ‘)’ or ‘}’ or ‘]’ pop it
  • also check if ‘)’ or ‘}’ or ‘]’ is read but stack is empty.
  • display the result

PROGRAM:

#include<stdio.h>
#include<string.h>
#define max 100
char stack[max];
char exp[max];
char c;
int i,top=-1;
void push(char a)
{
if(top==max-1)
printf("CANNOT INSERT,STACK FULL\n");
else
stack[++top]=a;
}
void pop()
{
if(top==-1)
printf("STACK EMPTY\n");
else
top--;
}
void checkparenthesis()
{
printf("\n Enter the expression\n");
scanf("%s",exp);
for(i=0;i<strlen(exp);i++)
{
if((exp[i]=='[')||(exp[i]=='(')||(exp[i]=='{'))
{ c=exp[i];
push(c);
}
else if((stack[top]=='['&&exp[i]==']')||(stack[top]=='{'&&exp[i]=='}')||
(stack[top]=='('&&exp[i]==')'))
pop();
else if((top==-1&&exp[i]==']')||(top==-1 &&exp[i]=='}')||
(top==-1 &&exp[i]==')'))
top=1;
else
continue;
}
if(top==-1)
printf("BALANCED EXPRESSION\n");
else
printf("UNBALANCED EQUATION\n");
}
void main()
{
checkparenthesis();
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Powered by CrazyTech