×

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

Heap Sort vs Merge Sort

In this article, we are going to discuss the Heap Sort, Merge sort and the difference between them. What is Heap Sort? Heap – A heap is an abstract data type categorised...

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.

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.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Extended Binary Tree

An extended binary tree is a binary tree in which all the NILL subtrees present mainly in the original trees are exchanged with the special nodes that are primarily known...

3 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 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.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

5 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.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Preorder Traversal of Binary Trees

In general, Stack, Array, Queue, and other linear data structures only have one way to traverse the data. However, there are numerous ways to traverse through the data in a hierarchical...

3 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 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 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.

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 minutes read.