Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //S->AB A->a B->b
- //ab accepted
- //aa not accepted
- #include <stdio.h>
- #include <string.h>
- typedef struct {
- char left; // Non-terminal
- char right[10]; // Production rule right side
- } Rule;
- int main() {
- int rule_count, i = 0;
- char input[20], stack[50] = "", temp[50];
- Rule rules[10];
- // Input production rules
- printf("Enter the number of production rules: ");
- scanf("%d", &rule_count);
- getchar(); // Consume newline
- printf("Enter the production rules (e.g., S-->AB|a):\n");
- for (i = 0; i < rule_count; i++) {
- fgets(temp, sizeof(temp), stdin);
- temp[strcspn(temp, "\n")] = '\0';
- rules[i].left = temp[0]; // Left-hand side
- strcpy(rules[i].right, temp + 3); // Right-hand side
- }
- // Input string to parse
- printf("Enter the input string: ");
- scanf("%s", input);
- printf("%-14s %-14s %-14s\n", "Stack", "Input", "Action");
- printf("-------------- -------------- --------------\n");
- i = 0;
- while (1) {
- // Shift operation
- if (i < strlen(input)) {
- strncat(stack, &input[i++], 1);
- printf("%-15s%-15sShift %c\n", stack, &input[i], input[i - 1]);
- }
- // Reduction attempt
- int reduced = 0;
- for (int j = 0; j < rule_count; j++) {
- int len = strlen(rules[j].right);
- if (strlen(stack) >= len &&
- strcmp(stack + strlen(stack) - len, rules[j].right) == 0) {
- stack[strlen(stack) - len] = '\0'; // Remove matched part
- strncat(stack, &rules[j].left, 1);
- printf("%-15s%-15sReduce %c-->%s\n", stack, &input[i], rules[j].left, rules[j].right);
- reduced = 1;
- break;
- }
- }
- // Check for acceptance
- if (!reduced && i == strlen(input) && stack[0] == rules[0].left && stack[1] == '\0') {
- printf("\nAccepted\n");
- return 0;
- }
- // Reject if no reduction possible and input is consumed
- if (!reduced && i == strlen(input)) {
- printf("\nNot Accepted\n");
- return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement