in this program i've pushed 10 values into array but i use the condition if (tos==9)
which means no value should be stored at 10th position but when i am storing values,
for (int i=1;i<=10;i++)
first.push(i);
class Stack{
int StackArray[] = new int[10];
int tos;
Stack(){
tos=-1;
}
public void push(int value){
if (tos==9) // no value should be stored on 10th position
System.out.print ("Stack already Full..!");
else
StackArray[++tos] = value;
}
public int pop(){
if (tos==-1){
System.out.print ("Stack is Empty");
return 0;
}
else
return StackArray[tos--];
}
}
class Stack1{
public static void main (String args[]){
Stack first = new Stack();
for (int i=1;i<=10;i++)
first.push(i);
for (int i=1;i<=10;i++)
System.out.println("tos= " + first.tos +", " + first.pop());
}
}
why the value is stored at 10th position ???
Output:
tos= 9, 10
tos= 8, 9
tos= 7, 8
tos= 6, 7
tos= 5, 6
tos= 4, 5
tos= 3, 4
tos= 2, 3
tos= 1, 2
tos= 0, 1