I have a very Basic Question
Stack<Integer> s=new Stack<integer>();
s.push(New Integer(1));
s.push(New Integer(2));
s.push(New Integer(3));
for(int i=0;i<s.size();i++){
System.out.println("i: "+i+" size:"+s.size());
System.out.print(s.pop());
if(s.size()>=1)
System.out.print(" ->");
}
This results in an output of
3->2->
And Not
3->2->1
Shouldn't the loop run thrice , Is the condition i < s.size()
changing as the stack size changes ?
Yes, because
i
increases while at the same timesize()
decreases. Walk through the logic in your head or on paper.We would normally write such a loop like this: