recursive descent parser (1)
recursive descent parser (1)
expression
#include<stdio.h>
#include<string.h>
#include<ctype.h>
char input[100];
int i = 0, error = 0;
void E();
void Eprime();
void T();
void Tprime();
void F();
void E() {
// E → T E'
T();
Eprime();
}
void Eprime() {
// E' → + T E' | ε
if (input[i] == '+') {
i++;
T();
Eprime();
}
}
void T() {
// T → F T'
F();
Tprime();
}
void Tprime() {
// T' → * F T' | ε
if (input[i] == '*') {
i++;
F();
Tprime();
}
}
void F() {
// F → ( E ) | id
if (input[i] == '(') {
i++;
E();
if (input[i] == ')')
i++;
else
error = 1;
} else if (isalpha(input[i])) { // Handling identifiers (like variables)
i++;
while (isalnum(input[i]) || input[i] == '_') {
i++;
}
} else {
error = 1; // Error if it's not a valid factor (like an identifier or expression)
}
}
int main() {
printf("Enter an arithmetic expression: \n");
return 0;
}
Output
➢ Enter an arithmetic expression:
a+(b*c
Rejected..!!!
#include <stdio.h>
#include <string.h>
void shift();
void reduce();
int main() {
printf("Enter input string (e.g., id+id*id): ");
fgets(input, sizeof(input), stdin);
printf("\nStack\tInput\tAction\n");
return 0;
}
void shift() {
stack[++top] = input[i++]; // Shift input to stack
stack[top + 1] = '\0'; // Null-terminate stack string
printf("$%s\t%s$\tShift\n", stack, input + i);
}
void reduce() {
// Reduce 'id' to 'E'
if (top >= 1 && stack[top - 1] == 'i' && stack[top] == 'd') {
top -= 1; // Pop 'id'
stack[top] = 'E'; // Replace with 'E'
stack[top + 1] = '\0'; // Null-terminate stack string
printf("$%s\t%s$\tReduce id to E\n", stack, input + i);
}
OUTPUT