Stack Example: Implementation in C

Stacks are one of the cornerstones of data structures in programming, playing a crucial role in algorithms, compilers, operating systems, and much more. In this blog, we’re going to take a closer look at the stack data structure, explore how it operates, and walk through a complete example in C, covering essential operations like push, pop, and peek.

Stack Example Implementation in C

Whether you’re a student just starting to learn about data structures or someone gearing up for interviews, knowing how to implement a stack in C can really give you an advantage.

If you’re eager to master data structures with C programming and get hands-on experience with real projects, don’t miss the Data Structures Course in Noida offered by Uncodemy.

What is a Stack?

A stack is a linear data structure that operates on the LIFO (Last In, First Out) principle. In simpler terms, the last item you add to the stack is the first one that gets removed.

Key Operations:

-        Push: This adds an element to the top of the stack.

-        Pop: This removes the top element from the stack.

-        Peek (Top): This lets you view the top element without taking it off the stack.

-        isEmpty: This checks if the stack is empty.

-        isFull: This checks if the stack is full (especially relevant for array implementations).

Real-World Examples of Stack

Stacks are utilized in a variety of real-life and technical situations:

-        Undo functions in applications like MS Word

-        Backtracking algorithms for solving mazes or puzzles

-        Function call stacks in programming languages

-        Managing browser history

-        Syntax parsing in compilers

Types of Stack Implementation

There are two popular methods to implement stacks in C:

-        Using Arrays – This approach has a fixed size and is straightforward to implement.

-        Using Linked Lists – This method offers a dynamic size and greater flexibility.

In this post, we’ll concentrate on array-based stack implementation for the sake of clarity and simplicity.

Stack Example in C Using Array

Let’s create a stack using arrays and implement basic operations like push, pop, peek, and display.

Program: Stack Implementation in C Using Array

Copy Code

#include <stdio.h>

#define SIZE 5

int stack[SIZE];

int top = -1;

// Function to add element to the stack

void push(int value) {

if (top == SIZE - 1)

        printf("Stack Overflow\n");

else {

     top++;

        stack[top] = value;

        printf("%d pushed to stack\n", value);

}

}

// Function to remove element from stack

void pop() {

if (top == -1)

        printf("Stack Underflow\n");

else {

        printf("%d popped from stack\n", stack[top]);

     top--;

}

}

// Function to view top element

void peek() {

if (top == -1)

        printf("Stack is empty\n");

else

        printf("Top element is %d\n", stack[top]);

}

// Function to display stack elements

void display() {

if (top == -1)

        printf("Stack is empty\n");

else {

        printf("Stack elements are: ");

     for (int i = 0; i <= top; i++)

            printf("%d ", stack[i]);

        printf("\n");

}

}

int main() {

push(10);

push(20);

push(30);

display();

peek();

pop();

display();

return 0;

}

Output:

10 pushed to stack

20 pushed to stack

30 pushed to stack

Stack elements are: 10 20 30

Top element is 30

30 popped from stack

Stack elements are: 10 20

Step-by-Step Explanation

Let’s break down how the stack operations work

1. Push Operation

-        Before we add a new item, we first check if the stack is full by seeing if top equals SIZE - 1.

-        If there’s still space, we go ahead and increase top and insert the value.

2. Pop Operation

-        We need to check if the stack is empty by looking at whether top equals -1.

-        If it’s not empty, we print the top value and then decrease top.

3. Peek Operation

-        This operation shows the top element without changing anything in the stack.

4. Display Operation

-        We loop from 0 to top and print each element along the way.

Edge Cases to Keep in Mind

1.  Underflow Condition: This happens when we try to pop from an empty stack.

2.  Overflow Condition: This occurs when we attempt to push onto a full stack.

3.  Handling Top = -1: This is a key check to prevent segmentation faults.

Stack Example in C Using Functions and Menu

Here’s a more advanced version featuring a menu-driven interface, which lets users input commands for all stack operations.

Menu-Driven Stack Program in C

Copy Code

#include <stdio.h>

#define SIZE 5

int stack[SIZE], top = -1;

void push();

void pop();

void peek();

void display();

int main() {

int choice;

while (1) {

        printf("\n*** Stack Menu ***\n");

        printf("1. Push\n2. Pop\n3. Peek\n4. Display\n5. 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: return 0;

            default: printf("Invalid choice\n");

     }

}

return 0;

}

void push() {

int val;

if (top == SIZE - 1)

        printf("Stack Overflow\n");

else {

        printf("Enter value to push: ");

        scanf("%d", &val);

        stack[++top] = val;

}

}

void pop() {

if (top == -1)

        printf("Stack Underflow\n");

else

        printf("Popped element: %d\n", stack[top--]);

}

void peek() {

if (top == -1)

        printf("Stack is empty\n");

else

        printf("Top element: %d\n", stack[top]);

}

void display() {

if (top == -1)

        printf("Stack is empty\n");

else {

        printf("Stack elements: ");

     for (int i = 0; i <= top; i++)

            printf("%d ", stack[i]);

        printf("\n");

}

}

Advantages of Stack

-        Easy to implement

-        Memory efficient, especially when using dynamic memory

-        Quick operations, with O(1) time for both push and pop

-        Great for backtracking and undo features

Limitations of Stack

-        The fixed size in array implementations can lead to overflow issues.

-        You can’t directly access elements in the middle due to its LIFO (Last In, First Out) nature.

-        Not the best choice for complex insertions or deletions; linked lists or other data structures might be better.

Applications of Stack in Programming

-        Reversing strings

-        Evaluating postfix expressions

-        Converting expressions from infix to postfix

-        Managing function calls

-        Checking for balanced parentheses

-        Solving backtracking problems

-        Implementing Depth First Search (DFS)

Best Practices While Working with Stacks

-        Always check stack boundaries to avoid underflow or overflow.

-        Use clear and meaningful variable names like top, maxSize, and stack[].

-        Break your code into modular functions for reusability.

-        Test edge cases, such as pushing beyond limits or popping from an empty stack.

-        Add comments to your code to enhance readability.

Related Advanced Concepts

If you’ve got a handle on the basics of stack operations, why not dive into some more advanced topics? Check these out:

-        Implementing a Stack with a Linked List in C

-        Creating a Dynamic Stack using malloc()

-        Managing Two Stacks within a Single Array

-        Evaluating Infix to Postfix Expressions

These subjects build on the same fundamental principles and are frequently featured in interviews.

To truly master these advanced concepts and elevate your skills in data structures, consider enrolling in the Data Structures Course in Noida offered by Uncodemy.

Conclusion

Stacks are a fundamental concept in computer science, providing a simple yet effective way to handle data. In this blog, we took a closer look at stack implementation in C, discussed essential operations like push, pop, and peek, and explored both basic and menu-driven versions.

Grasping how stacks function and learning to implement them from the ground up not only boosts your coding confidence but also equips you for interviews and practical applications.

If you’re serious about mastering data structures, start by solidifying your understanding of stack operations and then move on to more complex stack-based algorithms.

Join Uncodemy’s Data Structures Course in Noida to learn from industry professionals and engage in real-time DSA projects.

Frequently Asked Questions (FAQs)

Q1. What is a stack in C?

A stack in C is a data structure that operates on a Last In First Out (LIFO) principle. You can create it using either arrays or linked lists.

Q2. What’s the difference between a stack and a queue?

A stack follows the LIFO method, while a queue uses FIFO (First In First Out). This means that a stack removes the most recently added element, whereas a queue removes the oldest one.

Q3. What leads to stack overflow and underflow?

- Overflow happens when you try to push an element onto a stack that’s already full.

- Underflow occurs when you attempt to pop an element from an empty stack.

Q4. Can I create a dynamic stack in C?

Absolutely! By using malloc(), you can allocate memory during runtime, allowing your stack to grow or shrink as needed.

Q5. What’s the time complexity for stack operations?

All operations on a stack—like push, pop, and peek—are O(1), which means they take constant time.

Q6. Is there a built-in stack data structure in C?

Nope, C doesn’t come with built-in stack libraries. You’ll need to implement it yourself using arrays or linked lists.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses