Ho3in
Ho3in
CC#
Created by Ho3in on 3/8/2025 in #help
stack
This is the form of the question I wrote : Write a program that reads n integers from the input, places them on a stack, then clears the numbers from the stack and outputs them. ! I want to keep this short and simple, without classes or objects. :vibin: ! But one more thing: use a question mark for the pop function, so that it doesn't throw an error when it returns null . code : class Program {
private int n; private int[] stack; private int top = -1; public Program(int size) { n = size; stack = new int[n]; } public void Push(int k) { if (top == n - 1) { Console.WriteLine("The stack is full."); return; } stack[++top] = k; } public int Pop() { if (top == -1) { Console.WriteLine("The stack is empty.");
return -1; } return stack[top--]; } static void Main() { Console.WriteLine("Enter the number of numbers:"); int n = int.Parse(Console.ReadLine()); Program p = new Program(n); for (int i = 0; i < n; i++) { Console.Write($"عدد {i + 1}: "); int num = int.Parse(Console.ReadLine()); p.Push(num); } Console.WriteLine("Numbers popped from the stack:"); while (p.top >= 0) { Console.WriteLine(p.Pop()); } } }
46 replies