-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfandf.c
More file actions
92 lines (88 loc) · 3 KB
/
fandf.c
File metadata and controls
92 lines (88 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **productions;
int fvar;
int findPos(char NonTer) {
int i = 0;
while (productions[i][0] != NonTer) {
i++;
}
return i;
}
char* findGenerating(char Ter) {
int i = 0;
while (productions[i][0] != Ter) {
i++;
}
return productions[i];
}
void findFirst(char *prod) {
int i;
for (i = 3; i < strlen(prod); i++) {
if ((prod[i] >= 'a' && prod[i] <= 'z') || prod[i] == ')' || prod[i] == '(' || prod[i] == ',') {
printf(" %c ", prod[i]);
while (prod[i] != '/' && prod[i] != '\0') {
i++;
}
} else if (prod[i] >= 'A' && prod[i] <= 'Z') {
findFirst(findGenerating(prod[i]));
return;
} else if (prod[i] == '#') {
printf(" #");
} else {
continue;
}
}
}
void findFollow(char GeneratingSymbol, int n) {
int i, j;
if (GeneratingSymbol == 'S')
printf(" $ ");
for (j = 0; j < n; j++) {
for (i = 3; i < strlen(productions[j]); i++) {
if (GeneratingSymbol == productions[j][i]) {
if ((productions[j][i + 1] >= 'a' && productions[j][i + 1] <= 'z') || productions[j][i + 1] == ')' || productions[j][i + 1] == '(' || productions[j][i + 1] == ',') {
printf(" %c ", productions[j][i + 1]);
} else if (productions[j][i + 1] >= 'A' && productions[j][i + 1] <= 'Z') {
findFirst(findGenerating(productions[j][i + 1]));
} else if (i + 1 == strlen(productions[j])) {
findFollow(productions[j][0], n);
} else {
continue;
}
}
}
}
}
int main() {
int i, n;
printf("Enter the number of productions: ");
scanf("%d", &n);
getchar(); // consume newline after the number input
productions = (char*)malloc(sizeof(char) * n);
for (i = 0; i < n; i++)
productions[i] = (char*)malloc(sizeof(char) * 20);
for (i = 0; i < n; i++) {
printf("Enter production %d: ", i + 1);
fgets(productions[i], 20, stdin);
productions[i][strcspn(productions[i], "\n")] = 0; // Remove newline character
}
for (i = 0; i < n; i++) {
printf("\nFIRST(%c)={ ", productions[i][0]);
findFirst(productions[i]);
printf("}\n");
}
for (fvar = 0; fvar < n; fvar++) {
printf("\nFOLLOW(%c)={", productions[fvar][0]);
findFollow(productions[fvar][0], n);
printf("}\n");
}
printf("\nThe End\n");
// Free allocated memory
for (i = 0; i < n; i++) {
free(productions[i]);
}
free(productions);
return 0;
}First and follow