I wrote this program in c to check whether the parenthesis is balanced or not using the concept of stack.
#include<stdio.h>
#include<string.h>
#define MAX 100
int top = -1;
int arr[MAX];
void push(int x)
{
if (top == (MAX - 1))
{
printf("error:stack overflow n");
return;
}
top++;
arr[top] = x;
}
void pop()
{
top--;
}
int empty()
{
if (top == -1)
{
printf("The stack is empty \n ");
return 1;
}
else{
return 0;
}
}
int main()
{
char str[30];int len;int i;int temp;
printf("Enter he expression \n ");
scanf("%d",str);
len=strlen(str);
for(i=0;i<len;i++)
{
if (str[i] == '(' || str[i] == '{' || str[i] == '[')
{
push(str[i]);
}
if (str[i] == ')' || str[i] == '}' || str[i] == ']')
{
temp=empty();
if((empty())==1)
{
printf("Unbalanced\n ");
return;
}
else if(str[i]==arr[top])
{
pop();
}
}
}
if((empty())==1)
{
printf("Balanced\n");
}
else {
printf("unbalanced\n");
}
return 0;
}
however whatever the input i give the result i am getting is
Enter he expression
{{{]])
empty happend
Balanced
i have isolated the problem where my push and pop function are not being called,and the stack is empty regardless of the input.
any idea how to fix the code?