How to write a c program to read a parenthesised infix expression from the user and check whether it is well parenthesised or not in C Programming Language ?
Solution:
/*write a c program to read a parenthesised infix expression from the user and check whether it is well parenthesised or not */
#include<stdio.h>
#include<conio.h>
void main()
{
char infix[20];
int stack[20],i,cnt=0,n;
int c=0,d=0,top=0,j=0,k=0;
clrscr();
printf("\nenter infix expression:-");
gets(infix);
n=strlen(infix);
for(i=0;i<n;i++)
{
if(infix[i]=='(')
c++;
if(infix[i]==')')
d++;
if(infix[i]=='*'||infix[i]=='/'||infix[i]=='+'||infix[i]=='-')
{
if(infix[i+1]=='('||infix[i+2]==')')
stack[top++]=1;
else
stack[top++]=0;
}
if(infix[i]=='*'||infix[i]=='/'||infix[i]=='+'||infix[i]=='-')
{
if(infix[i-1]==')'||infix[i-2]=='(')
stack[top++]=1;
else
stack[top++]=0;
}
if(infix[i]=='(')
{
if(infix[i+1]==')'||infix[i+2]==')'||infix[i+3]==')')
stack[top++]=0;
}
if(infix[i]==')')
{
if(infix[i-1]=='('||infix[i-2]=='('||infix[i-3]=='(')
stack[top++]=0;
}
}
for(i=0;i<n;i++)
{
if(infix[i]=='*'||infix[i]=='/'||infix[i]=='+'||infix[i]=='-')
j++;
if(infix[i]==')'||infix[i]=='(')
k++;
}
cnt=0;
for(i=top-1;i>=0;i--)
{
if(stack[i]==1)
cnt++;
}
if(c==d&&cnt==top&&j>0&&k>0)
printf("\nthe given expression is well parenthesised");
else
printf("\nit is not well parenthesised please try again");
getch();
}
/*
enter infix expression((A+B)*(C-D))
the given expression is well parenthesised
*/