w3resource

C#: Check if an element is present or not in a stack

C# Sharp Stack: Exercise-11 with Solution

Write a C# program to implement a stack that checks if a given element is present or not in the stack.

Sample Solution:

C# Code:

using System;

// Implementation of a Stack data structure
public class Stack
{
    private int[] items; // Array to hold stack elements
    private int top;     // Index representing the top of the stack

    // Constructor to initialize the stack with a specified size
    public Stack(int size)
    {
        items = new int[size]; // Initializing the array with the given size
        top = -1;              // Initializing top to -1, indicating an empty stack
    }

    // Method to check if the stack is empty
    public bool IsEmpty()
    {
        return top == -1; // Returns true if top is -1 (empty stack), otherwise false
    }

    // Method to check if the stack is full
    public bool IsFull()
    {
        return top == items.Length - 1; // Returns true if top is at the last index of the array (full stack)
    }

    // Method to push an element onto the stack
    public void Push(int item)
    {
        if (IsFull())
        {
            Console.WriteLine("Stack Full!"); // Displays a message if the stack is full
            return;
        }

        items[++top] = item; // Inserts the item at the incremented top index
    }

    // Method to pop an element from the stack
    public int Pop()
    {
        if (IsEmpty())
        {
            Console.WriteLine("Stack underflow"); // Displays a message if the stack is empty
            return -1;
        }

        return items[top--]; // Removes and returns the top element by decrementing top
    }

    // Method to peek at the top element of the stack without removing it
    public int Peek()
    {
        if (IsEmpty())
        {
            Console.WriteLine("Stack is empty"); // Displays a message if the stack is empty
            return -1;
        }

        return items[top]; // Returns the element at the top index without removing it
    }

    // Method to get the current size of the stack
    public static int Size(Stack stack)
    {
        return stack.top + 1; // Returns the number of elements in the stack
    }

    // Method to check if an element is present in the stack
    public static bool Contains(Stack stack, int item)
    {
        if (stack == null || stack.IsEmpty())
            return false;

        bool found = false;
        Stack tempStack = new Stack(Size(stack)); // Temporary stack to store elements

        // Check if the item is present while preserving stack order
        while (!stack.IsEmpty())
        {
            int current = stack.Pop(); // Remove an element from the original stack

            if (current == item)
            {
                found = true;
                break; // Item found, exit loop
            }

            tempStack.Push(current); // Store the removed element in the temporary stack
        }

        // Restore original stack order
        while (!tempStack.IsEmpty())
        {
            stack.Push(tempStack.Pop()); // Restore elements to the original stack
        }

        return found; // Return whether the item was found in the stack
    }

    // Method to display the stack elements
    public static void Display(Stack stack)
    {
        if (stack.IsEmpty())
        {
            Console.WriteLine("Stack is empty");
            return;
        }

        Console.WriteLine("Stack elements:");
        for (int i = stack.top; i >= 0; i--)
        {
            Console.Write(stack.items[i] + " "); // Displays each element in the stack
        }
    }
}

// Main class to demonstrate the functionality of the Stack class
public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Initialize a stack:");
        Stack stack = new Stack(10); // Creating a stack with a size of 10

        Console.WriteLine("Input some elements onto the stack:");
        stack.Push(10);
        stack.Push(50);
        stack.Push(30);
        stack.Push(40);
        stack.Push(50);
        stack.Push(50);
        Stack.Display(stack); // Displaying the elements in the original stack

        int value = 50; // Value to check if present in the stack
        bool result = Stack.Contains(stack, value); // Checking if the value is present in the stack
        Console.WriteLine("\nCheck {0} is present in the above stack: {1}", value, result);

        value = 20; // Another value to check if present in the stack
        result = Stack.Contains(stack, value); // Checking if the value is present in the stack
        Console.WriteLine("\nCheck {0} is present in the above stack: {1}", value, result);
    }
}

Sample Output:

Initialize a stack:
Input some elements onto the stack:
Stack elements:
50 50 40 30 50 10 
Check 50 is present in the above stack: True

Check 20 is present in the above stack: False

Flowchart:

Flowchart: Check if an element is present or not in a stack.
Flowchart: Check if an element is present or not in a stack.
Flowchart: Check if an element is present or not in a stack.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Count specified element in a stack.
Next: Remove duplicates from a given stack.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.