For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
A stack is a data structure that follows the Last In, First Out (LIFO) principle. It allows you to add and remove elements from the top. For example, when you place plates on a stack, you remove the top plate first. In programming, stack operations allow you to add and remove elements from the top.
Implementing stack operations in C can be tricky, especially when handling dynamic memory and pointers.
This tutorial will guide you through implementing a stack in C program, along with essential stack operations. Let’s dive into the details!
Boost your C programming skills with our Software Development courses — take the next step in your learning journey!
In C, a stack can be represented using either an array or a linked list. An array-based implementation is straightforward and useful for stacks of fixed size, while a linked list implementation is dynamic and allows for a flexible size.
In this representation, the stack is implemented as an array, with the top of the stack being managed by an index variable.
Here’s the basic structure:
#define MAX 100 // Maximum stack size
int stack[MAX]; // Stack array
int top = -1; // Initialize top of stack as -1
Alternatively, you can use a linked list to represent a stack. In this case, each stack element is stored in a node, with each node pointing to the next one.
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
Both approaches are effective, but using a linked list is more flexible as it avoids the need to predefine a size.
Also Read: What are Data Structures in C & How to Use Them?
With the stack structure in place, let’s now explore the key operations that power stack functionality.
Here’s a quick look at the basic operations performed on a stack:
Operation | Description | Time Complexity | Space Complexity |
push() | Inserts an element at the top of the stack. | O(1) | O(1) |
pop() | Removes the top element from the stack. | O(1) | O(1) |
top() | Returns the top element without removing it. | O(1) | O(1) |
isEmpty() | Checks if the stack is empty. | O(1) | O(1) |
isFull() | Check if the stack is full. | O(1) | O(1) |
The push() operation adds an element to the top of the stack. It first creates a new node and then sets the new node’s pointer to the current top. The top pointer is updated to the new node, effectively making it the new top of the stack.
Algorithm for push():
The pop() operation removes the top element from the stack. It first checks if the stack is empty. If not, the top element is removed, and the top pointer is updated to the next node in the stack.
Algorithm for pop():
The top() operation retrieves the top element without removing it. It simply returns the value of the top element without modifying the stack.
Algorithm for top():
The isEmpty() operation checks if the stack is empty. It returns true if the stack is empty (i.e., the top pointer is NULL), and false otherwise.
Algorithm for isEmpty():
The isFull() operation checks if the stack is full. This operation isn't always necessary for a dynamic stack (implemented with a linked list) because the stack can grow as needed. For a static stack (e.g., using an array), it checks if the stack has reached its maximum capacity.
Algorithm for isFull():
Also Read: Types of Operators in C: Roles, Usage & Best Practices 2025
On that note, let's look at the types of stacks and their specific applications.
In C programming, stacks can be classified into different types based on their implementation. The two main types of stacks are Static Stacks and Dynamic Stacks.
Understanding these will help you choose the right one for your application, especially when dealing with stack operations in C.
A static stack is implemented using arrays. The stack size is predefined, meaning it has a fixed size at the time of creation. This makes the static stack simple to implement and efficient for small applications where the size of the stack is predictable.
However, one limitation is that the size cannot be changed dynamically.
Example:
int top = -1; #define MAX 100 // Set stack size
int stack[MAX]; // Array for stack
// Initialize top
A dynamic stack is implemented using linked lists. Unlike the static stack, the size of the stack is not predefined. The stack grows and shrinks dynamically as elements are added or removed, making it more flexible than a static stack.
It avoids memory wastage since it only uses memory as needed.
Example:
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
Here’s the list of a few other types of stacks:
A circular stack wraps the end of the stack to the beginning, making better use of memory, especially in applications with fixed memory limits. Ideal for cases where stack overflow could occur in a linear stack, as it reuses the memory space.
Example:
struct Node {
int data;
struct Node* next;
};
A double-ended stack (deque) allows inserting and removing elements from both ends, making it a versatile data structure. It's commonly used when you need efficient access to both ends of the stack.
Example:
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
A multi-stack implementation uses one array or linked list to manage multiple stacks. This method is useful in systems where different tasks need isolated memory spaces, such as in function calls or memory management systems.
Example:
int stack[MAX_SIZE];
int top[NUM_STACKS];
A persistent stack preserves the history of its operations, enabling users to access previous states. This is perfect for applications like text editors, where users can undo actions and revert to previous versions of data.
Example:
struct Node {
char action[100];
struct Node* next;
};
The type of stack you choose affects your program's performance, memory usage, and complexity.
For example, a static stack is faster but has a fixed size, whereas a dynamic stack offers flexibility but may incur extra memory overhead. A circular stack can be more efficient when memory is reused, and a double-ended stack can optimize tasks that require access from both ends.
Understanding the types of stacks and their use cases can help you make better decisions and build more optimized solutions when performing stack operations in C.
A real-life example of a stack is the browser history. When you visit websites, your browser stores the pages in a stack. The most recent page is always on top. If you press the "Back" button, the top page is popped off the stack, and the browser takes you to the previous page.
For this example, we will implement a simple stack that mimics this functionality with basic stack operations like push(), pop(), top(), isEmpty(), and isFull().
Let’s look at the algorithm:
Let’s see how the code works out:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a node structure for the stack
struct Node {
char url[100]; // Holds the website address
struct Node* next; // Points to the next node in the stack
};
// Define the top of the stack (initially NULL)
struct Node* top = NULL;
// Push operation to insert a page (URL) at the top of the stack
void push(char url[]) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory for a new node
if (newNode == NULL) {
printf("Memory overflow\n");
return;
}
strcpy(newNode->url, url); // Copy the URL into the new node's data field
newNode->next = top; // Link the new node to the current top node
top = newNode; // Move the top pointer to the new node
printf("Visited: %s\n", url); // Print the visited page URL
}
// Pop operation to remove the top page from the stack (back functionality)
void pop() {
if (top == NULL) { // Check if the stack is empty (no pages to go back to)
printf("No history to go back\n");
return;
}
struct Node* temp = top; // Temporarily store the top node
printf("Going back to: %s\n", temp->url); // Print the page we are going back to
top = top->next; // Move the top pointer to the next node
free(temp); // Free the memory of the old top node
}
// Top operation to view the current page (without popping it)
void topPage() {
if (top == NULL) {
printf("No page in history\n");
return;
}
printf("Currently on: %s\n", top->url); // Print the current top page URL
}
// Check if the stack is empty
int isEmpty() {
return top == NULL;
}
// Main function to simulate stack operations (browser history)
int main() {
push("www.google.com"); // Visit Google
push("www.youtube.com"); // Visit YouTube
push("www.stackoverflow.com"); // Visit StackOverflow
topPage(); // Check the current page
pop(); // Go back to previous page
pop(); // Go back to previous page
topPage(); // Check the current page after going back
return 0;
}
Output:
Currently on: Visited: www.google.com
Visited: www.youtube.com
Visited: www.stackoverflow.com
Currently on: www.stackoverflow.com
Going back to: www.stackoverflow.com
Going back to: www.youtube.com
www.google.com
Explanation:
In this example, we simulate the browser's "Back" functionality using stack operations in C. The stack holds a history of pages, and you can easily go back through the pages as needed using the pop() operation.
This quiz will help you test your understanding of stacks in C programming. See if you're ready to dive deeper into this fundamental data structure!
1. What is the main characteristic of a stack in C?
A) First In, First Out (FIFO)
B) Last In, First Out (LIFO)
C) No order
D) Random access
2. Which of the following is the main operation used to add an element to a stack in C?
A) pop()
B) push()
C) peek()
D) remove()
3. What is the default value of the stack pointer if no elements are pushed onto the stack?
A) NULL
B) 0
C) -1
D) Undefined
4. What happens if you attempt to pop an element from an empty stack?
A) Stack overflow
B) Stack underflow
C) No operation
D) Program crashes
5. Which of the following is NOT a method to implement a stack in C?
A) Using arrays
B) Using linked lists
C) Using hash tables
D) Using pointers
6. What is the output of the following C code when running a stack implemented using arrays?
#include <stdio.h>
#define MAX 3
int stack[MAX];
int top = -1;
void push(int val) {
if (top < MAX - 1) {
stack[++top] = val;
}
}
int main() {
push(10);
push(20);
printf("%d\n", stack[top]);
return 0;
}
A) 10
B) 20
C) 30
D) Error
7. What is the time complexity for the push and pop operations in a stack using an array?
A) O(n)
B) O(log n)
C) O(1)
D) O(n^2)
8. What is the role of the "top" pointer in a stack implemented using a linked list?
A) Points to the bottom element of the stack
B) Points to the most recent element pushed onto the stack
C) Tracks the number of elements in the stack
D) Marks the end of the stack
9. How can a stack be used in recursive algorithms?
A) It stores local variables during recursion
B) It helps with function call management
C) It tracks variables to be printed
D) It does not play a role in recursion
10. What is the key disadvantage of using a stack with a fixed size in C?
A) It wastes memory
B) It causes stack overflow when the size limit is exceeded
C) It has slower push/pop operations
D) It limits the number of elements that can be popped
Understanding stack in C is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.
How Can upGrad Help You Master Stack in C?
upGrad’s courses offer a comprehensive, hands-on approach to mastering C programming, including concepts like stacks, recursion, and data structures. Whether you’re learning how stacks operate or optimizing your stack-based algorithms, upGrad’s expert-led courses will guide you step-by-step through key C programming concepts.
Through our interactive courses, you'll gain practical experience working with stacks, from implementing basic operations to tackling more advanced applications in system-level programming and competitive coding.
Check out upGrad’s programs to advance your knowledge:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Binary Search in C
Constant Pointer in C: The Fundamentals and Best Practices
Find Out About Data Structures in C and How to Use Them?
A. A stack in C program is ideal for LIFO operations, providing efficient access to the most recent element, making it perfect for use cases like undo functionality or recursion.
A. Stack operations in C, like push and pop, operate in constant time O(1), making them very efficient for managing data with the LIFO structure.
A. Yes, stack operations in C can be implemented statically by using arrays, but dynamic memory allocation (linked list) allows for more flexible and scalable stacks.
A. Common real-life uses of stack operations in C include managing browser history, implementing undo features in text editors, and handling recursive function calls.
A. In dynamic stack implementations, memory is allocated dynamically for each node, ensuring that the stack can grow and shrink as needed, reducing memory wastage.
A. Trying to pop from an empty stack in C program will result in a stack underflow error, which should be handled with a condition check to ensure the stack isn't empty.
A. Stack overflow occurs when trying to push to a full stack, while stack underflow occurs when trying to pop from an empty stack.
A. Using an array to implement a stack in C program limits the stack size, requiring predefined memory allocation, which may lead to memory wastage or overflow.
A. The top() operation allows you to view the current element at the top of the stack without removing it, providing a peek into the most recent data added.
A. Yes, stack operations in C can be implemented recursively by using function calls, although managing stack overflow becomes crucial in recursive implementations.
A. Checking for stack overflow is crucial to prevent memory corruption, ensuring that data is not overwritten or causing crashes when the stack exceeds its capacity.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.