/* 2a. Write a LEX program to count number of lines, words, characters and blank spaces */
%{
int cha=0;
int words=0;
int lines=0;
int blanks=0;
%}
%%
\n lines++ ;
[ \t] cha++; blanks++;
[a-zA-Z0-9] cha++;
[a-zA-Z0-9]/[ \n] words++; cha++;
. cha++;
%%
main()
{
yylex();
printf("characters=%d\n",cha);
printf("words=%d\n",words);
printf("lines=%d\n",lines);
printf("blanks=%d\n",blanks);
}
/* 2b. Write a YACC program valid nested if statements and display the depth */
%{
#include"stdio.h"
#include"ctype.h"
%}
%%
%token IF
%token THEN
%token aop
%token rop
%token letter
%%
iflist:
|iflist '\n'
|iflist list {printf("\ncount =%d\n",count);}
;
list:
IF condition THEN stlist
| IF condition THEN list
;
condition:
exp
|exp rop condition
|'(' condition ')'
;
stlist:
exp
| stlist exp
| '{' stlist '}'
| '{' list '}'
;
exp:
letter
|exp aop letter
;
%%
#include<stdio.h>
int count = 0;
main()
{
yyparse();
}
yylex()
{
int c;
while((c=getchar())=='\t'||c==' '||c=='\n');
if(c=='I' || c=='i')
{
if((c=getchar())=='F' || c=='f')
{
count++;
return IF ;
}
}
if(c=='T' || c=='t')
if((c=getchar())=='H'||c=='h')
if((c=getchar())=='E' ||c=='e')
if((c=getchar())=='N' ||c=='n')
return THEN;
if(isalpha(c))
return letter;
if(c=='+'||c=='-'||c=='*'||c=='/')
return aop;
if(c==60||c==62)
return rop;
}
yyerror(char *s)
{
printf("\n%s ",s);
}