Stack Implementation Using Array in C: Data Structure, Algorithm, and C Program

stack implementation in C
stack implementation in C

A stack is one of the basic data structures in programming. It helps store and manage data in a particular order. You can see stack operations in many applications, such as undo and redo features, browser history, function calls, and expression evaluation.

In C programming, a stack can be implemented using an array or a linked list. In this guide, we will focus on stack implementation using array in C. You will learn how a stack works, understand its basic operations such as push, pop, and peek, and explore a complete C program with its output.

By the end, you will understand how to implement a stack, manage stack elements, and check whether a stack is full or empty. This will help you build a strong foundation in data structures and C programming.

What Is a Stack in Data Structure?

A stack is a linear data structure that stores elements in a specific order. It follows the Last In, First Out (LIFO) principle, which means the element added last will be removed first.

Think about a stack of plates. When you place a new plate on top, it becomes the first plate you can take. You cannot easily remove a plate from the middle or bottom without moving the plates above it. A stack works in the same way.

Here are the key points to understand about a stack:

  • 1. Linear data structure: Stack elements are arranged one after another.
  • 2. LIFO principle: The last element added is the first one removed.
  • 3. Top position: The top indicates the most recently added element.
  • 4. Push operation: Adds a new element to the top of the stack.
  • 5. Pop operation: Removes the top element from the stack.
  • 6. Peek operation: Displays the top element without removing it.
  • 7. Overflow condition: Occurs when you try to add an element to a full stack.
  • 8. Underflow condition: Occurs when you try to remove an element from an empty stack.

In C, you can implement a stack using an array or a linked list. An array-based stack is easy to understand and is a good starting point for learning stack implementation.

Understanding the Stack Data Structure

A stack is a linear data structure where insertion and deletion happen only at one end, called the top. This makes it different from other data structures, such as arrays and queues, where elements can be accessed or managed in different ways.

For example, consider a stack containing three elements: 10, 20, and 30.

Stack Implementation Using Array in C
Stack Implementation Using Array in C

In this example:

  • 1. 10 was added first, so it is at the bottom.
  • 2. 20 was added second, so it is in the middle.
  • 3. 30 was added last, so it is at the top.

If you perform a pop operation, the element 30 will be removed first. The next pop operation will remove 20.

In an array-based stack, a variable called top keeps track of the current top element. This variable helps the program identify where to insert or remove elements during stack operations. We will explore how to use this variable in the implementation section.

How Does a Stack Work Using an Array?

An array-based stack stores elements in consecutive memory locations. A variable called top is used to track the position of the last inserted element.

When a new element is added, the top value moves forward, and the element is stored at that position. When an element is removed, the top value moves backward.

For example, consider an array with a maximum capacity of five elements:

int stack[5];
int top = -1;

Here:

  • stack[5] creates an array that can store five elements.
  • top = -1 indicates that the stack is initially empty.
  • When the first element is inserted, top becomes 0.
  • When another element is inserted, top becomes 1.

Let’s understand this with an example:

OperationStack elementsTop value
Initial stateEmpty-1
Push 10100
Push 2010, 201
Push 3010, 20, 302
Pop10, 201

As you can see, the array stores the stack elements, while the top variable helps manage insertion and deletion.

This is the basic working principle behind stack implementation using an array in C.

What Is LIFO (Last In, First Out)?

LIFO stands for Last In, First Out. It is the main principle followed by a stack data structure. According to this rule, the element inserted last will be the first one removed.

Let’s understand this with a simple example.

Imagine you insert three elements into a stack in the following order:

  1. 1. Push 10 into the stack.
  2. 2. Push 20 into the stack.
  3. 3. Push 30 into the stack.

Now, the stack contains 10, 20, and 30, with 30 at the top.

Stack Implementation in C
Stack Implementation in C

When you perform the pop operation, 30 is removed first because it was the last element added. The next pop operation removes 20, followed by 10.

This is why a stack is called a Last In, First Out data structure. Understanding LIFO is important before learning stack operations such as push, pop, and peek in C programming.

Stack Operations in Data Structure

A stack supports different operations to add, remove, and access elements. These operations are performed only at the top of the stack, following the Last In, First Out (LIFO) principle.

The four basic stack operations are:

  • 1. Push: Adds a new element to the top of the stack.
  • 2. Pop: Removes the top element from the stack.
  • 3. Peek: Returns or displays the top element without removing it.
  • Display: Shows all the elements currently stored in the stack.

For example, consider a stack containing 10, 20, and 30. The element 30 is at the top. You can add another element using push, remove 30 using pop, or view 30 using peek.

Understanding these stack operations will help you learn how to implement a stack using an array in C.

Push Operation in a Stack

The push operation is used to add a new element to the top of a stack. Before inserting an element, the program checks whether the stack is full. If space is available, the top variable is increased by one, and the new element is stored at that position.

Pop Operation in a Stack

The pop operation removes the top element from the stack. Before removing an element, the program checks whether the stack is empty. If the stack contains elements, the top value is decreased by one after removing the element. If the stack is empty, the operation cannot be performed. This condition is called stack underflow.

Peek Operation in a Stack

The peek operation is used to view the top element without removing it from the stack. It is useful when you want to know which element will be removed during the next pop operation. If the stack is empty, there is no top element to display.

Display Stack Elements

The display operation shows all the elements currently stored in the stack. Usually, the elements are displayed from top to bottom. If the stack is empty, the program displays a message such as “Stack is empty.”

Stack operationPurposeHow it worksCondition
PushAdds an elementIncreases top and inserts the new elementStack must not be full
PopRemoves an elementRemoves the top element and decreases topStack must not be empty
PeekViews the top elementDisplays the element at the top positionStack must not be empty
DisplayShows stack elementsPrints all elements from top to bottomStack must contain elements

These four operations form the foundation of stack implementation using an array in C.

Stack Implementation Using Array in C

Stack implementation using an array is one of the simplest ways to understand how a stack works in C programming. In this method, an array stores the stack elements, and an integer variable called top keeps track of the most recently inserted element.

The array has a fixed size, which means it can store only a limited number of elements. Whenever you perform a push or pop operation, the top variable is updated to maintain the current position.

Before implementing the stack operations, you need to understand four important steps:

  1. 1. Declare an array to store the stack elements.
  2. 2. Initialise the stack and set the top variable.
  3. 3. Check whether the stack is full before inserting an element.
  4. 4. Check whether the stack is empty before removing or accessing an element.

These steps help prevent stack overflow and underflow errors during program execution.

Declaring an Array to Store Stack Elements

The first step in stack implementation using an array is to declare an array that stores the elements. In C, you can create an integer array with a fixed size based on how many elements you want the stack to hold.

For example: int stack[5];

Here, stack is an integer array that can store a maximum of five elements. Each element is stored at an index starting from 0.

The array positions are:

Array indexElement
0stack[0]
1stack[1]
2stack[2]
3stack[3]
4stack[4]

If you insert the values 10, 20, and 30, the array will look like this:

Index01234
Value102030EmptyEmpty

The array can store five elements, but currently, only three positions are occupied. The remaining two positions are available for future push operations.

In this way, an array provides the storage space required to implement a stack in C.

Initialising the Stack and Top Variable

After declaring the array, the next step is to initialise the stack. For this, you need an integer variable called top to track the position of the last inserted element.

Initially, assign -1 to the top variable.

int stack[5];
int top = -1;

Here is why top = -1 is used:

  • Array indexing in C starts from 0.
  • When top = -1, it indicates that no elements have been inserted.
  • When the first element is added, top becomes 0.
  • When the second element is added, top becomes 1.
  • Each time a new element is inserted, top increases by one.

For example, consider inserting three elements: 10, 20, and 30.

OperationStack elementsTop value
Initial stateEmpty-1
Insert 10100
Insert 2010, 201
Insert 3010, 20, 302

Therefore, the top variable helps identify the current top element and manage push, pop, and peek operations in stack implementation using an array in C.

Checking If the Stack Is Full

Before inserting a new element into a stack, you must check whether the stack has reached its maximum capacity. This condition is known as stack overflow.

In an array-based stack, the stack is full when the top variable reaches the last valid array index.

For example, consider an array with a capacity of five elements:

#define MAX 5

int stack[MAX];
int top = -1;

if (top == MAX - 1) {
    printf("Stack is full");
} else {
    printf("Space is available");
}

How does this condition work?

  • 1. MAX represents the maximum number of elements the stack can store.
  • 2. MAX - 1 represents the last valid array index.
  • 3. If top == MAX - 1, the stack is full.
  • Otherwise, the stack has space for additional elements.

For an array of size five, the valid indexes are 0 to 4. When top reaches 4, all five positions are occupied, and no more elements can be inserted.

Checking whether the stack is full before performing a push operation prevents stack overflow and avoids accessing an invalid array position.

Checking If the Stack Is Empty

Before performing a pop or peek operation, you need to check whether the stack contains any elements. If there are no elements, the stack is considered empty. This condition is known as stack underflow when an operation tries to remove an element from it.

In an array-based stack, the stack is empty when the top variable is equal to -1.

For example:

int stack[5];
int top = -1;

if (top == -1) {
    printf("Stack is empty");
} else {
    printf("Stack contains elements");
}

How does this condition work?

  • top = -1 indicates that no elements are currently stored in the stack.
  • If top == -1, the stack is empty.
  • If top >= 0, the stack contains at least one element.
  • When the last element is removed using the pop operation, top becomes -1 again.
Stack stateTop valueCondition
No elements-1Stack is empty
One element0Stack contains elements
Three elements2Stack contains elements
Five elements4Stack is full

Checking whether the stack is empty helps prevent invalid pop and peek operations. It ensures that the program accesses only valid stack elements during execution.

C Program for Stack Implementation Using Array

Now that you understand the basic concepts of a stack, its operations, and how an array stores stack elements, let’s implement a complete stack program in C.

In this program, we will use an integer array and a top variable to manage the stack. We will also use a menu-driven approach so that users can select different operations.

The program will support four main operations:

  • 1. Push: Insert a new element into the stack.
  • 2. Pop: Remove the top element from the stack.
  • 3. Peek: Display the top element without removing it.
  • 4. Display: Print all the elements currently available in the stack.

It will also check whether the stack is full or empty before performing the required operations. This helps beginners understand how stack implementation using an array works in a practical C program.

Complete C Program to Implement a Stack

The following C program implements a stack using an array. It includes all four basic operations: push, pop, peek, and display.

#include <stdio.h>
#define MAX 5

int stack[MAX];
int top = -1;

// Push operation
void push() {
    int value;

    if (top == MAX - 1) {
        printf("Stack is full! Overflow condition.\n");
    } else {
        printf("Enter the value to insert: ");
        scanf("%d", &value);

        top++;
        stack[top] = value;

        printf("%d inserted into the stack.\n", value);
    }
}

// Pop operation
void pop() {
    if (top == -1) {
        printf("Stack is empty! Underflow condition.\n");
    } else {
        printf("Deleted element: %d\n", stack[top]);
        top--;
    }
}

// Peek operation
void peek() {
    if (top == -1) {
        printf("Stack is empty. No element to display.\n");
    } else {
        printf("Top element: %d\n", stack[top]);
    }
}

// Display operation
void display() {
    if (top == -1) {
        printf("Stack is empty.\n");
    } else {
        printf("Stack elements:\n");

        for (int i = top; i >= 0; i--) {
            printf("%d\n", stack[i]);
        }
    }
}

// Main function
int main() {
    int choice;

    while (1) {
        printf("\n--- Stack Operations ---\n");
        printf("1. Push\n");
        printf("2. Pop\n");
        printf("3. Peek\n");
        printf("4. Display\n");
        printf("5. Exit\n");

        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                push();
                break;

            case 2:
                pop();
                break;

            case 3:
                peek();
                break;

            case 4:
                display();
                break;

            case 5:
                printf("Exiting the program.\n");
                return 0;

            default:
                printf("Invalid choice! Please try again.\n");
        }
    }

    return 0;
}
  • 1. #define MAX 5 sets the maximum stack capacity to five elements.
  • 2. int stack[MAX] declares the array used to store stack elements.
  • 3. int top = -1 indicates that the stack is initially empty.
  • 4. The push(), pop(), peek(), and display() functions perform the four stack operations.
  • 5. The switch statement allows users to select an operation from the menu.
  • 6. The while loop keeps the program running until the user selects Exit.

This program demonstrates how to implement a stack using an array in C with basic error checking for full and empty stack conditions.

Output of the Stack Implementation Program

Let’s execute the C program and see how the stack operations work.

For this example, we will insert three elements (10, 20, and 30), view the top element, remove an element, and display the remaining stack elements.

Sample Output:

--- Stack Operations ---
1. Push
2. Pop
3. Peek
4. Display
5. Exit

Enter your choice: 1
Enter the value to insert: 10
10 inserted into the stack.

Enter your choice: 1
Enter the value to insert: 20
20 inserted into the stack.

Enter your choice: 1
Enter the value to insert: 30
30 inserted into the stack.

Enter your choice: 3
Top element: 30

Enter your choice: 4
Stack elements:
30
20
10

Enter your choice: 2
Deleted element: 30

Enter your choice: 4
Stack elements:
20
10

Enter your choice: 5
Exiting the program.

Understanding the output:

  1. 1. Push: The values 10, 20, and 30 are inserted into the stack in that order.
  2. 2. Peek: The program displays 30 because it is the top element.
  3. 3. Display: All elements are printed from top to bottom (30, 20, 10).
  4. 4. Pop: The top element 30 is removed from the stack.
  5. 5. Display: The remaining elements are 20 and 10.

This output demonstrates the LIFO principle: the last element inserted (30) is the first element removed.

Explanation of Push, Pop, Peek, and Display Operations

The C program uses four functions to perform stack operations. Each function handles a specific task and updates or accesses the stack based on the current value of top.

Push Operation

The push() function inserts a new element at the top of the stack.

  • 1. First, it checks whether top == MAX - 1.
  • 2. If the condition is true, the stack is full, and insertion is not possible.
  • 3. Otherwise, top is increased by one.
  • 4. The new value is stored at stack[top].

Pop Operation

The pop() function removes the top element from the stack.

  • 1. First, it checks whether top == -1.
  • 2. If the condition is true, the stack is empty, and deletion is not possible.
  • 3. Otherwise, the program displays the top element.
  • 4. Finally, top is decreased by one.

Peek Operation

The peek() function displays the top element without removing it.

  • 1. It checks whether the stack is empty.
  • 2. If the stack contains elements, it displays stack[top].
  • 3. The top value remains unchanged because no element is removed.

Display Operation

The display() function prints all the elements currently stored in the stack.

  • 1. It first checks whether the stack is empty.
  • 2. If elements are available, a for loop starts from top.
  • 3. The loop moves towards index 0 and prints each element.
  • 4. This displays the stack elements from top to bottom.
OperationMain condition or statementPurpose
Pushtop == MAX - 1Checks whether the stack is full
Poptop == -1Checks whether the stack is empty
Peekstack[top]Accesses the top element
Displayfor (int i = top; i >= 0; i--)Prints all stack elements

Time Complexity of Stack Operations

OperationTime ComplexityReason
PushO(1)Inserts one element
PopO(1)Removes one element
PeekO(1)Accesses the top element
DisplayO(n)Visits all elements in the stack

Understanding these functions helps you see how an array and the top variable work together to perform stack operations in C.

Advantages and Limitations of Array-Based Stack

Using an array to implement a stack is a simple and beginner-friendly approach in C programming. It allows you to store elements in an organised manner and perform basic operations such as push, pop, and peek.

However, an array-based stack also has some limitations, especially when the number of elements changes frequently.

Let’s understand its advantages and limitations.

Advantages of Using an Array for Stack Implementation

Implementing a stack using an array offers several benefits, especially when working with a fixed number of elements.

  • 1. Easy to implement: An array-based stack is simple to understand and implement using basic C programming concepts.
  • 2. Fast operations: Push, pop, and peek operations take constant time, O(1), because they work directly with the top position.
  • 3. Memory organisation: Array elements are stored in consecutive memory locations, making access straightforward.
  • 4. No extra pointer required: Unlike a linked-list stack, an array-based stack does not need pointers to connect elements.
  • 5. Suitable for fixed-size data: It works well when the maximum number of elements is known in advance.

These advantages make an array-based stack a good choice for beginners learning data structures and implementing basic stack operations in C.

Limitations of Stack Using Array

Although an array-based stack is easy to implement, it has a few limitations that you should understand before using it in a program.

  • 1. Fixed size: An array has a predefined capacity. Once the stack reaches its maximum size, you cannot insert more elements.
  • 2. Stack overflow: If you try to insert an element when the stack is full, an overflow condition occurs.
  • 3. Memory wastage: If you declare a large array but use only a few positions, the remaining allocated space may go unused.
  • 4. Limited flexibility: Changing the stack capacity during program execution is not straightforward with a basic fixed-size array.
  • 5. Underflow condition: If you try to remove an element from an empty stack, an underflow condition occurs.

To overcome the fixed-size limitation, you can use a linked list to implement a stack. A linked-list stack can grow or shrink dynamically based on the number of elements.

Therefore, choose an array-based stack when the maximum capacity is known and a simple implementation is sufficient.

Final Thoughts

Understanding stack implementation using an array in C is an important step in learning data structures and programming. By practising push, pop, peek, and display operations, you can understand how elements are stored, accessed, and removed using the LIFO principle.

Start by writing simple C programs, experimenting with different stack operations, and handling conditions such as stack overflow and underflow. Regular practice will help you improve your programming and problem-solving skills.

If you want to build strong programming skills through practical, project-based training, Payilagam, a choice for learners looking for the Best Software Training Institute in Chennai, can help you take the next step towards your IT career.

Frequently Asked Questions About Stack Implementation in C

What Is a Stack in C?

A stack in C is a linear data structure that follows the Last In, First Out (LIFO) principle. It allows elements to be inserted and removed only from the top. The main operations include push, pop, peek, and display.

How Do You Implement a Stack Using an Array in C?

You can implement a stack using an array by declaring an array to store elements and an integer variable called top to track the top position. Initially, set top = -1. Then, use push, pop, peek, and display functions to perform stack operations.

How Do You Check If a Stack Is Full?

You can check whether a stack is full by comparing the top variable with the last valid array index.

if (top == MAX - 1) {
    printf("Stack is full");
}

If the condition is true, the stack has reached its maximum capacity, and you cannot insert another element.

What Happens When the Stack Is Empty?

When the stack is empty, the top variable is equal to -1. If you try to perform a pop operation on an empty stack, a stack underflow condition occurs. Similarly, the peek operation cannot return a top element because no elements are available.

What Is the Difference Between Push, Pop, and Peek Operations?

Push, pop, and peek are the three main operations used to manage stack elements.

OperationDescription
PushAdds a new element to the top of the stack.
PopRemoves the top element from the stack.
PeekDisplays the top element without removing it.

All three operations follow the LIFO principle and work with the top position of the stack.

We are a team of passionate trainers and professionals at Payilagam, dedicated to helping learners build strong technical and professional skills. Our mission is to provide quality training, real-time project experience, and career guidance that empowers individuals to achieve success in the IT industry.