## C program to calculate FIRST of a regular expression

LOGIC: To compute FIRST(X) for all grammar symbols x, apply the following rules until no more terminals can be added to any FIRST set.

1. if X is terminal, then FIRST(X) is {X}.

2. if X is nonterminal and X-> aα is a production, then add a to FIRST(X). if X->€ to FIRST(X)

3. if -> Y1,Y2,…….Yk is a production, then for all i such that all of Y1,….Yi-1 are nonterminals and FIRST(Yj) contains € for j=1,2,…… i-1, add every non-€ symbol in FIRST(Y1) to FIRST(x). if V is in FIRST(Yj) for j=1,2,………k, then add € to FIRST(X).

				
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char t,nt,p,first,temp;
int i,j,not,nont,k=0,f=0;
clrscr();
printf("\nEnter the no. of Non-terminals in the grammer:");
scanf("%d",&nont);
printf("\nEnter the Non-terminals in the grammer:\n");
for(i=0;i<nont;i++)
{
scanf("\n%c",&nt[i]);
}
printf("\nEnter the no. of Terminals in the grammer: ( Enter e for absiline ) ");
scanf("%d",&not);
printf("\nEnter the Terminals in the grammer:\n");
for(i=0;i<not||t[i]=='$';i++) { scanf("\n%c",&t[i]); } for(i=0;i<nont;i++) { p[i]=nt[i]; first[i]=nt[i]; } printf("\nEnter the productions :\n"); for(i=0;i<nont;i++) { scanf("%c",&temp); printf("\nEnter the production for %c ( End the production with '$' sign ) :",p[i]);
for(j=0;p[i][j]!='$';) { j+=1; scanf("%c",&p[i][j]); } } for(i=0;i<nont;i++) { printf("\nThe production for %c -> ",p[i]); for(j=1;p[i][j]!='$';j++)
{
printf("%c",p[i][j]);
}
}
for(i=0;i<nont;i++)
{
f=0;
for(j=1;p[i][j]!='$';j++) { for(k=0;k<not;k++) { if(f==1) break; if(p[i][j]==t[k]) { first[i][j]=t[k]; first[i][j+1]='$';
f=1;
break;
}
else if(p[i][j]==nt[k])
{
first[i][j]=first[k][j];
if(first[i][j]=='e')
continue;
first[i][j+1]='$'; f=1; break; } } } } for(i=0;i<nont;i++) { printf("\n\nThe first of %c -> ",first[i]); for(j=1;first[i][j]!='$';j++)
{
printf("%c\t",first[i][j]);
}
}
getch();
}


INPUT/OUTPUT
Enter the no. of Non-terminals in the grammer:3
Enter the Non-terminals in the grammer:
ERT
Enter the no. of Terminals in the grammer: ( Enter e for absiline ) 5
Enter the Terminals in the grammer:
ase*+
Enter the productions :
Enter the production for E ( End the production with '$' sign ) :a+s$
Enter the production for R ( End the production with '$' sign ) :e$
Enter the production for T ( End the production with '$' sign ) :Rs$
The production for E -> a+s
The production for R -> e
The production for T -> Rs
The first of E -> a
The first of R -> e
The first of T -> e s</nont;i++)<></not;k++)<></nont;i++)<></nont;i++)<></nont;i++)<></nont;i++)<></not||t[i]=='\$';i++)<></nont;i++)<>