×

Stack Using Array

Stack – A Stack is a linear abstract data type used to store elements. It is also called last in first out or first in last out data structure because the newly added element is removed first from the stack and the element added first is removed in last.

The basic operations performed on the stack data structure are push and pop, where push operation is used to add elements at the top of the stack, and pop operation is used to remove the top element of the stack.

In array implementation of stack, the top pointer stores the index value of the latest element added to the stack, known as the top of the stack. It is also known as the static implementation of the stack because here we fix the size of the stack. During the run time it can never be increased.

For Loop in C

The value of the top pointer determines the condition of stack overflow and underflow. When the top pointer stores the maximum possible index value, we can clearly say that the stack is overflowing, and if it is negative, we can say that the stack is underflowing.

The C++ program to implement stack using array as the primitive data type is given below:

// Array implementation of stack in C++
#include <iostream>
using namespace std;


// Defining the stack of size 10
int stack[10];
int n = 10;
int top = -1;


// Push function to push element at the top of the element
void push(int value)
{
    if (top == n - 1)
    {
        cout << "Stack overflow!" << endl;
    }
    else
    {
        top++;
        stack[top] = value;
    }
}


// Pop function to remove the top element from the stack
void pop()
{
    if (top == -1)
    {
        cout << "Stack underflow!";
    }
    else
    {
        cout << "The popped element is " << stack[top] << endl;
        top--;
    }
}


// Function to search element in the stack
void search_in_stack(int value)
{
    if (top == -1)
    {
        cout << "No element in stack" << endl;
    }
    for (int i = 0; i <= top; i++)
    {
        if (stack[i] == value)
        {
            cout << value << " is present in the stack!" << endl;
            return;
        }
    }
    cout << value << " is not present in the stack!" << endl;
}


// Function to display all the elements of the stack
void traverse()
{
    if (top == -1)
    {
        cout << "No element in stack" << endl;
        return;
    }
    cout << "Element of the stack are : ";
    for (int i = 0; i <= top; i++)
    {
        cout << stack[i] << " ";
    }
    cout << endl;
}


// Driver function
int main()
{


    cout << "Enter 1 to push element in the stack." << endl;
    cout << "Enter 2 to pop element from the stack." << endl;
    cout << "Enter 3 to search element in the stack." << endl;
    cout << "Enter 4 to print all the element of the stack." << endl;
    cout << "Enter 5 to exit from the program." << endl;


    int choice, x;
    do
    {
        cout << "Enter your choice : ";
        cin >> choice;


        switch (choice)
        {
        case 1:
            cout << "Enter the value to push in the stack : ";
            cin >> x;
            push(x);
            break;
        case 2:
            pop();
            break;
        case 3:
            cout << "Enter the value to search in the stack : ";
            cin >> x;
            search_in_stack(x);
            break;
        case 4:
            traverse();
            break;
        case 5:
            cout << "Exited Successfully!";
            break;
            ;
        default:
            cout << "Wrong choice!" << endl;
            break;
        }


    } while (choice != 5);


    return 0;
}

The sample output of the above program is given below:

Enter 1 to push anelement in the stack.
Enter 2 to pop an element from the stack.
Enter 3 to search an element in the stack.
Enter 4 to print all the elements of the stack.
Enter 5 to exit from the program.
Enter your choice : 1
Enter the value to push in the stack : 12
Enter your choice : 1
Enter the value to push in the stack : 34
Enter your choice : 1
Enter the value to push in the stack : 5
Enter your choice : 1
Enter the value to push in the stack : 67
Enter your choice : 1
Enter the value to push in the stack : 23
Enter your choice : 2
The popped element is 23
Enter your choice : 3
Enter the value to search in the stack : 45
45 is not present in the stack!
Enter your choice : 3
Enter the value to search in the stack : 23
23 is not present in the stack!
Enter your choice : 4
Element of the stack are : 12 34 5 67 
Enter your choice : 5
Exited Successfully!

In the above program, the main function is programmed so that the program will be run according to the user’s choice. The stack operations or function calls will be done as per the user’s choice. Such types of programs are also known as menu-driven programs.

  • POP operation – The POP operation is used to pop the top element of the stack, and the code of the same is explained below:

Here, we first check whether the stack is already empty or not, and the condition for the same is top = -1. If the stack is empty, we throw a warning that the stack is underflowing and no elements if present in the stack to pop. If the stack is not empty, we pop the top element by printing its value, and we decrement the value of the top pointer by 1, and the top pointer will store the index value of the very previous element. Here, we actually don’t delete the value from the stack or array, we forget the top element and make the very previous element as the top element of the stack.

void pop()
{
    if (top == -1)
    {
        cout << "Stack underflow!";
    }
    else
    {
        cout << "The popped element is " << stack[top] << endl;
        top--;
    }
}
  • PUSH Operation – The PUSH operation is used to add elements at the top of the stack, and the code of the push operation is explained below:
void push(int value)
{
    if (top == n - 1)
    {
        cout << "Stack overflow!" << endl;
    }
    else
    {
        top++;
        stack[top] = value;
    }
}

To perform the push operation on a stack, we first check whether the stack is already full or not, and the condition for the same is top = n-1, where n is the size of the array. If the stack is already full, we can’t add an element to it, and we throw a warning of ‘stack overflow’. If the stack is not full, we first increment the value of the top pointer by 1 and add the new element at the top index. The newly added element becomes the new top element of the stack.

  • Searching is stack – One cannot easily search for an element in a stack. As the basic operations performed on a stack are push and pop. The code for the search element in a stack is explained below:
void search_in_stack(int value)
{
    if (top == -1)
    {
        cout << "No element in stack" << endl;
    }
    for (int i = 0; i <= top; i++)
    {
        if (stack[i] == value)
        {
            cout << value << " is present in the stack!" << endl;
            return;
        }
    }
    cout << value << " is not present in the stack!" << endl;
}

We are using the linear search here, as we have implemented our stack using an array. We are traversing the stack from the 0th index to the top index. We match the input value one by one, and if we find the element, we give the output as “the element is present in the stack”. If not, we give the output as “the element is not present”. Before searching for the element, we first check the stack underflow condition.

  • Stack Traversal – There are two methods to traverse a stack. In the first method, we pop all the stack elements. In the second method, we traverse the stack internally depending on which primitive data structure is used to implement that stack without popping any element from it. The code of stack traversal is explained below:
void traverse()
{
    if (top == -1)
    {
        cout << "No element in stack" << endl;
        return;
    }
    cout << "Element of the stack are : ";
    for (int i = 0; i <= top; i++)
    {
        cout << stack[i] << " ";
    }
    cout << endl;
}

Here, we are internally traversing all the elements starting from the 0th index to the top index and printing all the values as the program’s output without removing any element from the stack. Before traversing the stack, we have checked the condition of stack underflow.


Related Topics

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Introduction to 1D-Arrays

One Dimensional Array Technical Definitions The simplest version of an Array is a One-Dimensional Array, in which the items are stored linearly and may be accessed individually by supplying the index value...

6 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Hashing and its Applications

Hashing Hashing refers to transforming plain text data in such a way that even if it is leaked for some reason, no one would be able to make sense of it....

6 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

What is a 2-3 Tree in Data Structure?

Tree Data structure The information about the tree is self-explanatory. Trees are ordered and, therefore, not linear. But they are actually designed differently. Tree A node-based data model that represents and...

5 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Diameter of a Binary Tree

Implementation We will now witness the implementation of the diameter of a binary tree. // Creating a recursive and challenging C program that will help us determine the diameter of a binary...

4 minutes read.

Strings in Data Structures

Strings and functions in C A string is a collection of characters. We'll learn how to declare strings, operate with strings in C programming, and use pre-defined string handling routines. We'll look...

7 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

Structure and Union Data Structure

The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure...

4 minutes read.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

Application of 2D array - Sparse Matrix

2D Arrays Application - Sparse Matrix A matrix is a two-dimensional data item consisting of m rows and n columns, with a total of m x n values. A sparse matrix...

7 minutes read.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

Convert binary tree to a doubly linked list

Implementation //creating a C++ program for the transition of a binary tree into a linked list. #include <iostream> using namespace std; /* Firstly, let’s create a binary tree that will help us in setting...

4 minutes read.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.