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
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

The index of the 10th position is 9. When (tos==9), that is the highest index is 9, the StackArray is full, which means the last value has been already stored in the 10th position. If you want to have no value stored at the 10th position, the condition has to …

## All 3 Replies

The index of the 10th position is 9. When (tos==9), that is the highest index is 9, the StackArray is full, which means the last value has been already stored in the 10th position. If you want to have no value stored at the 10th position, the condition has to be (tos==8)

thanks alot :)

It is better to use the length attribute of the array to compute positions in the array instead of hardcoding a literal like 9 or 10. If you change the size of the array, your code won't work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.