Implementation of Stack Using Array in C

In this we will learn the Implementation of Stack Using Array in C

Stack.

1. What is a stack?
ANS.: An ordered collection of elements using the LIFO(Last in First Out) mechanism.

2. Operations performed on the stack?
ANS.: Push (insertion), pop (deletion), peek (Topmost element) & display.

3. Applications of the stack?
ANS.: Infix, Postfix, and Prefix notations, Recursive functions, Function cell, Expression evaluation etc

Graphical Representation.

Implementation of Stack Using Array in C

Implementation of Stack Using Array in C

Source code.
#include<conio.h>
#include<stdio.h>
#define SIZE 4

int stack[SIZE];
int top=-1;

int empty();
int full();
void display();
void pop();
void push(int);

int main()
{
	
        printf("push elements\n");
	push(10);//10
	push(20);//10 20
	push(30);//10 20 30
        push(40);// 10 20 30 40
	push(15);//error full
        printf("pop elements.\n ");
	pop();//10 20 30
	pop();//10 20
	pop();// 10
	pop();//error empty
        getch();
}

int empty()
{
	if(top==-1)
		return 1;
	else
		return 0;
}

int full()
{
	if(top==SIZE-1)
		return 1;
	else
		return 0;
}

void display()
{
	int i;
	printf("Stack:");
	for(i=0; i<=top; i++)
        printf("%d ",stack[i]);
	printf("\n");
}

void push(int val)
{
	if(full())
	{
		printf("Error : 
                Stack full\n");
	}
	else
	{
		stack[++top]=val;
		display();
	}
}

void pop()
{
	int i,loc;
	if(empty())
	{
	      printf("Error : 
             Stack empty\n");
	}
	else
	{    top--;
             display();
	}
}

Also, you can use the C compiler to compile a program.

Output.

push stack.
Stack: 10
Stack: 10 20
Stack: 10 20 3O
Stack: 10 20 3O 40
Error : Stack full
pop stack.
Stack: 10 20 3O
Stack: 10 20
Stack: 10
Stack: 

Also View:Queue using linked list.

About Ashishkumar Vishwakarma

I am Ashish- a Developer live in Mumbai.

View all posts by Ashishkumar Vishwakarma →

One Comment on “Implementation of Stack Using Array in C”

Leave a Reply