I have an array with six values in it {1, 2, 3, 4, 5, 6}. I have been able to successfully push the values into a stack using a for loop. I am supposed to also write a for loop and pop each value from the stack until there is only one left. I can't find an example of it anywhere. Help, please?
int[] numbers = new int[] {1, 2, 3, 4, 5, 6};
Stack<int> myStack = new Stack<int>();
for (int i = 0; i <numbers.Length; i )
{
mystack.Push(numbers[i]);
}
foreach(int item in myStack)
{
Console.Write(item ", ");
}
This prints the pushed values in the array. We have been using the other properties such as Peek and Count with stack as well. I don't have an issue with those. I don't have an issue using Pop for a single value either.
Console.WriteLine("The value popped from the stack is: {0} ", myStack.Pop());
My issue is trying to use a for loop to pop each item from the stack one by one. My brain isn't translating this well at all. I have looked for examples. I have not been able to find one using a for loop.
CodePudding user response:
you can use the below code.
int count = myStack.Count;
for (int i = 1; i < count; i )
{
Console.WriteLine("The value popped from the stack is: {0} ", myStack.Pop());
}
CodePudding user response:
// check stack count
while (myStack.Count > 1)
{
// console
Console.WriteLine($@"POP VALUE: {myStack.Pop()}");
}
CodePudding user response:
while (myStack.Count > 1)
{
Console.WriteLine("The value popped from the stack is: {0} ", myStack.Pop());
}
CodePudding user response:
for (int i = myStack.Count; i > 0; i--)
{
Console.WriteLine($"The value popped from the stack is: {myStack.Pop()}");
}
To use a for loop with a stack you want to use it in a descending manner, while initializing the loop variable to the count in the stack. If you use the stack length as the conditional it will check against the current count every time and stop prematurely