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");
}
}
}
that code needs to be in a method..
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.