fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. char stack[100];
  6. char input[100];
  7. int top = -1;
  8.  
  9. void printStack()
  10. {
  11. int i;
  12. for(i = 0; i <= top; i++)
  13. printf("%c", stack[i]);
  14. printf("\n");
  15. }
  16.  
  17. void reduce()
  18. {
  19. int changed = 1;
  20.  
  21. while(changed)
  22. {
  23. changed = 0;
  24.  
  25. if(top >= 0 &&
  26. stack[top] >= 'a' &&
  27. stack[top] <= 'z')
  28. {
  29. stack[top] = 'E';
  30. printf("Reduce: ");
  31. printStack();
  32. changed = 1;
  33. }
  34.  
  35. if(top >= 2 &&
  36. stack[top-2] == '(' &&
  37. stack[top-1] == 'E' &&
  38. stack[top] == ')')
  39. {
  40. top -= 2;
  41. stack[top] = 'E';
  42. printf("Reduce: ");
  43. printStack();
  44. changed = 1;
  45. continue;
  46. }
  47.  
  48. if(top >= 2 &&
  49. stack[top-2] == 'E' &&
  50. stack[top-1] == '+' &&
  51. stack[top] == 'E')
  52. {
  53. top -= 2;
  54. stack[top] = 'E';
  55. printf("Reduce: ");
  56. printStack();
  57. changed = 1;
  58. continue;
  59. }
  60.  
  61. if(top >= 2 &&
  62. stack[top-2] == 'E' &&
  63. stack[top-1] == '*' &&
  64. stack[top] == 'E')
  65. {
  66. top -= 2;
  67. stack[top] = 'E';
  68. printf("Reduce: ");
  69. printStack();
  70. changed = 1;
  71. continue;
  72. }
  73. }
  74. }
  75.  
  76. int main()
  77. {
  78. int ptr = 0;
  79. int i, len;
  80.  
  81. printf("Enter an Expression: ");
  82. fgets(input, sizeof(input), stdin);
  83.  
  84. char exp[100];
  85. int j = 0;
  86.  
  87. for(i = 0; input[i] != '\0'; i++)
  88. {
  89. if(input[i] != ' ' &&
  90. input[i] != '\t' &&
  91. input[i] != '\n')
  92. {
  93. exp[j++] = input[i];
  94. }
  95. }
  96.  
  97. exp[j] = '\0';
  98. len = strlen(exp);
  99.  
  100. while(ptr < len)
  101. {
  102. stack[++top] = exp[ptr++];
  103. printf("Shift: ");
  104. printStack();
  105.  
  106. reduce();
  107. }
  108.  
  109. reduce();
  110.  
  111. if(top == 0 && stack[0] == 'E')
  112. printf("String Accepted\n");
  113. else
  114. printf("String Rejected\n");
  115.  
  116. return 0;
  117. }
Success #stdin #stdout 0s 5324KB
stdin
(a + (b*a))
stdout
Enter an Expression: Shift: (
Shift: (a
Reduce: (E
Shift: (E+
Shift: (E+(
Shift: (E+(b
Reduce: (E+(E
Shift: (E+(E*
Shift: (E+(E*a
Reduce: (E+(E*E
Reduce: (E+(E
Shift: (E+(E)
Reduce: (E+E
Reduce: (E
Shift: (E)
Reduce: E
String Accepted