Q22.
Design a yacc/lex code to recognize valid arithmetic expression with operators +,
-, * and / .
CODE:
(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;
}
Ayush Dwivedi Sec-A1 15
(prog.y)
%{
#include <stdio.h>
#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 15
OUTPUT:
Ayush Dwivedi Sec-A1 15
Q23. Design a yacc/lex code to evaluate arithmetic expression with operators +, -, *,
and / with operator precedence.
SOURCE CODE:
(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;
}
Ayush Dwivedi Sec-A1 15
(prog.y):
%{
#include <stdio.h>
#include <stdlib.h>
%}
%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);
}
int main(){
printf("Enter an arithmetic expression:\
n"); yyparse();
return 0;
}
Ayush Dwivedi Sec-A1 15
OUTPUT:
Ayush Dwivedi Sec-A1 15
Q24. Design YACC / LEX code that translates INFIX Expression to POSTFIX
Expression.
Program.l
%{
#include "y.tab.h"
%}
%%
[0-9]+ {yylval=atoi(yytext); return NUMBER;}
[+\-*/] {return yytext[0];}
\n {return '\n';}
.{}
%%
int yywrap()
{
return 1;
}
Ayush Dwivedi Sec-A1 15
Program.y
%{
#include <stdio.h>
#include <stdlib.h>
void yyerror(const char *s);
int yylex();
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
stmt:
expr '\n' { printf("\n"); }
;
expr:
expr '+' expr { printf(" + "); }
| expr '-' expr { printf(" - "); }
| expr '*' expr { printf(" * "); }
| expr '/' expr { printf(" / "); }
| '(' expr ')' /* ignore parentheses in output */
| NUMBER { printf("%d ", $1); } // Changed yyval to $1
;
%%
void yyerror(const char *s)
{
fprintf(stderr, "Error: %s \n", s);
}
int main()
{
printf("Enter infix expression: \n");
yyparse();
return 0;
}
Ayush Dwivedi Sec-A1 15
OUTPUT
Ayush Dwivedi Sec-A1 15