You are on page 1of 2

Ex 5

Program to create a syntax tree for simple expression.


#include <stdio.h> len = strlen(expression);
#include <stdlib.h> expression[len - 1] = '#'; // Replace newline
#include <string.h> character with #

#define Blank ' ' for (i = 0; expression[i] != '#'; i++) {


#define Tab '\t' if (!white_space(expression[i])) {
#define MAX 100 switch (expression[i]) {
case '(':
long int pop(); push(expression[i]);
void expression_to_syntaxtree(); break;
int prec(char symbol);
void push(long int symbol); case ')':
int white_space(char symbol); while ((next = pop()) != '(')
syntaxtree[p++] = next;
char expression[MAX], syntaxtree[MAX]; break;
long int stack[MAX];
int top = -1; case '+':
case '-':
int main() { case '*':
char choice = 'y'; case '/':
case '%':
while (choice == 'y') { case '^':
top = -1; precedence = prec(expression[i]);
printf("Enter Expression : "); while (stack[top] != '#' &&
fflush(stdin); precedence <= prec(stack[top]))
fgets(expression, sizeof(expression), stdin); syntaxtree[p++] = pop();
expression_to_syntaxtree(); push(expression[i]);
printf("Expression Tree Format : %s\n", break;
syntaxtree);
printf("Want to continue(y/n) : "); default: /*if an operand comes */
scanf(" %c", &choice); // space added syntaxtree[p++] = expression[i];
before %c to consume newline } /*End of switch */
getchar(); // consume the newline } /*End of if */
character left in the input buffer } /*End of for */
}
while (stack[top] != '#')
return 0; syntaxtree[p++] = pop();
}
syntaxtree[p] = '\0'; /*End syntaxtree with
void expression_to_syntaxtree() { '\0' to make it a string*/
int i, p = 0, type, precedence, len; }
char next;
stack[++top] = '#'; // Initialize stack with # int prec(char symbol) {
Ex 5

switch (symbol) { } else {


case '(': stack[++top] = symbol;
return 0; }
case '+': }
case '-':
return 1; long int pop() {
case '*': if (top == -1) {
case '/': printf("Stack underflow \n");
case '%': exit(2);
return 2; } else {
case '^': return stack[top--];
return 3; }
default: }
return -1; // Unknown precedence for
unknown symbols int white_space(char symbol) {
} if (symbol == Blank || symbol == Tab ||
} symbol == '\0')
return 1;
void push(long int symbol) { else
if (top >= MAX - 1) { return 0;
printf("Stack overflow\n"); }
exit(1);

You might also like