in Doing Books

The C Programming Language (TCPL): Chapter 5

Exercise 5-10. Write a program expr, which evalutes a reverse Polish expression from the command line, where each operator or operand is a separate argument. For example, expr 2 3 4 + * evalutes 2 x (3 + 4).

#include
#include
#include

#define STACKSIZE 1024

double stack[STACKSIZE];
int stackn = 0;

double pop()
{
return stack[--stackn];
}

void push(double x)
{
stack[stackn++] = x;
}

int main(int argc, char *argv[])
{
int i;
double value = 0;

for(i = 1; i < argc; i++) { push(atof(argv[i])); float tmp; if(strlen(argv[i]) < 2) { if(argv[i][0] == '+') { pop(); /* removes operator */ push(pop() + pop()); } if(argv[i][0] == '-') { pop(); tmp = pop(); push(pop() - tmp); } if(argv[i][0] == '*') { pop(); push(pop() * pop()); } if(argv[i][0] == '/') { pop(); tmp = pop(); if (tmp != 0.0) { push(pop() / tmp); } else { printf("DIV BY 0n"); return 1; } } } } printf("%.2fn", pop()); return 0; }

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.