Monday, June 25, 2018

Check Expression - DS (C Program)

#include<stdio.h>
void PUSH(char s[],int *top,char num,int size)
{       
 int i;
if(*top == size-1)
{
printf("\nStack Overflow...");
return;
}
(*top)++;
s[*top]=num;
}
char POP(char s[],int *top)
{ int temp;
if(*top==-1)
{
return NULL;
}
temp=s[*top];
(*top)--;
return temp;
}
int isoperand(char c)
{      //7292
if((c >= 65 && c<=90) || (c >= 97 && c<=122) || (c>=48 && c<=57))
return 1;
return 0;
}
int isoperator(char c)
{
if(c == '+' || c == '-' || c == '/' || c == '*')
return 1;
return 0;
}
int opencase(char c)
{
if(c == '(')
return 1;
return 0;
}
int closecase(char c)
{
if(c == ')')
return 1;
return 0;
}
int check_parantheses(char expr[])
{
char s[30],pop;
int size=30,t=-1,i;
int *top=&t;
for(i=0;expr[i]!=NULL;i++)
{
if(expr[i] == '(')
PUSH(s,top,expr[i],size);
if(expr[i] == ')')
{
pop=POP(s,top);
if(pop == NULL)
return 0;
}
}
if(*top == -1)
return 1;
else
return 0;

}
int check_expression(char expr[])
{

int i;
if(check_parantheses(expr))
{
for(i=0;expr[i]!=NULL;i++)
{
if((isoperand(expr[i]) && isoperand(expr[i+1])) || (isoperator(expr[i]) && isoperator(expr[i+1])) || (isoperator(expr[i]) && closecase(expr[i+1])) || (expr[0] && closecase(expr[0])) || (opencase(expr[i]) && isoperator(expr[i+1])) || (closecase(expr[i]) && isoperand(expr[i+1])))
return 1;
}
return 0;
}
return 1;
}
void main()
{

char expr[30];
int check;
clrscr();
printf("\nEnter Expression : ");
gets(expr);
check = check_expression(expr);
if(check)
printf("\nInvalid Expression...");
else
printf("\nValid Expression...");
/*printf("\nDo you want to Continue. (Y | N)");
scanf("%c",&opt);
switch(opt)
{
case 'Y': goto y;
case 'y': goto y;
case 'N': goto n;
case 'n': goto n;
default: printf("\nInvalid Choice ... ");
break;
}
n:*/
getch();
}

No comments:

Post a Comment