CS 3723
 Programming Languages 
   Translate to RPN  


Translate Arithmetic Expressions to RPN: The code that was added to carry out the translation is given in red.

Translate to RPN
/* arith.rpnc: translate to RPN
 * grammar:
 *   P ---> E '#'
 *   E ---> T {('+'|'-') T}
 *   T ---> S {('*'|'/') S}
 *   S ---> F '^' S | F
 *   F ---> char | '(' E ')'
 */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char next;
void P(void);
void E(void);
void T(void);
void S(void);
void F(void);
void error(int);
void scan(void);

void P() {
   scan();
   E();
   if (next != '$') error(1);
   else printf("$");
   // else printf("\nSuccess");
}

void E(void) {
   char save;
   T();
   while (next == '+' || next == '-') {
      save = next;
      scan();
      T();
      printf("%c", save);
   }
}

void T(void) {
   char save;
   S();
   while (next == '*' || next == '/') {
      save = next;
      scan();
      S();
      printf("%c", save);
   }
}
void S(void) {
   F();
   if (next == '^') {
      scan();
      S();
      printf("^");
   }
}

void F(void) {
   if (isalpha(next)) {
      printf("%c", next);
      scan();
   }
   else if (next == '(') {
      scan();
      E();
      if (next == ')') scan();
      else error(2);
   }
   else {
      error(3);
   }
}

void scan(void) {
   while (isspace(next = getchar()))
       ;
   // printf("%c", next);
}

void error(int n) {
   printf("\nERR#: %i, next: %c\n",
      n, next);
   exit(1);
}

int main() {
   P();
   printf("\n");
}

Here is output from this program:

Run of C Program
a+b*c$
abc*+$

a*b+c$
ab*c+$

(a+b)*c$
ab+c*$

a*b*c*d$
ab*c*d*$

a^b^c^d$
abcd^^^$
a+b*c^d*e+f$
abcd^*e*+f+$

a^b*c+d*e^f$
ab^c*def^*+$

(((a)+(((b*(c^d))))))$
abcd^*+$

(same with redundant
parens, that is, all
parens, removed):
a+b*c^d$
abcd^*+$


Revision date: 2014-01-22. (Please use ISO 8601, the International Standard.)