Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Compiler Design Lab Exercise 3

Name: DARSHNI B
Reg No: 21BLC1603
Date: 18/02/2024
1.Construct a Recursive Decent Parser for the following Grammar
E -> E + T | T
T -> T * F | F
F -> (E) | [a-z]
Parse the following string:
1)a+b*c+d
2)a*c+*d
3))a+b*c
4)((a+b)*c
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
char input[50];
int i;
bool E();
bool EP();
bool T();
bool TP();
bool F();
int main() {
scanf("%s", input);
i = 0;
if (E() && input[i] == '\0') {
printf("\nString is accepted\n");
} else {
printf("\nString is not accepted\n");}
return 0;
}
bool E() {
if (T()) {
if (EP()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
bool EP() {
if (input[i] == '+') {
i++;
if (T()) {
if (EP()) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return true;
}
}
bool T() {
if (F()) {
if (TP()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
bool TP() {
if (input[i] == '*') {
i++;
if (F()) {
if (TP()) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return true;
}
}
bool F() {
if (input[i] == '(') {
i++;
if (E()) {
if (input[i] == ')') {
i++;
return true;
} else {
return false;
}
} else {
return false;
}
} else if (isalpha(input[i])) {
i++;
return true;
} else {
return false;
}
}
OUTPUT:

2.Construct a Recursive Decent Parser for the following Grammar


E -> E # T | T
T -> T & F | F
F -> ! F | ( E ) | [a-z]
Parse the following string:
1) a#b&!c
2) a&#b
3) a#b&!c)
4) (a#b)&c)
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
char input[10];
int i;
bool E();
bool EP();
bool T();
bool TP();
bool F();
int main() {
scanf("%s", input);
i = 0;
if (E() && input[i] == '\0') {
printf("\nString is accepted\n");
} else {
printf("\nString is not accepted\n");
}
return 0;
}
bool E() {
if (T()) {
if (EP()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
bool EP() {
if (input[i] == '#') {
i++;
if (T()) {
if (EP()) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return true;
}
}
bool T() {
if (F()) {
if (TP()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
bool TP() {
if (input[i] == '&') {
i++;
if (F()) {
if (TP()) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return true;
}
}
bool F() {
if (input[i] == '!') {
i++;
if (F()) {
return true;
} else {
return false;
}
} else if (input[i] == '(') {
i++;
if (E()) {
if (input[i] == ')') {
i++;
return true;
} else {
return false;
}
} else {
return false;
}
} else if (isalpha(input[i])) {
i++;
return true;
} else {
return false;
}
}
OUTPUT:

RESULT:
Thus the codes were executed successfully.

You might also like