Professional Documents
Culture Documents
CD 6 PDF
CD 6 PDF
CD 6 PDF
T->T*F|F
F->(E)|id
E->TT'
T'->+TT'|ε
T->FT''
T''->*FT''|ε
F->(E)|id
E->TT’
T’->+TT’|ε
STEP 2: Op mize the DFA by decreases the number of states, yielding the final
transi on diagram.
STEP 3:
Simula on on the input string.
Steps involved in the simula on procedure are: Start from the star ng state.
If a terminal arrives consume it, move to the next state.
If a non-terminal arrive go to the state of the DFA of the non-terminal and return on
reached up to the final state.
Return to actual DFA and Keep doing parsing. If one completes reading the input
string completely, you reach a final state, and the string is successfully parsed.
Program:
#include <iostream>
#include <string>
using namespace std;
class Predic veParser {
private:
string input;
int index;
char lookahead() {
return input[index];
}
void match(char expected) {
if (lookahead() == expected)
index++;
else
cout << "Error: Unexpected token '" << lookahead() << "'" << endl;
}
void E() {
T();
EPrime();
}
void EPrime() {
if (lookahead() == '+') {
match('+');
T();
EPrime();
}
}
void T() {
F();
TPrime();
}
void TPrime() {
if (lookahead() == '*') {
match('*');
F();
TPrime();
}
}
void F() {
if (lookahead() == '(') {
match('(');
E();
match(')');
} else if (isalnum(lookahead())) {
match(lookahead());
} else {
cout << "Error: Unexpected token '" << lookahead() << "'" << endl;
}
}
public:
Predic veParser(string inputString) {
input = inputString;
index = 0;
}
void parse() {
E();
if (lookahead() == '$') // Ensure end of input
cout << "Parsing Successful!" << endl;
else
cout << "Error: Unexpected token '" << lookahead() << "'" << endl;
}
};
int main() {
string input;
cout<<"Gungun Sahu EN21CS301277"<<endl;
cout << "Enter the expression to parse: ";
cin >> input;
input += '$'; // Append end of input marker
Predic veParser parser(input);
parser.parse();
return 0;
}
Output: