0% found this document useful (0 votes)
2 views

Left Recursion

The document contains a C program that eliminates left recursion from a set of grammar production rules. It prompts the user to input the number of production rules and the rules themselves, then processes each rule to identify and remove left recursion if present. The modified grammar is printed to the console after processing.

Uploaded by

Ridya Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Left Recursion

The document contains a C program that eliminates left recursion from a set of grammar production rules. It prompts the user to input the number of production rules and the rules themselves, then processes each rule to identify and remove left recursion if present. The modified grammar is printed to the console after processing.

Uploaded by

Ridya Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <string.h>

void eliminateLeftRecursion(char s[][50], int n) {


printf("Grammar after removing left recursion if any:\n");

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


char p[50];
strcpy(p, s[i]);

if (strchr(p, '|') == NULL) {


printf("%s\n", p);
} else {
char q[10][50]; // Assuming a maximum of 10 alternatives
int q_count = 0;
char *token = strtok(p, "|");

while (token != NULL) {


strcpy(q[q_count++], token);
token = strtok(NULL, "|");
}

char *a = q[0];
char *b = q[q_count - 1];

if (a[0] == a[3]) {
char x[50];
strcpy(x, &a[4]);
char y = a[0];

printf("%c->%s%c'\n", y, b, y);
printf("%c'->%s%c'", y, x, y);

for (int j = 1; j < q_count - 1; j++) {


char *r = q[j];
char *d = &r[1];
printf("|%s%c'", d, y);
}

printf("|eps\n");
} else {
printf("%s\n", s[i]);
}
}
}
}

void main() {
printf("Enter the number of Production Rules: ");
int n;
scanf("%d", &n);
fflush(stdin); // Flush input buffer

char s[10][50]; // Assuming a maximum of 10 production rules, each with a


length of up to 50 characters

printf("Enter the production rules in the form 'E->EA | A':\n");


for (int i = 0; i < n; i++) {
scanf("%s", s[i]);
}

eliminateLeftRecursion(s, n);
}

You might also like