CD Lab 3
CD Lab 3
CD Lab 3
SECTION : 01
Code:
#include<iostream>
#include<string>
string input;
int pos = 0;
// Function declarations
bool S();
bool A();
pos++;
return true;
}
return false;
bool A() {
return true;
pos = backtrack;
if (match('a')) {
return true;
return false;
bool S() {
// Match "cAd"
return true;
return false;
}
int main() {
} else {
return 0;
Output :
Input: cad
Input: cabd
Input: cbad
Code:
#include<iostream>
#include<stack>
#include<string>
string input;
int pos = 0;
stack<char> parseStack;
while (!parseStack.empty()) {
return;
}
if (top == currentInput) {
parseStack.pop();
pos++;
parseStack.pop();
} else {
return;
int main() {
predictiveParser(input);
return 0;
}
Output :
Input: ba$
Input: bb$
3)Design and implement an LL(1) parser for a simple expression grammar. The
language supports basic arithmetic expressions with the following features:
Operators: +, -, *, / Operands: Integer values Parentheses: ( and ) for grouping
Unary operators (e.g., -3), floating-point numbers, or exponentiation (e.g., ^
operator). Solution :
1. You can consider the following example grammar: E → TE' E' → +TE' |
-TE' | ε T → FT' T' → *FT' | /FT' | ε F → (E) | id
Code:
#include <iostream>
#include <stack>
#include <map>
#include <string>
// Parsing Table
void initializeParsingTable() {
// LL(1) Parser
stack<char> parseStack;
parseStack.push('$');
int pos = 0;
while (!parseStack.empty()) {
if (top == currentInput) {
parseStack.pop();
pos++;
parseStack.pop();
if (production != "ε") {
for (int i = production.length() - 1; i >= 0; i--) {
parseStack.push(production[i]);
} else {
return;
int main() {
initializeParsingTable();
string input;
parseLL1(input);
return 0;
}
Output :
Input: id+id$
Input: id*id$
Input: id+$
Code:
Lex code :
%{
#include "y.tab.h"
%}
%%
%%
int yywrap() {
return 1;
YACC Code :
%{
#include <stdio.h>
#include <math.h>
int yylex();
%}
%union {
%right '^'
%%
expr:
| term { $$ = $1; }
;
term:
| factor { $$ = $1; }
factor:
| NUMBER { $$ = $1; }
%%
int main() {
yyparse();
return 0;
Compile Code :
yacc -d yacc.y
lex lex.l
Test parser :
./parser
Enter an expression: (3 + 5) * 2 ^ 3
Result: 64
Output :
Enter an expression: (3 + 2) ^ 2
Result: 25
Code:
Lex:
%{
#include "y.tab.h"
%}
%%
%%
int yywrap() {
return 1;
Yacc:
%{
#include <stdio.h>
#include <math.h>
#include <string.h>
int yylex();
double binaryToDecimal(const char* binary);
%}
%union {
char* str;
double dval;
%%
expr:
int_part:
BINARY { $$ = binaryToDecimal($1); }
frac_part:
'.' BINARY { $$ = fractionalBinaryToDecimal($2); }
| { $$ = 0; }
%%
double result = 0;
return result;
factor /= 2;
return result;
int main() {
printf("Enter a binary number: ");
yyparse();
return 0;
Output :
$ ./binary_parser
Decimal: 5.625