Stack implementation using arrays in C
Stack is a linear data structure which stores data. It uses the LIFO(Last In First Out) principle.
It has following functions.
‘push()’ – it inserts the data into stack.
‘pop()’ – it deletes the data from the stack.
Program implementation:
- · This program includes the built-in header file. It defines the maximum size as 50.
- · Stack and top values are initialised.
- · To insert the value, check top value with maximum size to check for overflow. If it is overflow, the message is displayed. Otherwise, the data is inserted.
- · To delete the value, check for top value. If it is -1, then it is called underflow. Otherwise, the data is removed from the top.
- · Finally, data is displayed using print ().
#include <stdio.h>
#define Max_size 50
// maximum size
int stack[Max_size];
int top = -1; //
initialise top value as -1
// insert the value
void push(int value) {
if (top ==
Max_size - 1) {
printf("Stack is Overflow! you are unable to push %d\n",
value);
} else {
stack[++top] =
value;
printf("%d pushed onto stack\n", value);
}
}
// Delete the value
int pop() {
if (top == -1) {
printf("Stack is Underflow! you Cannot pop\n");
return -1;
} else {
return
stack[top--];
}
}
// printing the value
void print() {
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");
}
}
int main() {
push(110);
push(20);
push(33);
push(67);
push(89);
print();
printf("Popped element: %d\n", pop());
print();
return 0;
}
Output:
110 pushed onto stack
20 pushed onto stack
33 pushed onto stack
67 pushed onto stack
89 pushed onto stack
Stack elements: 110 20 33 67 89
Popped element: 89
Stack elements: 110 20 33 67
This program is completed. Hope, the concept is useful to
you. Keep Coding!!!
Comments
Post a Comment