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:

  1. Step – Using gedit create a file with extension .l For example: prg1.l
  2. Step – lex prg1.l
  3. Step – cc lex.yy.c –ll
  4. Step – ./a.out

Steps in writing YACC Program:

  1. Step: Using gedit editor create a file with extension y. For example: gedit prg1.y
  2. Step: YACC –d prg1.y
  3. Step: lex prg1.l
  4. Step: cc y.tab.c lex.yy.c -ll
  5. 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

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();
}

System Software Lab 1b Code [lab1b.y] – Output

System Software

Leave a Reply

Your email address will not be published. Required fields are marked *

WhatsApp Icon Join For Job Alerts