superdemo.java
unknown
java
a year ago
3.3 kB
15
Indexable
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int n, m = 0, i = 0, j = 0;
char a[10][10], f[10], visited[10];
void follow(char c);
void first(char c);
void main() {
int i, z;
char c, ch;
printf("Enter the number of productions:\n");
scanf("%d", &n);
printf("Enter the productions (in the format: A->B):\n");
// Read productionssca
for(i = 0; i < n; i++) {
scanf("%s%c", a[i], &ch); // Read each production rule
}
do {
m = 0; // Reset the set for each query
memset(f, 0, sizeof(f)); // Clear the array to avoid garbage values
printf("Enter the element whose FIRST & FOLLOW is to be found: ");
scanf(" %c", &c); // Notice the space before %c to consume newline character
// Calculate and display FIRST
first(c);
printf("FIRST(%c) = {", c);
for(i = 0; i < m; i++) {
printf("%c", f[i]);
if (i != m - 1) printf(", ");
}
printf("}\n");
// Reset for FOLLOW calculation
m = 0;
memset(f, 0, sizeof(f)); // Reset the set for FOLLOW calculation
// Calculate and display FOLLOW
follow(c);
printf("FOLLOW(%c) = {", c);
for(i = 0; i < m; i++) {
printf("%c", f[i]);
if (i != m - 1) printf(", ");
}
printf("}\n");
// Ask if the user wants to continue
printf("Continue (1 for Yes, 0 for No)? ");
scanf("%d%c", &z, &ch); // Read choice to continue or not
} while(z == 1);
}
void first(char c) {
int k;
// If 'c' is a terminal, add it to the FIRST set
if (!isupper(c)) {
if (!strchr(f, c)) { // Check if the character is already in the set
f[m++] = c;
}
}
// If 'c' is a non-terminal, process its productions
for (k = 0; k < n; k++) {
if (a[k][0] == c) {
if (a[k][2] == '$') {
follow(a[k][0]); // If the production has epsilon, follow the non-terminal
} else if (islower(a[k][2])) {
if (!strchr(f, a[k][2])) {
f[m++] = a[k][2]; // Add terminal to FIRST
}
} else {
first(a[k][2]); // Recursively call first for non-terminal
}
}
}
}
void follow(char c) {
// Avoid adding duplicate entries to FOLLOW set
if (visited[c - 'A']) return;
visited[c - 'A'] = 1;
if (a[0][0] == c) {
f[m++] = '$'; // Add '$' to FOLLOW of start symbol
}
// Iterate over all productions
for (i = 0; i < n; i++) {
for (j = 2; j < strlen(a[i]); j++) {
// If the non-terminal 'c' appears in the right-hand side
if (a[i][j] == c) {
// If it is not the last character, add FIRST of the next character
if (a[i][j + 1] != '\0') {
first(a[i][j + 1]);
}
// If it is the last character or epsilon, add FOLLOW of left-hand side
if (a[i][j + 1] == '\0' && c != a[i][0]) {
follow(a[i][0]);
}
}
}
}
}
Editor is loading...
Leave a Comment