Implementation of Stack using Array in C

In this source code example, we will write a code to implement the Stack data structure using an Array in C programming language.

Implementation of Stack using Array in C

A stack is an ordered list in which insertion and deletion are done at one end, called a top. The last element inserted is the first one to be deleted. Hence, it is called the Last in First out (LIFO) or First in Last out (FILO) list.

Main stack operations

Push Operation:
The process of putting a new data element onto the stack is known as a Push Operation.

Pop Operation:
Accessing the content while removing it from the stack, is known as a Pop Operation.

Let's write a C program to implement the Stack data structure using an Array. We will take input from the User or console:

#include<stdio.h>
#include<stdlib.h>

#define MAXSTK 100
int top = -1;
int items[MAXSTK];
int Isempty();
int Isfull();
void Push(int);
int Pop();
void Display();

void main() {
	int x;
	char ch = '1';
	while (ch != '4') {
		printf("\n 1-PUSH");
		printf("\n 2-POP");
		printf("\n 3-DISPLAY");
		printf("\n 4-QUIT");
		printf("\n Enter your choice:");
		fflush(stdin);
		ch = getchar();
		switch (ch) {
		case '1':
			printf("\n Enter the element to be pushed:");
			scanf("%d", &x);
			Push(x);
			break;
		case '2':
			x = Pop();
			printf("\n Pop element is %d\n:", x);
			break;
		case '3':
			Display();
			break;
		case '4':
			break;
		default:
			printf("\n Wrong choice!Try again:");
		}
	}
}
int Isempty() {
	if (top == -1)
		return 1;
	else
		return 0;
}
int Isfull() {
	if (top == MAXSTK - 1)
		return 1;
	else
		return 0;
}
void Push(int x) {
	if (Isfull()) {
		printf("\n Stack full");
		return;
	}
	top++;
	items[top] = x;
}
int Pop() {
	int x;
	if (Isempty()) {
		printf("\n Stack empty");
		exit(0);
	}
	x = items[top];
	top--;
	return x;
}
void Display() {
	int i;
	if (Isempty()) {
		printf("\n Stack empty");
		return;
	}
	printf("\n Elements in the Stack are :\n");
	for (i = top; i >= 0; i--)
		printf("%d\n", items[i]);
}

Output:

 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:1

 Enter the element to be pushed:10

 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:1

 Enter the element to be pushed:20

 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:1

 Enter the element to be pushed:30

 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:3

 Elements in the Stack are :
30
20
10

 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:2

 Pop element is 30
:
 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:3

 Elements in the Stack are :
20
10

 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:2

 Pop element is 20
:
 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:3

 Elements in the Stack are :
10

 1-PUSH
 2-POP
 3-DISPLAY
 4-QUIT
 Enter your choice:4

Comments