Advertisement
Sri27119

cd4 left recursion

Nov 20th, 2024 (edited)
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. //S->aS|b no left recursion
  2. //A->Aa|Ab|c
  3. //A->cA'
  4. //A'->a|bA'|e
  5.  
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <ctype.h>
  9.  
  10. #define MAX 100
  11.  
  12. void checkLeftRecursion(char nonTerminal, char *productions) {
  13. char alpha[MAX] = "", beta[MAX] = "";
  14. int isLeftRecursive = 0;
  15.  
  16. for (char *token = strtok(productions, "|"); token; token = strtok(NULL, "|")) {
  17. if (token[0] == nonTerminal) {
  18. isLeftRecursive = 1;
  19. strcat(alpha, token + 1);
  20. strcat(alpha, "|");
  21. } else {
  22. strcat(beta, token);
  23. strcat(beta, "|");
  24. }
  25. }
  26.  
  27. if (isLeftRecursive) {
  28. alpha[strlen(alpha) - 1] = '\0';
  29. beta[strlen(beta) - 1] = '\0';
  30. printf("Left Recursive Grammar Detected.\n");
  31. printf("%c -> %s%c'\n", nonTerminal, beta, nonTerminal);
  32. printf("%c' -> %s%c'|e\n", nonTerminal, alpha, nonTerminal);
  33. } else {
  34. printf("No Left Recursion detected.\n");
  35. }
  36. }
  37.  
  38. int main() {
  39. char input[MAX], nonTerminal, productions[MAX];
  40.  
  41. printf("Enter the production rule (e.g., A->Aa|b): ");
  42. fgets(input, MAX, stdin);
  43. input[strcspn(input, "\n")] = '\0';
  44.  
  45. if (!isupper(input[0]) || strncmp(input + 1, "->", 2) != 0) {
  46. printf("Error: Invalid production rule format.\n");
  47. return 0;
  48. }
  49.  
  50. nonTerminal = input[0];
  51. strcpy(productions, input + 3);
  52.  
  53. checkLeftRecursion(nonTerminal, productions);
  54. return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement