Last active
November 3, 2015 18:05
-
-
Save devpruthvi/c0274f3e5f356c4134c3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
#include<string.h> | |
char* lhs[10] = { "E","E","E","E","E" }; | |
char *rhs[10] = { "E+E","E-E","E*E","E/E","a" }; | |
int numProductions = 5; | |
int row_id,len; | |
char stack[50] = "$"; | |
char inp_string[50]; | |
int get_id(char * string, char* arr[10],int len) | |
{ | |
int i; | |
for (i = 0; i < strlen(string); i++) | |
{ | |
if (string[i] == 'a') | |
{ | |
printf("\n%-15s%-15s%-15s", stack, inp_string, "reduce"); | |
string[i] = 'E'; | |
} | |
} | |
for (i = 0; i < len; i++) | |
{ | |
if (strcmp(string, arr[i]) == 0) | |
{ | |
return i; | |
} | |
} | |
return -1; | |
} | |
int main() | |
{ | |
printf("Enter a string to test: "); | |
scanf("%s", inp_string); | |
strcat(inp_string, "$"); | |
printf("\n%-15s%-15s%-15s\n", "Top of Stack", "Input String", "Parsing Action"); | |
printf("%045s\n",""); | |
while (inp_string[0] != '$') | |
{ | |
printf("\n%-15s%-15s%-15s", stack, inp_string, "shift"); | |
len = strlen(stack); | |
stack[len] = inp_string[0]; | |
stack[len + 1] = '\0'; | |
memmove(inp_string, inp_string + 1, strlen(inp_string)); | |
row_id = get_id(stack + 1, rhs, numProductions); | |
if (row_id != -1) | |
{ | |
printf("\n%-15s%-15s%-15s", stack, inp_string, "reduce"); | |
strcpy(stack, "$"); | |
memcpy(stack + 1, lhs[row_id], strlen(lhs[row_id])); | |
stack[2] = '\0'; | |
} | |
} | |
printf("\n%-15s%-15s%-15s\n", stack, inp_string, "shift"); | |
if (strcmp(stack, "$E") == 0 && strcmp(inp_string, "$") == 0) | |
printf("\n The string is ACCEPTED!"); | |
else | |
printf("The String is NOT accepted\n\n"); | |
return 0; | |
} |
Author
devpruthvi
commented
Sep 25, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment