Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

LAB - 4

Kumar Setu (2K19/IT/068)

FIRST program
Code:

1. #include<stdio.h>
2. #include<ctype.h>
3. void FIRST(char[],char );
4. void addToResultSet(char[],char);
5. int numOfProductions;
6. char productionSet[10][10];
7.  
8. int main()
9. {
10. int i;
11. char choice;
12. char c;
13. char result[20];
14. printf("How many number of productions ? :");
15. scanf(" %d",&numOfProductions);
16. for(i=0;i<numOfProductions;i++)//read production string
17. {
18. printf("Enter productions Number %d : ",i+1);
19. scanf(" %s",productionSet[i]);
20. }
21. do
22. {
23. printf("\n Find the FIRST of :");
24. scanf(" %c",&c);
25. FIRST(result,c); //Compute FIRST; Get Answer in result array
26. printf("\n FIRST(%c)= { ",c);
27. for(i=0;result[i]!='\0';i++)
28. printf(" %c ",result[i]); //Display result
29. printf("}\n");
30. printf("press 'y' to continue : ");
31. scanf(" %c",&choice);
32. }
33. while(choice=='y'||choice =='Y');
34. }
35.  
36.  
37. void FIRST(char* Result,char c)
38. {
39. int i,j,k;
40. char subResult[20];
41. int foundEpsilon;
42. subResult[0]='\0';
43. Result[0]='\0';
44. //If X is terminal, FIRST(X) = {X}.
45. if(!(isupper(c)))
46. {
47. addToResultSet(Result,c);
48. return ;
49. }
50.  
51. for(i=0;i<numOfProductions;i++)
52. {
53. if(productionSet[i][0]==c)
54. {
55. //PART 2 --> If X = eps is a production, then add eps to FIRST(X).
56. if(productionSet[i][2]=='$')
57. addToResultSet(Result,'$');
58. /*PART 3 --> If X is a non-terminal, and X = Y1 Y2 Y3....Yk is a production, then
59. add a to FIRST(X) if for some i, a is in FIRST(Yi), and eps is in all of
60. FIRST(Y1), …, FIRST(Yi-1).*/
61. else
62. {
63. j=2;
64. while(productionSet[i][j]!='\0')
65. {
66. foundEpsilon=0;
67. FIRST(subResult,productionSet[i][j]);
68. for(k=0;subResult[k]!='\0';k++)
69. addToResultSet(Result,subResult[k]);
70. for(k=0;subResult[k]!='\0';k++)
71. if(subResult[k]=='$')
72. {
73. foundEpsilon=1;
74. break;
75. }
76.  
77. if(!foundEpsilon)
78. break;
79. j++;
80. }
81. }
82. }
83. }
84. return ;
85. }
86.  
87. void addToResultSet(char Result[],char val)
88. {
89. int k;
90. for(k=0 ;Result[k]!='\0';k++)
91. if(Result[k]==val)
92. return;
93. Result[k]=val;
94. Result[k+1]='\0';
95. }
96.  
97.  
Outputs

You might also like