×

Implementation of Stack Using Array

Before moving forward to implementation of stack using array, we must know more about stack.

A stack is defined as a linear data structure that follows LIFO (Last In First Out) method, that means the elements added at end of the stack will be removed first and the new order cannot be updated or changed.

A stack can be implemented in multiple ways.

Stack implementation using an array includes the following operation methods:

  • Push (): It adds the element at the top of the stack in O (n) time.
  • Pop (): It removes the top element from stack in O (n) time.
  • Peak (): It is used for accessing the top element of stack by returning it in O(n) time.

Push Operation: Adding an Element to the Stack

This operation adds an element at the top of the stack and is known as the push operation.

It works in the following steps:

  1. It increments the top variable (the pointer that points to the top of the stack) and then starts to point towards a new memory location.
  2. Then, it adds the element at the new top, the new memory location and this increases the size of the stack.

Algorithm:

start
if top == n;                                                                 ( implies the stack is full)
else
        t = t + 1;                                                                  (t=top)
stack (t)  = new__item;
stop

Time Complexity:

Push operation in stack occurs in O(1) time.

Pop Operation: Deleting an Element from the Stack

This operation fetches the value by removing it from the top of the stack and is known as the pop() operation.

In the stack data structure while implementation of pop () operation in the array, instead of removing the data from the stack, the pointer shifts to a lower position in the stack and points to the further value, and similarly the size decreases.

*The pop () function returns the removed value.

Algorithm:

start
if t == 0;                                                                            (that means the stack is empty)
else
top_item = stack(t);  
        t = t - 1;  
stop

Peek Operation: Accesses the Top Element of Stack

By peek operation, the value of the element which is present at the top of the stack is returned without making any changes to it. If we try to use peek over an empty stack, then the stack goes underflow.

Algorithm:

start
if t == -1;                                                          (that means stack is empty)
else
item = stack[t];   
return item;  
stop

Code of Stack using Array in C:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
int top = -1, inp_array[SIZE];
void push();
void pop();
void peek();


int main()
{
int choice;


while (1)
    {
printf("\nPerform operations on the stack:");
printf("\n1.Push the element\n2.Pop the element\n3.peek\n4.End");
printf("\n\nEnter the choice: ");
scanf("%d", &choice);


switch (choice)
        {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
exit(0);


default:
printf("\nInvalid choice!!");
        }
    }
}


void push()
{
int x;


if (top == SIZE - 1)
    {
printf("\nOverflow!!");
    }
else
    {
printf("\nEnter the element to be added onto the stack: ");
scanf("%d", &x);
top = top + 1;
inp_array[top] = x;
    }
}


void pop()
{
if (top == -1)
    {
printf("\nUnderflow!!");
    }
else
    {
printf("\nPopped element: %d", inp_array[top]);
top = top - 1;
    }
}


void peek()
{
if (top == -1)
    {
printf("\nUnderflow!!");
    }
else
    {
printf("\nElements present in the stack: \n");
for (int i = top; i>= 0; --i)
printf("%d\n", inp_array[i]);
    }
}

Output:

Perform operations on the stack:
1.Push the element
2.Pop the element
3.peek
4.End


Enter the choice:

Now, you can enter the choices. Suppose, you enter 1 (push the element). Now, you enter the element to be added onto the stack is 3. So, the program execution, when you enter the choice 3 (peek the element), you can see that it shows “element present in the stack is 3.

Enter the choice: 1
Enter the element to be added onto the stack: 3
Perform operations on the stack:
1.Push the element
2.Pop the element
3.peek
4.End


Enter the choice: 3
Elements present in the stack: 
3


Perform operations on the stack:
1.Push the element
2.Pop the element
3.peek
4.End


Enter the choice:  

Java Example:

// Stack implementation in Java


class Stack {


  // store elements of stack
private int arr[];
  // represent top of stack
private int top;
  // total capacity of the stack
private int capacity;


  // Creating a stack
Stack(int size) {
    // initialize the array
    // initialize the stack variables
arr = new int[size];
capacity = size;
top = -1;
  }


  // push elements to the top of stack
public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");


      // terminates the program
System.exit(1);
    }


    // insert element on top of stack
System.out.println("Inserting " + x);
arr[++top] = x;
  }


  // pop elements from top of stack
public int pop() {


    // if stack is empty
    // no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");
      // terminates the program
System.exit(1);
    }


    // pop element from top of stack
return arr[top--];
  }


  // return size of the stack
public int getSize() {
return top + 1;
  }


  // check if the stack is empty
public Boolean isEmpty() {
return top == -1;
  }


  // check if the stack is full
public Boolean isFull() {
return top == capacity - 1;
  }


  // display elements of stack
public void printStack() {
for (int i = 0; i<= top; i++) {
System.out.print(arr[i] + ", ");
    }
  }
public static void main(String[] args) {
    Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);


System.out.print("Stack: ");
stack.printStack();


    // remove element from stack
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
  }
}

Output:

Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3, 
After popping out 1, 2,

.


Related Topics

List of Union Territories of India

India now has 28 states and 8 union territories. Jammu and Kashmir, the previous state, was split into two Union Territories: J&K and Ladakh. Reorganization legislation enacted by the parliament...

11 minutes read.

Best Examples of Backend Technologies

What is a Backend Technology? Backend technology works on the server side of a website. It helps us to ensure that data is organized so everything on the client side of...

9 minutes read.

Explain dobereiner's triad

Dobereiner's Law of Triads with Example There have been several attempts since the beginning of time to organize the elements according to their qualities. Many theories to categorize the elements emerged...

4 minutes read.

List of Popular English Songs

1. Memories Memories by Maroon 5 will make your heart skip a beat and surely make you jump into your memories. It is a sweet simple Melody that will fill your...

6 minutes read.

List of Presidents in India

Introduction After years of colonized British control, our country was eventually able to break free in 1947. The year of independence, 1947, was when the entire country came together into a...

5 minutes read.

Top 5 Programming Languages for Backend Development

What is Backend Development? As we all know that a website has two important components, which are frontend and backend. The frontend is the part where the user directly interacts with and...

3 minutes read.

List of South Indian Actress

Introduction In the old days, India had only one famous film industry, Bollywood, But because of our different languages and culture, we needed to produce films in different languages. And as...

6 minutes read.

Basics of Animation

The fundamental of basic of animation started after the 1930’s when Walt Disney noticed that the animation level was based on new storylines. Some classes are set up under the...

8 minutes read.

Top 10 IDEs for Programmers

IDE stands for “Integrated Development Environment” is software where programmers can write the code for their apps. Debuggers and compilers are typically included with IDEs, which greatly simplifies the job...

5 minutes read.

The Longest River in India

India is known as the "Land of Rivers" because of the many rivers run here. Himalayan Rivers, the rivers that originate in the Himalayas, and Peninsular Rivers, the rivers that...

6 minutes read.

Defect Triage Meeting

The main application of Defect Triage (sometimes referred to as Bug Triage) is in software testing. It is necessary to describe the faults' importance and seriousness. The severity of a...

3 minutes read.

Properties of Fourier Transform

What is Fourier Transform? It is a type of mathematical function that is used to split a waveform. This waveform is a time function that is made up of frequencies. The...

6 minutes read.

Largest State of India

There are twenty-eight states and eight union territories in India. Each of these states and territories has its geographical location and population. In this article, we are going to look...

4 minutes read.

List of Universities in Canada

Universities provide higher education, and it offers a research fellowship as well as undergraduate and graduate programs. The Latin phrase Universitas ET scholarium, which means "community of teachers & scholars," is...

7 minutes read.

Types of Web Browsers

What is a Web Browser? The application software used to access the internet facilities provided by World Wide Web (WWW) is called a Web Browser. When a user wants information from the...

4 minutes read.

List of Fruits

The portion of a plant that develops from the flower is called a fruit. It might be pulpy or dry. Fruits are made up of a plant's seeds. Except for...

5 minutes read.

What is a Burp Suite?

A set of tools for web application penetration testing is called the Burp Suite. It was created by a business called Portswigger, which is also the alias of the company's...

4 minutes read.

Functional Programming Paradigm

Introduction A paradigm for creating computer programs using expressions & functions while maintaining the state or data is known as functional programming. Functional programming aims to develop code that is simpler...

3 minutes read.

List of Countries and Capitals

Introduction The modern world is divided into several countries based on various historical and political reasons. Some countries in the modern world have democracy, monarchy, dictatorship, etc. All these countries have...

4 minutes read.

List of South American Countries

South America got its name because it encompasses the whole southern portion of the supercontinent of the Americas. The Pacific Ocean encircles it on its western side, the Atlantic Ocean...

8 minutes read.