-
Notifications
You must be signed in to change notification settings - Fork 0
/
1b.y
62 lines (52 loc) · 808 Bytes
/
1b.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
%{
#include "y.tab.h"
extern yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return num;}
[\+\-\*\/] {return yytext[0];}
[)] {return yytext[0];}
[(] {return yytext[0];}
. {;}
\n {return 0;}
%%
lab1b.y - PROGRAM
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token num
%left '+' '-'
%left '*' '/'
%%
input:exp{printf("%d\n",$$);exit(0);}
exp:exp'+'exp{$$=$1+$3;}
|exp'-'exp{$$=$1-$3;}
|exp'*'exp{$$=$1*$3;}
|exp'/'exp{ if($3==0){printf("Divide by Zero error\n");exit(0);}
else $$=$1/$3;}
|'('exp')'{$$=$2;}
|num{$$=$1;};
%%
int yyerror()
{
printf("error");
exit(0);
}
int main()
{
printf("Enter an expression:\n");
yyparse();
}
/*
output
gedit 1b.l
gedit 1b.y
lex 1b.l
yacc -d 1b.y
cc lex.yy.c y.tab.c -ll
./a.out
Enter th expr:
6+9
15
*/