left recursion program in c++
#include <iostream>
#include <string>
using namespace std;
bool S(string input, int& index);
bool A(string input, int& index) {
if (input[index] == 'a') {
index++;
if (S(input, index)) {
if (input[index] == 'd') {
index++;
return true;
}
}
}
return false;
}
bool S(string input, int& index) {
if (A(input, index)) {
return true;
}
return false;
}
int main() {
string input;
cout << "Enter a string: ";
cin >> input;
int index = 0;
if (S(input, index) && index == input.length()) {
cout << "Input string is in the language.\n";
} else {
cout << "Input string is not in the language.\n";
}
return 0;
}
Explanation:
S
andA
are two non-terminal symbols representing rules in a grammar.S
represents the left recursive rule in the grammar.- The
bool S(string input, int& index)
function checks if the input string satisfies the rule defined byS
. - The
bool A(string input, int& index)
function checks if the input string satisfies the rule defined byA
. - The
A
rule checks if the input starts with the character 'a', followed by the ruleS
and then ends with the character 'd'. - Inside
A
, it checks for 'a', and if found, increments the index and proceeds to check the ruleS
. IfS
is valid, it checks for 'd' at the end. - The
S
rule simply calls theA
rule. This introduces left recursion, asS
indirectly references itself. - The
main
function reads an input string from the user. - It initializes the index to 0 and checks if the input string satisfies the rule
S
. - If the input string satisfies the rule
S
completely (i.e., the entire string is consumed), it outputs that the input string is in the language; otherwise, it indicates that the input string is not in the language.