STACK IN C PROGRAMMING MADE EASY
In C, a stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last item added to the stack will be the first one to be removed. To implement a stack in C, you can use an array and two pointers to keep track of the top of the stack. The push operation is performed by incrementing the top pointer and storing the new value at that location, while the pop operation is performed by retrieving the value at the current top location and decrementing the top pointer.
For example:
#include <stdio.h>
#define MAX 100
int stack[MAX];
int top = -1;
void push(int value) {
if (top == MAX - 1) {
printf("Error: Stack overflow\n");
return;
}
top++;
stack[top] = value;
}
int pop() {
if (top == -1) {
printf("Error: Stack underflow\n");
return -1;
}
int value = stack[top];
top--;
return value;
}
int main() {
push(1);
push(2);
push(3);
printf("%d\n", pop()); // Output: 3
printf("%d\n", pop()); // Output: 2
printf("%d\n", pop()); // Output: 1
return 0;
}
This code implements a stack data structure in the C programming language.
The code starts by including the standard input/output header file, stdio.h
, and defining a macro, MAX
, with a value of 100. This macro is used to set the maximum size of the stack array.
The stack is implemented as an array, stack
, and a variable, top
, is used to keep track of the top of the stack. Initially, top
is set to -1
, which indicates that the stack is empty.
The code implements two functions, push
and pop
, to add and remove elements from the stack, respectively.
The push
function first checks if the stack is full by checking if top
is equal to MAX - 1
. If the stack is full, an error message is printed and the function returns without adding an element to the stack. If the stack is not full, top
is incremented and the value passed as an argument is added to the top of the stack by assigning it to stack[top]
.
The pop
function first checks if the stack is empty by checking if top
is equal to -1
. If the stack is empty, an error message is printed and the function returns -1
without removing an element from the stack. If the stack is not empty, the value at the top of the stack is stored in a variable value
, top
is decremented, and value
is returned.
In the main
function, the push
function is called three times to add the values 1, 2, and 3 to the stack. The pop
function is then called three times to remove and print the values from the top of the stack. The expected output is 3, 2, 1.
Follow, Like and share Thank you