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