Q:

C# program to implement stack using structure

0

C# program to implement stack using structure

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to implement a stack using structure is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to implement stack using the structure

using System;

struct Stack
{
    private int[] ele;
    private int top;
    private int max;

    public Stack(int size)
    {
        ele = new int[size];
        top = -1;
        max = size;
    }

    public void Push(int item)
    {
        if (top == max - 1)
        {
            Console.WriteLine("Stack Overflow");
            return;
        }
        else
        {
            ele[++top] = item;
        }
    }

    public int Pop()
    {
        if (top == -1)
        {
            Console.WriteLine("Stack Underflow");
            return -1;
        }
        else
        {
            Console.WriteLine("Poped item is: " + ele[top]);
            return ele[top--];
        }
    }

    public void DisplayStack()
    {
        if (top == -1)
        {
            Console.WriteLine("Stack is Empty");
            return;
        }
        else
        {
            for (int i = 0; i <= top; i++)
            {
                Console.WriteLine("Item[" + (i + 1) + "]: " + ele[i]);
            }
        }
    }
}

class Demo
{
    static void Main()
    {
        Stack S = new Stack(4);

        S.Push(102);
        S.Push(202);
        S.Push(303);
        S.Push(405);
        
        Console.WriteLine("Items are : ");
        S.DisplayStack();

        S.Pop();
        S.Pop();
    }
}

Output:

Items are :
Item[1]: 102
Item[2]: 202
Item[3]: 303
Item[4]: 405
Poped item is: 405
Poped item is: 303
Press any key to continue . . .

Explanation:

In the above program, we created a structure Stack that contains three data members array of elements, "top"  to specify the top-most position of an element of the stack and the "max" to specify the maximum number of elements that can be stored by the stack.

The Stack structure contains Push() and Pop() methods. The Push() method is used to insert the item into the stack. The Pop() method is used to remove an element from the stack.

Now look to the Demo class, the Demo class that contains the Main() method. The Main() method is the entry point for the program. Here, We created the reference of Stack structure and perform Push() and Pop() operations.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Data Structure Solved Programs/Examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to implement Double Stack using structu... >>
<< C# program to implement stack using array...