C# program to implement stack using array

In this C# program, we will learn about stack implementation. Here, we are implementing a stack using array.
Submitted by IncludeHelp, on November 21, 2017 [Last updated : March 27, 2023]

Stack Using Array

Stack follows LIFO (Last In First Out) property, it means last inserted elements, deleted first. There are two basic operations are performed in Stack:

  1. PUSH : To insert an element into stack.
  2. POP : To get and remove element from stack.

In stack we use array to store elements, and a pointer top, that points top most element in stack.

Stack implementation using array in C#

using System;

namespace ConsoleApplication1
{
    class 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 element is: " + ele[top]);
                return ele[top--];
            }
        }

        public void printStack()
        {
            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 Program
    {
        static void Main()
        {
            Stack S = new Stack(5);

            S.push(10);
            S.push(20);
            S.push(30);
            S.push(40);
            S.push(50);

            Console.WriteLine("Items are : ");
            S.printStack();

            S.pop();
            S.pop();
            S.pop();
        }
    }
}

Output

Items are :
Item[1]: 10
Item[2]: 20
Item[3]: 30
Item[4]: 40
Item[5]: 50
Poped element is: 50
Poped element is: 40
Poped element is: 30

C# Data Structure Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.