K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition)
C Program to evaluate reverse Polish expression from the command line, where each operator or operand is a separate argument.
For example:expr 2 3 4 + * evaluates 2 X (3 + 4). Read more about C Programming Language .
/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
double stack[MAX];
int stack_height = 0;
void panic(const char *msg) {
fprintf(stderr, "%sn", msg);
exit(EXIT_FAILURE);
}
void push(double value) {
if (stack_height == MAX)
panic("stack is too high!");
stack[stack_height] = value;
++stack_height;
}
double pop(void) {
if (stack_height == 0)
panic("stack is empty!");
return stack[--stack_height];
}
int main(int argc, char **argv) {
int i;
double value;
for (i = 1; i < argc; ++i) {
switch (argv[i][0]) {
case ' ':
panic("empty command line argument");
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
push(atof(argv[i]));
break;
case '+':
push(pop() + pop());
break;
case '-':
value = pop();
push(pop() - value);
break;
case '*':
push(pop() * pop());
break;
case '/':
value = pop();
push(pop() / value);
break;
default:
panic("unknown operator");
break;
}
}
printf("%gn", pop());
return 0;
}
Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.
To get regular updates on new C programs, you can Follow @c_program
You can discuss these programs on our Facebook Page. Start a discussion right now,
our page!
Share this program with your Facebook friends now! by liking it
(you can send this program to your friend using this button)
Like to get updates right inside your feed reader? Grab our feed!