Search code examples
javaevaluate

A simple stack calculator in C, need help understanding details


String hello = "44+"
int result=0, top=-1;
int []stack = new int[hello.length()];
for(int i=0 ; i<hello.length() ; i++)
{
    char c = s.charAt(i);
    if(c >= '0' && c <= '9')
        stack[++top]=(int)(c-'0');
    else
    {
        int x=stack[top--]; //pop
        int y=stack[top--]; //pop
        switch(c)
        {
            case '+' : result = x + y;
                break;
            case '-' : result = y - x;
                break;
            case '*' : result = x * y;
                break;
            case '/' : result = y / x;
                break;
            default : result = 0;
        }
        stack[++top]=result; //push
    }
}
result = stack[top--]; //pop
return result;

44+ stores 8 -> return result happens and when I print it on the main I get 8 as a output.. which is correct

if I replace this code

    stack[++top]=(int)(c-'0');

with this one

    stack[++top]=(int)(c);

the output looks like this = 104.. the second code looks correct to me but it doesn't give me the correct output

My questions are

  1. why c-'0' is used and not a c only ?
  2. why case '-' : result = y - x is used and not x - y ?
  3. why case '/' : result = y / x is used and not x / y ?

Thanks in advance


Solution

  • A string (for example "44+") contains a set of characters. Each character in a string is represented by a specific code or value. The string "ABC" is represented by the values 65,66,67 (in decimal). The string "ABC0123456789" is represented by the values 65,66,67,48,49,50,51,52,53,54,55,56,57 respectively. Therefore, to get the numerical value of the digit characters ('0' to '9') you have to subtract 48 from the character's code.

    Regarding your 2nd and 3rd questions: Y is the first number pushed on the stack and X is the second number pushed on the stack. Since the operation is supposed to be between the first and second digits, it should be Y-X and Y/X (it should also be Y+X and Y*X but the order doesn't change the result in this case).

    Note that this code won't work well with more than two digits or when the string isn't formatted exactly as in the example.