C program to create stack using array.

Posted by Mangesh on April 11, 2018

/* program to implement stack. */

Description :

Stack is a container that is use to store objects. It use principle of First In Last Out. Stacks are data structures that allow us to insert and remove items. The operate like a stack of papers or books on our desk - we add new things to the top of the stack to make the stack bigger, and remove items from the top as well to make the stack smaller. This makes stacks a LIFO (Last In First Out) data structure – the data we have put in last is what we will get out first.

Program :

#include<stdio.h>
#include<conio.h>
#define limit 100
void push(int *top,int x,int arr[limit])
{
  *top = *top + 1;
  arr[*top] = x;
}
int empty(int top)
{
 if(top == -1)
   return 1;
return 0;
}
void pop(int *top,int arr[limit])
{
  if(empty(*top))
    printf("\nArray is already empty!!!");
  else{
  *top = *top - 1;
  }

}
void printarray(int top,int arr[limit])
{
  int i;
  printf("\nElements in stack are : ");
  for(i=0;i<=top;i++)
    printf("%d ",arr[i]);
}
void main()
{
int arr[limit];
int top = -1,x,choice,i;
clrscr();
do{
printf("\n\n1.Push.\n2.Pop.\n3.Get top value.\n4.Exit");
printf("\nEnter the choice : ");
scanf("%d",&choice);
  switch(choice)
  {
  case 1 :
   printf("Enter the element in stack : ");
   scanf("%d",&x);
   push(&top,x,arr);
   printarray(top,arr);
  break;
  case 2 :
   pop(&top,arr);
   printf("Element poped");
   printarray(top,arr);
  break;
  case 3:
   printf("top of stack is at %d",top);
  break;
  case 4:
   printf("exiting...");
  break;
  default :
   printf("invalid choice!!!");
  break;
  }
}while(choice!=4);
getch();
}

Output :

Output of push operation : c program for stack push Executed and tested in Turbo C 3.2 Output of pop operation : c program for stack pop Executed and tested in Turbo C 3.2

Written with from Mangesh.

Related Post
1 C program to create stack using array.
Latest Post
1 shubhanshu
2 test
3 C program for Breadth First Search.
4 C program for Depth First Search(DFS).
5 C for circular queue using linked list.