Q22.
Design a yacc/lex code to recognize valid arithmetic expression with operators +,-,*
and /.
Program
(prog.l):
%{
#include "y.tab.h"
%}
%%
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
"+"    { return PLUS; }
"-"    { return MINUS; }
"*"    { return MUL; }
"/"   { return DIV; }
[ \t] {}
.     { printf("Unexpected character: %s\nINVALID expression", yytext); exit(1); }
%%
int yywrap(){
    return 1;
}
(prog.y)
%{
#include <stdio.h>
Ayush Dwivedi                                    Sec- A1                             Roll No. 15
#include <stdlib.h>
%}
%token NUMBER
%token PLUS MINUS MUL DIV
%%
expr:
    expr PLUS expr
    | expr MINUS expr
    | expr MUL expr
    | expr DIV expr
    | NUMBER
%%
int yyerror(const char *s){
    fprintf(stderr, "Error: %s\n", s);
    exit(1);
}
int main(){
    printf("Enter an arithmetic expression: ");
    if(yyparse() == 0){
        printf("This is a valid expression\n");
    else printf("This expression is invalid\n");
    return 0;
}
Ayush Dwivedi                                      Sec- A1   Roll No. 15
OUTPUT:
Ayush Dwivedi   Sec- A1   Roll No. 15
Q23. Design a yacc/lex code to evaluate arithmetic expression with operators +, -, *, and
/ with operator precedence.
Program
(prog.l):
%{
#include "y.tab.h"
%}
%%
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
[+\-*/] { return yytext[0]; }
"\n" { return '\n'; }
[ \t] { /* Ignore whitespace */ }
.    { printf("Unexpected character: %s\nINVALID expression\n", yytext); exit(1); }
%%
int yywrap(){
    return 1;
}
(prog.y):
%{
#include <stdio.h>
#include <stdlib.h>
%}
Ayush Dwivedi                                   Sec- A1                               Roll No. 15
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
stmt:
   expr '\n' { printf("The result is: %d\n", $1); }
  ;
expr:
   expr '+' expr { $$ = $1 + $3; }
   | expr '-' expr { $$ = $1 - $3; }
   | expr '*' expr { $$ = $1 * $3; }
   | expr '/' expr {
        if($3 == 0){
            fprintf(stderr, "Cannot divide by 0\n");
            exit(1);
        }
        else{
            $$ = $1 / $3;
   | NUMBER { $$ = $1; }
 ;
%%
int yyerror(const char *s){
   fprintf(stderr, "Error: %s\n", s);
   exit(1);
Ayush Dwivedi                                          Sec- A1   Roll No. 15
}
int main(){
    printf("Enter an arithmetic expression:\n");
    yyparse();
    return 0;
}
Output
Ayush Dwivedi                                      Sec- A1   Roll No. 15
Ayush Dwivedi   Sec- A1   Roll No. 15