Advertisement
Sri27119

cd7 shift reduce

Nov 20th, 2024
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. //S->AB A->a B->b
  2. //ab accepted
  3. //aa not accepted
  4.  
  5. #include <stdio.h>
  6. #include <string.h>
  7.  
  8. typedef struct {
  9. char left; // Non-terminal
  10. char right[10]; // Production rule right side
  11. } Rule;
  12.  
  13. int main() {
  14. int rule_count, i = 0;
  15. char input[20], stack[50] = "", temp[50];
  16. Rule rules[10];
  17.  
  18. // Input production rules
  19. printf("Enter the number of production rules: ");
  20. scanf("%d", &rule_count);
  21. getchar(); // Consume newline
  22.  
  23. printf("Enter the production rules (e.g., S-->AB|a):\n");
  24. for (i = 0; i < rule_count; i++) {
  25. fgets(temp, sizeof(temp), stdin);
  26. temp[strcspn(temp, "\n")] = '\0';
  27. rules[i].left = temp[0]; // Left-hand side
  28. strcpy(rules[i].right, temp + 3); // Right-hand side
  29. }
  30.  
  31. // Input string to parse
  32. printf("Enter the input string: ");
  33. scanf("%s", input);
  34.  
  35. printf("%-14s %-14s %-14s\n", "Stack", "Input", "Action");
  36. printf("-------------- -------------- --------------\n");
  37.  
  38. i = 0;
  39. while (1) {
  40. // Shift operation
  41. if (i < strlen(input)) {
  42. strncat(stack, &input[i++], 1);
  43. printf("%-15s%-15sShift %c\n", stack, &input[i], input[i - 1]);
  44. }
  45.  
  46. // Reduction attempt
  47. int reduced = 0;
  48. for (int j = 0; j < rule_count; j++) {
  49. int len = strlen(rules[j].right);
  50. if (strlen(stack) >= len &&
  51. strcmp(stack + strlen(stack) - len, rules[j].right) == 0) {
  52. stack[strlen(stack) - len] = '\0'; // Remove matched part
  53. strncat(stack, &rules[j].left, 1);
  54. printf("%-15s%-15sReduce %c-->%s\n", stack, &input[i], rules[j].left, rules[j].right);
  55. reduced = 1;
  56. break;
  57. }
  58. }
  59.  
  60. // Check for acceptance
  61. if (!reduced && i == strlen(input) && stack[0] == rules[0].left && stack[1] == '\0') {
  62. printf("\nAccepted\n");
  63. return 0;
  64. }
  65.  
  66. // Reject if no reduction possible and input is consumed
  67. if (!reduced && i == strlen(input)) {
  68. printf("\nNot Accepted\n");
  69. return 0;
  70. }
  71. }
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement