530 CD
530 CD
Date:
3)First and Follow
3.1) Simulate First and Follow of a Grammar.
Program:
#include<stdio.h>
#include<string.h>
int n, m = 0, p, i = 0, j = 0;
char a[10][10], f[10];
void follow(char c);
void first(char c);
int main()
{
int i, z;
char c, ch;
printf("enter the no. of productions:");
scanf("%d", &n);
printf("enter the productions(epsilon = $):\n");
for(i = 0; i < n; i++)
scanf("%s%c", a[i], &ch);
do
{
m = 0;
printf("enter the element whose FIRST & FOLLOW is to be found:");
scanf("%c", &c);
first(c);
printf("FIRST(%c) = {", c);
for(i = 0;i<m;i++)
printf("%c", f[i]);
printf("}\n");
follow(c);
printf("FOLLOW(%c) = {", c);
for(;i<m;i++)
printf("%c", f[i]);
printf("}\n");
printf("do you want to continue(0/1)?");
scanf("%d%c", &z, &ch);
}
while(z = 1);
}
void follow(char c)
{
if(a[0][0] = c)
f[m++] = '$';
for(i = 0;i<n;i++)
{
for(j = 2;j<strlen(a[i]);j++)
{
if(a[i][j] = c)
{
if(a[i][j+1] != '\0')first(a[i][j+1]);
3.2) Implement the lexical analyzer using JLex, flex or lex or other lexical analyzer
generating tools
Program:
%{
#include<stdio.h>
int i=0,id=0;
%}
%%
[#].*[<].*[>]\n {}
[ \t\n]+ {}
\/\/.*\n {}
\/\*(.*\n)*.*\*\/ {}
auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|
register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|
while {printf("token : %d < keyword , %s >\n",++i,yytext);}
[+\-\*\/%<>] {printf("token : %d < operator , %s >\n",++i,yytext);}
[();{}] {printf("token : %d < special char , %s >\n",++i,yytext);}
[0-9]+ {printf("token : %d < constant , %s >\n",++i,yytext);}
[a-zA-Z_][a-zA-Z0-9_]* {printf("token : %d < Id%d ,%s >\n",++i,++id,yytext);}
^[^a-zA-Z_] {printf("ERROR Invaild token %s \n",yytext);}
%%
Output:
Week - 4
4)Top Down Parsing
4.1) Develop an operator precedence parser for a given language.
Program:
#include<stdio.h>
#include<string.h>
char stack[20],temp;
int top=-1;
void push(char item)
{
if(top>=20)
{
printf("STACK OVERFLOW");
return;
}
stack[++top]=item;
}
char pop()
{
if(top<=-1)
{
printf("STACK UNDERFLOW");
return;
}
char c;
c=stack[top--];
printf("Popped element:%c\n",c);
return c;
}
char TOS()
{
return stack[top];
}
int convert(char item)
{
switch(item)
{
case 'i':return 0;
case '+':return 1;
case '*':return 2;
case '$':return 3;
}
}
int main()
{
char pt[4][4]={
else if(pt[convert(TOS())][convert(input[lkh])]=='<')
{
push(input[lkh]);
printf("Push---%c\n",input[lkh]);
lkh++;
}
else
{
pop();
}
}
return 0;
}
Output:
Output: