MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC1 BATCH: A
Practical 10
Title: Write a C Program to compute FOLLOW Set of the given grammar
Hint : Always initialize the FOLLOW set of the start symbol with the end-of-
input symbol '$'. This is because the start symbol can appear at the beginning of
a sentence.
Program :
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 10
int n;
char productions[MAX][MAX], first[MAX][MAX], follow[MAX][MAX];
char calc_first(char, int, int);
void calc_follow(char);
void find_first();
void find_follow();
int main() {
int i;
printf("Aagam Gandhi\n");
printf("92310103034\n");
printf("Enter the number of productions: ");
scanf("%d", &n);
printf("Enter the productions (Example: E=E+T):\n");
for (i = 0; i < n; i++) {
scanf("%s", productions[i]); }
find_first();
find_follow();
printf("\nFIRST sets:\n");
for (i = 0; i < n; i++) {
printf("FIRST(%c) = { %s }\n", productions[i][0], first[i]); }
printf("\nFOLLOW sets:\n");
for (i = 0; i < n; i++) {
printf("FOLLOW(%c) = { %s }\n", productions[i][0], follow[i]); }
Aagam Gandhi 92310103034
MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC1 BATCH: A
return 0;}
void find_first() {
int i, j;
char result;
for (i = 0; i < n; i++) {
result = calc_first(productions[i][0], 0, 0);
strncat(first[i], &result, 1); }}
void find_follow() {
int i;
follow[0][0] = '$';
for (i = 0; i < n; i++) {
calc_follow(productions[i][0]); }}
char calc_first(char c, int q1, int q2) {
int j;
if (!isupper(c)) {
return c;}
for (j = 0; j < n; j++) {
if (productions[j][0] == c) {
if (!isupper(productions[j][2])) {
return productions[j][2];
} else {
return calc_first(productions[j][2], q1, q2); } } }
return '\0';}
void calc_follow(char c) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 2; j < strlen(productions[i]); j++) {
if (productions[i][j] == c) {
if (productions[i][j + 1] != '\0') {
char next_first = calc_first(productions[i][j + 1], 0, 0);
if (next_first != '\0' && next_first != c) {
strncat(follow[i], &next_first, 1); } }
if (productions[i][j + 1] == '\0' && productions[i][0] != c) {
calc_follow(productions[i][0]);
strcat(follow[i], follow[productions[i][0] - 'A']); } } } }}
Aagam Gandhi 92310103034
MARWADI UNIVERSITY
DEPARTMENT OF COMPUTER ENGINEERING
CLASS: TC1 BATCH: A
Output:
Aagam Gandhi 92310103034