Stack Implementation in C

Stack are the data structures, working on the principle of Last In First Out. In this C program, the stack class is implemented without using the container.

#include<stdio.h>
#include<stdlib.h>
#define CAPACITY 5
int stack[CAPACITY],top=-1;
void push(int);
int isFull();
void pop();
void traverse();
int isEmpty();
void peek();
int main(){
	int ch,item;
	while(1){
		printf("1. Push \n");
		printf("2. Pop \n");
		printf("3. Traverse \n");
		printf("4. Peek \n");
		printf("5. Exit \n");
		printf("Enter your choice ");
		scanf("%d",&ch);
		switch(ch){
			case 1:	printf("Enter the value to push : ");
				scanf("%d",&item);
				push(item);
				break;
			case 2:	pop();
				break;
			case 3: traverse();
				break;
			case 4:	peek();
				break;
			case 5: exit(0);
			default : printf("Not a valid Number\n");break;
		}
	}
	return 0;
}

void push(int k){
	if(isFull()){
		printf("It is full\n");
		return;
	}
	else{
		top++;
		stack[top] = k;
		printf("Element pushed\n");
		return;
	}
}
int isFull(){
	if(top==(CAPACITY-1)){
		return 1;
	}
	else{
		return 0;
	}
}
void pop(){
	if(isEmpty()){
		printf("Stack is Empty\n");
	}
	else{
		top--;
		printf("Element returned\n");
	}
}
void traverse(){
	if(isEmpty()){
		printf("Stack is Empty\n");
	}
	else{
		printf("The elements are ");
		for(int i=0;i<=top;i++){
			printf("%d ",stack[i]);
		}
		printf("\n");
	}
}
int isEmpty(){
	if(top==-1){
		return 1;
	}
	else{
		return 0;
	}
}
void peek(){
	if(isEmpty()){
		printf("Stack is Empty\n");
	}
	else{
		printf("Top element is %d : ",stack[top]);
	}
}
output of the above program. stack
output of the above program. stack

Leave a Reply