Untitled
unknown
plain_text
9 months ago
2.4 kB
4
Indexable
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.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 number of productions:\n");
scanf("%d", &n);
printf("Enter the productions:\n");
// Input productions
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); // Ensure to capture the next non-whitespace character
// Calculate First set
first(c);
printf("First(%c) = {", c);
for (i = 0; i < m; i++) {
printf("%c", f[i]);
if (i < m - 1) printf(", ");
}
printf("}\n");
// Reset f[] and m for the follow set
strcpy(f, "");
m = 0;
// Calculate Follow set
follow(c);
printf("Follow(%c) = {", c);
for (i = 0; i < m; i++) {
printf("%c", f[i]);
if (i < m - 1) printf(", ");
}
printf("}\n");
printf("Continue (1 for Yes, 0 for No): ");
scanf("%d%c", &z, &ch);
} while (z == 1);
}
void first(char c) {
int k;
if (!isupper(c)) {
f[m++] = c; // If the character is a terminal, add it to the First set
}
for (k = 0; k < n; k++) {
if (a[k][0] == c) { // Check if the production starts with character c
if (a[k][2] == '$') { // If it contains epsilon
follow(a[k][0]);
} else if (islower(a[k][2])) {
f[m++] = a[k][2]; // If the next character is a terminal
} else {
first(a[k][2]); // Otherwise, recursively call first() on the next character
}
}
}
}
void follow(char c) {
if (a[0][0] == c) { // Add $ to the Follow set if c is the start symbol
f[m++] = '$';
}
for (i = 0; i < n; i++) {
for (j = 2; j < strlen(a[i]); j++) { // Check the production rules
if (a[i][j] == c) {
if (a[i][j + 1] != '\0') {
first(a[i][j + 1]);
}
if (a[i][j + 1] == '\0' && c != a[i][0]) {
follow(a[i][0]);
}
}
}
}
}Editor is loading...
Leave a Comment