Posted By

acecengic on 12/17/14


Tagged

calc posfix


Versions (?)

Postfix C++


 / Published in: C++
 

solver of postfix in C++ calculator

  1. //Haris Cengic
  2. //a program to evaluate a postfix expression.
  3.  
  4.  
  5. #define SIZE 100 //size of the stack
  6. #include <ctype.h> //The ctype.h accepts an int as a param and returns boolean operations any int n for true, 0 for false
  7.  
  8. int vector[SIZE]; //creates a vector of ints, the size of SIZE, 100
  9. int head=-1; //set head at -1 to read input from right to left
  10.  
  11. main() //main method and testing
  12. {
  13. char input[100], ch; //using char to input everything to a vector called 'unput' one char at a time, max 100
  14. int i = 0;
  15. int operatorA = 0;
  16. int operatorB = 0;
  17. printf("\n\n Welcome! Input your expression in POSTFIX: ");
  18. scanf("%s",input);
  19. while( (ch=input[i++]) != '\0') //read while the input isn't null
  20. {
  21. if(isdigit(ch)) push(ch-'0');//isdigit is a built in function in ctype, used in CECS 130
  22.  
  23. else {
  24. operatorB = pop();//if it isn't a digit you define it as an operator and you pop it out of the stack
  25. operatorA = pop();//same
  26.  
  27. switch(ch) //switch statement used from calculator program from CECS 130
  28. { //actually does the calculation and pushes the result to the stack
  29. case '+':push(operatorA+operatorB)
  30. ;break;
  31. case '-':push(operatorA-operatorB)
  32. ;break;
  33. case '*':push(operatorA*operatorB)
  34. ;break;
  35. case '/':push(operatorA/operatorB)
  36. ;break;
  37. } //until eventually the only thing that is left in the stack is the head, or the solution
  38. }
  39. }
  40. printf("\n This was your input: %s\n",input);
  41. printf("\n This is the solution: %d\n",vector[head]);
  42. }
  43.  
  44. //now for the push and pops for the stack
  45. push(int thing) //thing can be +-/* or any number
  46. {
  47. vector[++head] = thing; //add the thing to the top of the stack, aka PUSH
  48. }
  49.  
  50. int pop()
  51. {
  52. return(vector[head--]); //take away the thing at the top of the vector, the head
  53. }

Report this snippet  

You need to login to post a comment.