FIRST and FOLLOW

 #include <stdio.h>


#include <string.h>

#include <ctype.h>


int numProductions, resultIndex = 0;

char productions[10][10], result[10];


void follow(char nonTerminal);

void first(char nonTerminal);


int main()

{

    int i, continueFlag;

    char symbol, tempChar;


    printf("Enter the number of productions:\n");

    scanf("%d", &numProductions);


    printf("Enter the productions:\n");

    for (i = 0; i < numProductions; i++)

        scanf("%s%c", productions[i], &tempChar); // read each production


    do

    {

        resultIndex = 0;

        printf("Enter the non-terminal to find FIRST and FOLLOW: ");

        scanf("%c", &symbol);


        first(symbol);

        printf("FIRST(%c) = {", symbol);

        for (i = 0; i < resultIndex; i++)

            printf("%c", result[i]);

        printf("}\n");


        strcpy(result, " ");

        resultIndex = 0;


        follow(symbol);

        printf("FOLLOW(%c) = {", symbol);

        for (i = 0; i < resultIndex; i++)

            printf("%c", result[i]);

        printf("}\n");


        printf("Continue? (0 = No / 1 = Yes): ");

        scanf("%d%c", &continueFlag, &tempChar);

    } while (continueFlag == 1);


    return 0;

}


void first(char nonTerminal)

{

    int k;

    if (!isupper(nonTerminal))

        result[resultIndex++] = nonTerminal;


    for (k = 0; k < numProductions; k++)

    {

        if (productions[k][0] == nonTerminal)

        {

            if (productions[k][2] == '$')

            {

                follow(productions[k][0]);

            }

            else if (islower(productions[k][2]))

            {

                result[resultIndex++] = productions[k][2];

            }

            else

            {

                first(productions[k][2]);

            }

        }

    }

}


void follow(char nonTerminal)

{

    int i, j;

    if (productions[0][0] == nonTerminal)

        result[resultIndex++] = '$';


    for (i = 0; i < numProductions; i++)

    {

        for (j = 2; j < strlen(productions[i]); j++)

        {

            if (productions[i][j] == nonTerminal)

            {

                if (productions[i][j + 1] != '\0')

                {

                    first(productions[i][j + 1]);

                }

                if (productions[i][j + 1] == '\0' && nonTerminal != productions[i][0])

                {

                    follow(productions[i][0]);

                }

            }

        }

    }

}

Comments