## For loops and Stacks

A place to discuss the science of computers and programs, from algorithms to computability.

Formal proofs preferred.

Moderators: phlip, Moderators General, Prelates

yitriana
Posts: 2
Joined: Sun Apr 19, 2009 5:59 pm UTC

### For loops and Stacks

Why don't for loops work on stacks?

==
I am to make a program that collapses integers of a stack.

Write a method collapse that takes a stack of integers as a parameter and that collapses it by replacing each successive pair of integers with the sum of the pair. For example, suppose a stack stores these values:

bottom [7, 2, 8, 9, 4, 13, 7, 1, 9, 10] top

collapsed, it is

bottom [9, 17, 17, 8, 19] top

If the stack stores an odd number of elements, the final element is not collapsed. For example, the stack:

bottom [1, 2, 3, 4, 5] top

Would collapse into:

bottom [3, 7, 5] top

==

i tried using a for loop to run through the stack. why won't it work?

Code: Select all

public void collapse (Stack<Integer> s) {
for (int i = 0; i < s.size(); i++)
q.enqueue(s.pop());
while (!q.isEmpty())
s.push(q.dequeue());
while (!s.isEmpty())
q.enqueue(s.pop());
while (q.size() > 1)
s.push(q.dequeue() + q.dequeue());
if (!q.isEmpty())
s.push(q.dequeue());
}

==

however, if i use a while loop inplace of the for loop

Code: Select all

while(!s.isEmpty())
q.enqueue(s.pop());

the program works.

Why doesn't a for loop work on the stack?

Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

### Re: For loops and Stacks

Finding the answer is simple: Just step through the execution using a debugger.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

Posts: 687
Joined: Mon May 05, 2008 2:14 am UTC

### Re: For loops and Stacks

The for loop is doing something different than the while loop.

Think about it. The index of the for loop is increasing while the size of the stack is decreasing. What's your loop condition? What happens?

GalstafSofL
Posts: 7
Joined: Wed Apr 29, 2009 8:53 pm UTC

### Re: For loops and Stacks

for loops do work, you just have to construct them properly. you have a slight bug in your loop, and when you realize it you will slap yourself in the face. the poster above me explained the bug about as well as possible without outright fixing the code.