1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
#include<stdio.h>
#include<conio.h>
#include <cstring>
#include <fstream>
using namespace std;
char nt[]={'S','A','X','Z','D','E','Y'},ter[]={'a','b','c','d','e','$'};
char arr[20][20][20]={
{"A","#"," "," ","#","#"," "},
{"ZX","#"," "," ","#","#"," "},
{" ","#","eA"," ","#","#"," "},
{"abD","#"," "," "," "," "," "},
{" ","#","Ed"," ","#","#",""},
{" ","#","cY"," ","#","#",""},
{" ","#"," "," ","#","#","cY"}
};
char ipstr[20];
char stack[40],prod[10];
int i=0,top=1,ia,ix;
int main()
{
void pop();
void push(char );
int resolve_nt(char );
int resolve_t(char );
void advance();
char a,x;
int len,temp,k;
stack[0]='$';
stack[1]='S';
printf("Enter the input string:\n");
printf("Enter $ as an end marker\n");
scanf("%s",ipstr);
printf("I/P String\t\tStack Contents\t\tProduction Used\n");
while(1)
{
a=ipstr[i];
x=stack[top];
/*To display the input string*/
for(k=i;ipstr[k]!='$';k++)
printf("%c",ipstr[k]);
printf("$\t\t");
if(x==a)
{
if(x=='$')
{
printf("\rinput string is accepted");
break;
}
else
{
pop();
advance();
}
}
else if(isupper(x))
{
ix=resolve_nt(x);
ia=resolve_t(a);
strcpy(prod,arr[ix][ia]);
len=strlen(prod);
pop();
for(k=1;k<=len;k++)
push(prod[len-k]);
if(stack[top]=='#')
pop();
}
else
{
printf("Error: Could not parse this input string");
break;
}
/*To display the stack contents and the production used*/
for(k=0;k<=top;k++)
printf("%c",stack[k]);
printf("\t\t\t\t%s\n",prod);
}
getch();
}
void push(char t)
{
top+=1;
stack[top]=t;
}
void pop()
{
top--;
}
void advance()
{
i++;
}
int resolve_nt(char t)
{
int k,index;
for(k=0;k<5;k++)
{
if(t==nt[k])
{
index=k;
break;
}
}
return index;
}
int resolve_t(char t)
{
int k,index;
for(k=0;k<6;k++)
{
if(t==ter[k])
{
index=k;
break;
}
}
return index;
}
|