Created
September 22, 2020 05:00
-
-
Save blacksmithop/ee21b95b08705471f0e2bf1b128cd8fb to your computer and use it in GitHub Desktop.
Calculator with lex, yacc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| %{ | |
| /* Definition section */ | |
| #include<stdio.h> | |
| #include "y.tab.h" | |
| extern int yylval; | |
| %} | |
| /* Rule Section */ | |
| %% | |
| [0-9]+ { | |
| yylval=atoi(yytext); | |
| return NUMBER; | |
| } | |
| [\t] ; | |
| [\n] return 0; | |
| . return yytext[0]; | |
| %% | |
| int yywrap() | |
| { | |
| return 1; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| %{ | |
| /* Definition section */ | |
| #include<stdio.h> | |
| int yylex(); | |
| void yyerror(); | |
| int flag=0; | |
| %} | |
| %token NUMBER | |
| %left '+' '-' | |
| %left '*' '/' '%' | |
| %left '(' ')' | |
| /* Rule Section */ | |
| %% | |
| ArithmeticExpression: E{ | |
| printf("\nResult=%d\n", $$); | |
| return 0; | |
| }; | |
| E:E'+'E {$$=$1+$3;} | |
| |E'-'E {$$=$1-$3;} | |
| |E'*'E {$$=$1*$3;} | |
| |E'/'E {$$=$1/$3;} | |
| |E'%'E {$$=$1%$3;} | |
| |'('E')' {$$=$2;} | |
| | NUMBER {$$=$1;} | |
| ; | |
| %% | |
| //driver code | |
| void main() | |
| { | |
| printf("\nEnter Arithmetic Expression with operations +,-,*,%%,/ and ():\n"); | |
| yyparse(); | |
| if(flag==0) | |
| printf("\nEntered arithmetic expression is Valid\n\n"); | |
| } | |
| void yyerror() | |
| { | |
| printf("\nEntered arithmetic expression is Invalid\n\n"); | |
| flag=1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment