So I have been stuck on this program. Here it is for reference:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int c;
c = getchar();
printf("%d\n", prefix(0, -1, -1, c));
return 0;
}
int prefix(int op, int a, int b, int c){
int x = 0;
printf("%c, %d, %d, %c\n", op, a, b, c);
// Check if char is a operator
if(c == '+' || c == '-' || c == '*' || c == '/')
op = c;
//Parse integers
if(c > 47 && c < 58){
if(c == 48)
c = 0;
if(c == 49)
c = 1;
if(c == 50)
c = 2;
if(c == 51)
c = 3;
if(c == 52)
c = 4;
if(c == 53)
c = 5;
if(c == 54)
c = 6;
if(c == 55)
c = 7;
if(c ==56)
c = 8;
if(c == 57)
c = 9;
if(a == -1)
a = c;
else{
b = c;
}
}
if(c == '\n')
return a;
if(a >= 0 && b >= 0){
if(op == '+'){
x = b;
b = -1;
return a + x;
}
if(op == '-'){
x = b;
b = -1;
return a - x;
}
if(op == '*'){
x = b;
b = -1;
return a * x;
}
if(op == '/'){
x = b;
b = -1;
return a / x;
}
}
if(b == -1)
return prefix(op, a, b, c = getchar());
exit(1);
}
The idea is the program needs to read in an expression from input and evaluate it. The case I am currently working on is "++3 4 3" = 10. I have +3 4 working (it equates to 7). I am not allowed to use built in functions besides that ones I used already or any structs. The idea is to do this recursively, but my problem is after evaluating +3 4 I can't get it to the next step which would be +7 3. Does anyone have any suggestions for how to set up the recursion so the stack variables can be evaluated properly?
essentially the idea is
f(0) = +, -1, -1
f(1) = +, -1, -1
f(2) = +, 3, -1
f(3) = +, 3, 4 = 7
f(2) = +, 7, 3, = 10
f(1) = , 10, -1
f(0) = , 10, -1
main prints 10
So I want to change my b value from -1 to some valid number if a is not null
and I want to change my operator after every evaluation.