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

Compiler design file part 2

Uploaded by

Nepturious
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Compiler design file part 2

Uploaded by

Nepturious
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

PRACTICAL 4

AIM: Write a program to remove left recursion from Grammar.

PROGRAM:

#include <stdio.h>
#include <string.h>
void main() {
char input[100], l[50], r[50], temp[10], tempprod[20], productions[25][50];
int i = 0, j = 0, flag = 0, consumed = 0;
printf("Enter the productions: ");
scanf("%1s->%s", l, r);
printf("%s", r);
while (sscanf(r + consumed, "%[^|]s", temp) == 1 && consumed <= strlen(r)) {
if (temp[0] == l[0]) {
flag = 1;
sprintf(productions[i++], "%s->%s%s'\0", l, temp + 1, l);
} else {
sprintf(productions[i++], "%s'->%s%s'\0", l, temp, l);
}
consumed += strlen(temp) + 1;
}
if (flag == 1) {
sprintf(productions[i++], "%s->ε\0", l);
printf("The productions after eliminating Left Recursion are:\n");
for (j = 0; j < i; j++)
printf("%s\n", productions[j]);
} else {
printf("The Given Grammar has no Left Recursion");
}
}
PRACTICAL-5

AIM: Write a program to perform Left Factoring on a Grammar.

Program:

#include<stdio.h>
#include<string.h>
int main() {
char gram[20], part1[20], part2[20], modifiedGram[20], newGram[20],
tempGram[20];
int i, j = 0, k = 0, l = 0, pos;
printf("Enter Production : A->");
gets(gram);
// Separate the two parts of the production
for (i = 0; gram[i] != '|'; i++, j++)
part1[j] = gram[i];
part1[j] = '\0';
for (j = ++i, i = 0; gram[j] != '\0'; j++, i++)
part2[i] = gram[j];
part2[i] = '\0';
for (i = 0; i < strlen(part1) || i < strlen(part2); i++) {
if (part1[i] == part2[i]) {
modifiedGram[k] = part1[i];
k++;
pos = i + 1;
}
}
for (i = pos, j = 0; part1[i] != '\0'; i++, j++)
newGram[j] = part1[i];
newGram[j++] = '|';
for (i = pos; part2[i] != '\0'; i++, j++)
newGram[j] = part2[i];
modifiedGram[k] = 'X';
modifiedGram[++k] = '\0';
newGram[j] = '\0';
printf("\n A->%s", modifiedGram);
printf("\n X->%s\n", newGram);
return 0;
}

You might also like