Ho3in
stack
The question given by the teacher is as follows:
Question 1
Write a program that reads n integers from the input, then puts them on a stack, then clears the numbers in the stack and puts them on the output. By presenting
Something like this but this seems to be used with a class or advanced, for example, statics before defining variables I don't want to be
using System;
class Program
{
static int[] stack;
static int top = -1;
static int n;
// Push function to add an element to the stack
static void Push(int k)
{
if (top < n - 1)
{
stack[++top] = k;
}
else
{
Console.WriteLine("The stack is full.");
}
}
// Pop function to remove an element from the stack
static int? Pop()
{
if (top == -1)
{
Console.WriteLine("The stack is empty.");
return null; // Return null instead of throwing an error
}
return stack[top--];
}
static void Main()
{
Console.WriteLine("Enter the number of numbers:");
n = int.Parse(Console.ReadLine());
stack = new int[n];
// Pushing numbers onto the stack
for (int i = 0; i < n; i++)
{
Console.Write($"Enter number {i + 1}: ");
int num = int.Parse(Console.ReadLine());
Push(num);
}
// Popping numbers from the stack and displaying them
Console.WriteLine("Numbers popped from the stack:");
int? poppedNumber;
while ((poppedNumber = Pop()) != null)
{
Console.WriteLine(poppedNumber);
}
}
}
46 replies