CD Exp-5 Material
CD Exp-5 Material
EXERCISE – 5
Program:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
20 | P a g e
Roll No:
if (lookahead == '+') {
printf("E' -> +TE'\n");
match('+');
T();
EPrime();
21 | P a g e
Roll No:
} else {
printf("E' -> e\n");
}
}
void T() {
printf("T -> FT'\n");
F();
TPrime();
}
void TPrime() {
if (lookahead == '*') {
printf("T' -> *FT'\n");
match('*');
F();
TPrime();
} else {
printf("T' -> e\n");
}
}
void F() {
if (isdigit(lookahead)) {
printf("F -> %c\n", lookahead);
match(lookahead);
} else if (lookahead == '(') {
printf("F -> (E)\n");
match('(');
E();
match(')');
} else {
printf("Parsing failed: Unexpected character '%c'\n", lookahead);
exit(1);
}
}
void match(char expected) {
22 | P a g e
Roll No:
if (lookahead == expected) {
if (expected != '\0') {
index++;
lookahead = expr[index];
}
} else {
printf("Parsing failed: Expected '%c' but found '%c'\n", expected, lookahead);
exit(1);
}
}
Output:
Enter an arithmetic expression: 3*1
E -> TE'
T -> FT'
F -> 3
T' -> *FT'
F -> 1
T' -> e
E' -> e
Parsing successful.
23 | P a g e