PROGRAM 3:

Program to recognize a valid arithmetic expression that uses operator +, – , * and /.



ALGORITHM:

1. Start the program.
2. Read the input expression.
3. Check the validation of the given expression according to the specified rule using yacc.
4. Print the result after the validation check
5. Stop the program.


PROGRAM:

LEX PART

%{

    #include "y.tab.h"

%}

%%

[a-zA-Z_][a-zA-Z_0-9]* return id;

[0-9]+(\.[0-9]*)?      return num;

[+/*]                  return op;

.                      return yytext[0];

\n                     return 0;

%%

int yywrap()

{

return 1;

}

YACC PART



%{

    #include<stdio.h>

    int valid=1;  

%}

%token num id op

%%

start : id '=' s ';'

s :     id x      

      | num x      

      | '-' num x  

      | '(' s ')' x

      ;

x :     op s       

      | '-' s      

      |            

      ;

%%

int yyerror()

{

    valid=0;

    printf("\n Invalid expression!\n");

    return 0;

}

int main()

{

    printf("\n Enter the expression:\n");

    yyparse();

    if(valid)

    {

        printf("\n Valid expression!\n");

    }


}

COMPILATION

lex filename.l
yacc -d filename.y
cc lex.yy.c y.tab.c -w
./a.out

OUTPUT


Enter the expression:
a+b;

Valid expression!

Enter the expression:
a+b

Invalid expression!