Write a program to perform left factoring on a grammer.

#include <stdio.h>

#include <string.h>


void leftFactor(char part1[], char part2[]) {

    char modifiedGram[20], newGram[20];

    int i, j = 0, k = 0, pos;


    for (i = 0; part1[i] != '\0' && part2[i] != '\0'; i++) {

        if (part1[i] == part2[i]) {

            modifiedGram[k] = part1[i];

            k++;

            pos = i + 1;

        }

    }


    modifiedGram[k] = 'X';

    modifiedGram[++k] = '\0';


    for (i = pos, j = 0; part1[i] != '\0'; i++, j++) {

        newGram[j] = part1[i];

    }


    newGram[j++] = '|';


    for (i = pos, j = 0; part2[i] != '\0'; i++, j++) {

        newGram[j] = part2[i];

    }


    newGram[j] = '\0';


    printf("\nGrammar Without Left Factoring : \n");

    printf(" A->%s\n", modifiedGram);

    printf(" X->%s\n", newGram);

}


int main() {

    char productions[100][20] = {

        "A->iaBx",

        "A->iaCd"

    };

    int n = 6; // Number of productions


    for (int i = 0; i < n; i++) {

        char part1[20], part2[20];

        int j;

        for (j = 0; productions[i][j] != '-'; j++) {

            part1[j] = productions[i][j];

        }

        part1[j] = '\0';


        for (j = 0; productions[i][j] != '\0'; j++) {

            part2[j] = productions[i][j];

        }

        part2[j] = '\0';


        leftFactor(part1, part2);

    }


    return 0;

}





Comments

Popular posts from this blog

Write a program to find out the FIRST of the Non‐terminals in a grammar.