Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //S->aS|b no left recursion
- //A->Aa|Ab|c
- //A->cA'
- //A'->a|bA'|e
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- #define MAX 100
- void checkLeftRecursion(char nonTerminal, char *productions) {
- char alpha[MAX] = "", beta[MAX] = "";
- int isLeftRecursive = 0;
- for (char *token = strtok(productions, "|"); token; token = strtok(NULL, "|")) {
- if (token[0] == nonTerminal) {
- isLeftRecursive = 1;
- strcat(alpha, token + 1);
- strcat(alpha, "|");
- } else {
- strcat(beta, token);
- strcat(beta, "|");
- }
- }
- if (isLeftRecursive) {
- alpha[strlen(alpha) - 1] = '\0';
- beta[strlen(beta) - 1] = '\0';
- printf("Left Recursive Grammar Detected.\n");
- printf("%c -> %s%c'\n", nonTerminal, beta, nonTerminal);
- printf("%c' -> %s%c'|e\n", nonTerminal, alpha, nonTerminal);
- } else {
- printf("No Left Recursion detected.\n");
- }
- }
- int main() {
- char input[MAX], nonTerminal, productions[MAX];
- printf("Enter the production rule (e.g., A->Aa|b): ");
- fgets(input, MAX, stdin);
- input[strcspn(input, "\n")] = '\0';
- if (!isupper(input[0]) || strncmp(input + 1, "->", 2) != 0) {
- printf("Error: Invalid production rule format.\n");
- return 0;
- }
- nonTerminal = input[0];
- strcpy(productions, input + 3);
- checkLeftRecursion(nonTerminal, productions);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement