using System; using System.Linq; namespace Stack { class Program { // INT? = NULLABLE INT, CAN SET VALUE TO NULL static int?[] numbers = new int?[6]; static int t = -1; static void Main(string[] args) { bool quit = false; // ENDS PROGRAM WHEN TRUE while (!quit) // KEEP RUNNING { // UI STUFF Console.Clear(); Console.WriteLine("Stack Simulator"); Console.WriteLine(" -----------------------"); Console.Write("| "); print(numbers); Console.WriteLine(" -----------------------"); Console.WriteLine("1) Peek"); Console.WriteLine("2) Pop"); Console.WriteLine("3) Push"); Console.WriteLine("4) QUIT"); try { int choice = Convert.ToInt32(Console.ReadLine()); // TAKE USER CHOICE switch (choice) { case 1: peek(numbers); break; case 2: pop(numbers); break; case 3: push(numbers); break; case 4: // END PROGRAM quit = true; break; } } catch { // IF THE USER ENTERS ANYTHING WHICH ISNT AN INT, IT WILL THROW AN ERROR BECAUSE THIS USES A SWITCH STATEMENT // THIS JUST IGNORES THAT continue; } } } static void print(int?[] stack) { // A BEAUTIFULLY FORMATTED PREVIEW OF THE STACK for (int i = 0; i < stack.Length; i++) { Console.Write("{0} | ", stack[i]); } Console.WriteLine(); } static bool overflow(int?[] stack) { if (t >= stack.Length - 1) { // CHECKS IF TOP OF STACK IS LARGER THAN THE STACK ITSELF return true; } else { return false; } } static bool underflow(int?[] stack) { if (t < 0) { // CHECKS IF THE TOP OF THE ARRAY IS LESS THAN 0 return true; } else { return false; } } static void push(int?[] stack) { if (overflow(numbers) == true) { Console.Clear(); Console.WriteLine("Stack Overflow error"); if (stack[t] == 0) { Console.WriteLine("0 still counts as a value, remove it first"); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } else { Console.Clear(); int val; Console.WriteLine("Value to be pushed: "); val = Convert.ToInt32(Console.ReadLine()); t++; // INCREASE THE TOP POINTER BY ONE stack[t] = val; // AND SET IT TO THE VALUE Console.Clear(); Console.WriteLine("{0} successfully added to stack", val); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } static void pop(int?[] stack) { if (underflow(numbers) == true) { Console.Clear(); Console.WriteLine("Stack Underflow error"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } else { stack[t] = null; // SET THE TOP VALUE TO NULL t = t - 1; // AND INDICATE THAT THE TOP VALUE HAS MOVED DOWN Console.Clear(); Console.WriteLine("Top value removed from stack"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } static void peek(int?[] stack) { Console.Clear(); Console.WriteLine("Top Value: {0}", stack[t]); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }