Introduction Code {codecitation class="brush: csharp; gutter: true;" width="650px"} using System; using System.Collections.Generic; using System.Text;
namespace Stackconcept { class Program {
/*an stack array is created of size 5*/
int[] stack_arr = new int[5];
/*top denotes the top element of stack..for example
we enter 1,2,3 in this case 3 is top..when stack is empty then top is -1*/
int top = -1;
/*push function is created to understand why parameter is taken
* look at its calling in the switch case*/
public void push(int item)
{
/*now top element become 0*/
top = top + 1;
/*at 0 memory location of stack_arr item is stored*/
stack_arr[top] = item;
}
public void pop()
{
/*it will display the topmost element or
* the last number enterded by the user */
Console.WriteLine("pop data ="+stack_arr[top]);
/*here top decrement so that the next value can be displayed
for example---1234..here it will first display 4 then top is reduced by 1
now it will display 3..so similarly it will display all numbers*/
top = top - 1;
Console.ReadLine();
}
public void display()
{
/*Here condition is check to ensure that the stack is empty or not*/
if (top == -1)
{
Console.WriteLine("Stack is empty");
Console.ReadLine();
}
else
{
Console.WriteLine("Stack elements are ");
/*to diplay the basic rule is last in first out means
the last no. entered is the first on to come out...
for example u hv entered 1,2,3,4 it will display
4,3,2,1*/
for (int i = top; i >= 0; i--)
{
Console.Write("<"+(i+1)+">");
Console.WriteLine(stack_arr[i]);
Console.ReadLine();
}
}
}
static void Main(string[] args)
{
Program obj = new Program();
/*this is how we create menu in c#*/
do
{
/*clear is used to keep the menu still now allowing to repet itself*/
Console.Clear();
Console.WriteLine("******************************");
Console.WriteLine("**** Main Menu ********");
Console.WriteLine("1.push ****");
Console.WriteLine("2.pop ****");
Console.WriteLine("3.Display ****");
Console.WriteLine("******************************");
Console.WriteLine("Enter your choice ");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
{
Console.WriteLine("Enter a number");
int num = int.Parse(Console.ReadLine());
obj.push(num);
break;
}
case 2: { obj.pop(); break; }
case 3: { obj.display(); break; }
}
} while (true);
/*Thanks for reading the commnets hope u have understood its concept*/
}
}
}
{/codecitation} Thank you Bhandari |