Pages

Friday, 11 October 2013

C code to eliminate productions in a Grammar

C program to eliminate the productions that do not produce terminal in a grammar.

#include<stdio.h> 

int check(char ,int ); 
int flag=0; 
char a[20][20]; 
int main() 
{ 
int i=0,j=0,k,n,p; 
char c; 
FILE *fp; 
//clrscr(); 
fp=fopen("input.txt","r"); 
while(fscanf(fp,"%c",&c)!=EOF) 
{ 
 if(c=='|') 
 { 
 a[i][j]='\n'; 
 j=0,i++; 
 a[i][j]=a[i-1][j++]; 
 a[i][j++]='-'; 
 a[i][j++]='>'; 
 } 
 else if(c!='\n') 
   a[i][j++]=c; 
 else 
 { 
 a[i][j]=c; 
 i++; 
 j=0; 
 }
} 
n=i; 
j=i=0; 
fclose(fp); 
printf("\n\tStart symbol is S\n\tCapital latters are variables\n\tSmall latters are terminals\n"); 
printf("\n:::::::::::----INPUT-----::::::::::::\n\n"); 
while(i<n) 
{ 
 if(a[i][j]!='\n') 
  printf("%c",a[i][j++]); 
 else 
 { 
  printf("%c",a[i][j]); 
  i++; 
  j=0; 
 }
} 
i=0; 
j=3; 
while(i<n) 
{ 
if(a[i][j]!='\n') 
{ 
 if(a[i][j]=='S') 
  j++; 
 if(a[i][j]>='a'&&a[i][j]<='z') 
  j++; 
 if(a[i][j]>='A'&&a[i][j]<='Z') 
 { 
    
 check(a[i][j],n); 
 if(flag==1) 
 { 
   a[i][0]=' '; 
 }  
 j++; 
  }   //ifA 
 }    //if'/n' 
 else 
 { 
 i++; 
 j=3; 
 } 
}  
//while// 
i=j=0; 
printf("\n:::::::::::----OUTPUT-----::::::::::::\n\n"); 
while(i<n) 
{ 
 if(a[i][j]==' ') 
 { 
 i++; 
 j=0; 
 } 
 else if(a[i][j]!='\n') 
 printf("%c",a[i][j++]); 
 else 
 { 
 printf("%c",a[i][j]); 
 i++; 
 j=0; 
 }
} 
//getch(); 
} 

  
int check(char c,int n) 
{ 
//char b; 
int i=0,p,j=3; 

for(i=0;i<n;i++) 
  if(a[i][0]==c) 
  {  
 flag=0; 
   break;   
  } 
  else 
   flag=1; 
while(a[i][j]!='\n'&&flag!=1) 
{ 
 if(a[i][j]=='S'||a[i][j]==c) 
  j++; 

 if(a[i][j]>='a'&&a[i][j]<='z') 
  j++; 

 if(a[i][j]>='A'&&a[i][j]<='Z') 
 { 
  check(a[i][j],n); 
   j++; 
  } 
 }
}

INPUT FILE (input.txt):-

S->ASa|ASB|ASC|AB
A->a
B->b
C->D

Output:-

C code to eliminate productions in a Grammar

Related Programs:-

Regular Grammar

SLR Parser

Context Free Grammar (CFG)

DFA (Deterministic Finite Automata)

NFA (Non-Deterministic Finite Automata)

No comments:

Post a Comment

Back to Top