System Software Lab 1| Read Now
System Software VTU Lab
Program 1
a] Write a LEX program to recognize valid arithmetic expressions. Identifiers in the expression could be only
integers and operators could be + and *. Count the identifiers & operators present and print them separately.
b] Write YACC program to evaluate arithmetic expression involving operators: +, -, *, and /.
Steps in writing LEX Program:
- Step – Using gedit create a file with extension .l For example: prg1.l
- Step – lex prg1.l
- Step – cc lex.yy.c –ll
- Step – ./a.out
Steps in writing YACC Program:
- Step: Using gedit editor create a file with extension y. For example: gedit prg1.y
- Step: YACC –d prg1.y
- Step: lex prg1.l
- Step: cc y.tab.c lex.yy.c -ll
- Step: /a.out
System Software Lab 1a Code [lab1.l]
%{ #include<stdio.h> int v=0,op=0,id=0,flag=0; %} %% [a-zA-Z]+[0-9A-Za-z]* {id++;} [0-9]+ {id++;} [\+\-\*/\=] {op++;} "(" {v++;} ")" {v--;} ";" {flag=1;} .|\n {return 0;} %% int main() { printf("Enter the expression:"); yylex(); if((op+1)==id && v==0 && flag==0) { printf("\n Expression is Valid\n"); printf("No of identifier = %d \n No of Operators = %d \n",id,op); } else printf("\n Expression is Invalid\n"); return 0; }
System Software Lab 1a Code [lab1.l] – Output
System Software Lab 1b Code [lab1b.y]
%{ #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(); }