For a given grammar g[e]:
E→e+t| E-t| T
T→t*f| T/f| F
f→ (E) |i
The grammar to eliminate left recursion is:
E→te '
E ' →+te ' |-te ' |∑
T→ft '
T ' →*ft ' |/ft ' |∑
f→ (E) |i
is ll (1) grammar?
Select (E→te ') =first (TE ') ={(, i}
Select (E ' →+te ') =first (+te ') ={+}
Select (E ' →-te ') =first (-te ') ={-}
Select (E ' →∑) =follow (e ') ={), #}
Select (t→ft ') =first (FT ') ={(, i}
Select (T ' →*ft ') =first (*ft ') ={*}
Select (T ' →/ft ') =first (/ft ') ={/}
Select (t ' →∑) =follow (t ') ={+,-,), #)
Select (f→ (e)) =first ((e)) ={(}
Select (f→i) =first (i) ={i}
From the above analysis, learned that this grammar satisfies ll (1) grammar
The code is as follows
1#include <stdio.h>2#include <string>3 Charstr[Ten];//record the string to parse4 intx=0;//Record first character5 6 voidE (); 7 voidX (); 8 voidT (); 9 voidY ();Ten voidF (); One A intMain () - { - intLen; theprintf"Please enter an arithmetic expression:"); -scanf"%s", str); -len=strlen (str); -str[len]='#'; +str[len+1]=' /'; - E (); +printf"\ nthe correct!\n"); Astrcpy (str,""); atx=0; - return 0; - } - - voidE () - { in T (); - X (); to } + - voidX () the { * if(str[x]=='+'|| str[x]=='-') $ {Panax NotoginsengX + +; - T (); the X (); + } A } the + voidT () - { $ F (); $ Y (); - } - the voidY () - {Wuyi if(str[x]=='*'|| str[x]=='/') the { -X + +; Wu F (); - Y (); About } $ } - - voidF () - { A if(str[x]>='a'&&str[x]<='Z') + { theX + +; - } $ Else if(str[x]>=0&&str[x]<=9) the { theX + +; the } the Else if(str[x]=='(') - { inX + +; the E (); the if(str[x]==')') About { theX + +; the } the Else + { -printf"\ n Error!\n"); theExit0);Bayi } the } the Else - { -printf"\ n Error r!\n"); theExit0); the } the}
Recursive descent analysis