Reputation: 99
The first foreach method gets several errors. I can't figure out why and it seems like it should work...
foreach - invalid token 'foreach' in class, struct, or interface member declaration.
This prints out 1 2 3 4 1 2 3 4 1 2 3 4.
the 2nd foreach method. How does this work? I think it just iterates through each number one at a time in order. The confusion comes in where it is the same code, but stack instead of queue. The 2nd foreach prints out 4 3 2 1. Why is this?
namespace Cards
{
class Class1
{
Queue numbers = new Queue();
foreach (int number in new int[4]{1,2,3,4})
{
numbers.Enqueue(number);
Console.WriteLine(number + " has joined the queue");
}
foreach (int number in numbers)
{
Console.WriteLine(number);
}
while(numbers.Count > 0)
{
int number = (int)numbers.Dequeue();
Console.WriteLine(number + " has left the queue");
}
}
}
Upvotes: 0
Views: 151
Reputation: 106
Well! In your second loop you are trying to print all the elements in the collection. 1) In case of Queue the objects are stored as it is added. So you get the same answer like in your first loop (FIFO) 2) In case of Stack the objects will be stored in the reverse order so when you pop the object from the collection you can remove the last object which you inserted. (LIFO)
Hope this helps.
Upvotes: 0
Reputation: 44298
that code needs to be in a method..
class Class1
{
public void DoQstuff()
{
Queue numbers = new Queue();
foreach (int number in new int[4]{1,2,3,4})
{
numbers.Enqueue(number);
Console.WriteLine(number + " has joined the queue");
}
foreach (int number in numbers)
{
Console.WriteLine(number);
}
while(numbers.Count > 0)
{
int number = (int)numbers.Dequeue();
Console.WriteLine(number + " has left the queue");
}
}
}
and the whole thing works as expected if you run it
Queues work, first in, first out..... so 1 was first in, so its first out
Stacks work, first in, last out, so 1 was the first thing in, so it will be the last thing out
like, if you line up to be served at a coffee shop, you have to wait in queue till your turn, first person in the queue, is the first person served.
stacks is like stacking books on top of each other....you can't take the first thing off the stack until you unstack all the things on top of it.
Upvotes: 3
Reputation: 1
A stack does not follow the same heuristics as a queue. In a queue, what goes in first, also comes out first. In a stack, you're looking at FILO (First In, Last Out).
That is why you see the reverse happening, that is, 4,3,2,1.
Upvotes: 0