Suppose I want to return tos = tos-2 , how can I change the code?
tos = tos-2
int pop() { System.out.print("tos = " +tos+" "); if (tos<0) { System.out.println("Stack limit reached .. UNDERFLOW"); return 0;} else { return stck[tos--]; } }
Java does not have a unary decrement by two operator, so you have to split it over two lines:
tos -= 2; return stck[tos + 2];
Or use a temp for reading:
tos -= 2; int returnIndex = tos + 2; return stck[returnIndex];
If you want to revert the position of the array before the change tos (similar to how you did it return stck[tos--] ):
tos
return stck[tos--]
tos-=2; return stck[tos+2];
Otherwise,
tos-=2; return stck[tos];
int pop(){ System.out.print("tos = " +tos+" "); if (tos<0) { System.out.println("Stack limit reached .. UNDERFLOW"); return 0; } else { tos = tos-2; return stck[tos]; } }
int pop(){ System.out.print("tos = " +tos+" "); if (tos<0) { System.out.println("Stack limit reached .. UNDERFLOW"); return 0; } else { tos -=2; return stck[tos]; } }
stop using postfix .: D
int pop() { int tos = 2;//3 System.out.print("tos = " + tos + " "); if (tos < 0) { System.out.println("Stack limit reached .. UNDERFLOW"); return 0; } return stck[tos-=2]; }