You are on page 1of 2

EXPERIMENT-7

AIM- Consider the following grammar:


S->ABC
A->abA|ab
B->b|BC
C->c|cC
Following any suitable parsing technique(prefer top-down),
design a parser which accepts a string and tells whether
the string is accepted by above grammar or not.

CODE-
/* recursive descent parser for the grammar
* s->ABC
* A->abA | ab
* B->b | BC
* C->c|cC
*/
#include<bits/stdc++.h>
using namespace std;
void match(char r);
void S(string s);
void A(string s);
void B(string s);
void C(string s);
void D(string s);
int lookahead=0;
int main()
{
cout<<"enter string"<<endl;
string str;
cin>>str;
S(str);
if(lookahead==str.length())
cout<<"Valid string";
return 0;
}
void match(char r,string s)
{
if(s[lookahead]==r)
{
lookahead++;
return ;
}
else
{
cout<<"Invalid string";
exit(0);
}
}
void S(string s)
{
A(s); B(s); C(s);
return ;
}
void A(string s)
{
match('a',s);
match('b',s);
if(lookahead<s.length() && s[lookahead]=='a')
A(s);
}
void B(string s)
{
match('b',s);
D(s);
}
void D(string s)
{
if(s[lookahead]=='c')
{
C(s); D(s);
}
else return;
}
void C(string s)
{
if(lookahead<s.length())
match('c',s);
if(lookahead<s.length() && s[lookahead]=='c')
C(s);
else return;
}

You might also like