Stack with arrays
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C# program that simulates the operation of a stack using an array of integers. There will be a class called Stack with 2 properties, an array of integers and an integer to store the current position of the stack.
The stack must have a constructor where the size will be specified per parameter and two methods, one for Push() and one for Pop() the values. Remember that the new values are queued at the beginning of the stack and the last ones are unstacked.
To test, create a Stack object in the program's Main and try to stack and unstack some values.
Input
Output
Solution
using System;
public class StackArrays
{
public static void Main(string[] args)
{
int size = 2;
Stack stack = new Stack(size);
int val1 = 7,
val2 = 1;
stack.Push(val1);
stack.Push(val2);
val1 = stack.Pop();
val2 = stack.Pop();
Console.WriteLine(val1);
Console.WriteLine(val2);
}
}
public class Stack
{
private int[] stack;
private int position;
public Stack(int size)
{
position = 0;
stack = new int[size];
}
public void Push(int value)
{
stack[position] = value;
position++;
}
public int Pop()
{
if (position > 0)
{
position -= 1;
return stack[position];
}
return 0;
}
}