Skip to content

Instantly share code, notes, and snippets.

@M2skills
Created November 12, 2016 11:35
Show Gist options
  • Save M2skills/6c570c134ea99a2e8e497c67581e2b1b to your computer and use it in GitHub Desktop.
Save M2skills/6c570c134ea99a2e8e497c67581e2b1b to your computer and use it in GitHub Desktop.
Simple Stack implementation in C
/* program for stack implementation in c*/
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
//global variables
int stackk[20],top;
//function definition
void push(int);
int pop();
int main()
{
int element,cont,choice,i;
top=-1;
cont=1;
do
{
printf("\nTHE FOLLOWING CHOICES ARE AVAILIABLE : ");
printf("\n1.PUSH AN ELEMENT");
printf("\n2.POP AN ELEMENT");
printf("\n3.VIEW STACK CONTENTS");
printf("\nENTER YOUR CHOICE : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nENTER THE ELEMENT TO BE PUSHED : ");
scanf("%d",&element);
push(element);
break;
case 2:
element=pop();
if(element!=99999)
{
printf("\nTHE ELEMENT POPPED IS : %d",element);
}
break;
case 3:
printf("\nTHE ELEMENTS OF STACK ARE : ");
for(i=0;i<=top;i++)
{
printf("\n%d",stackk[i]);
}
}
printf("\nDO YOU WANT TO CONTINUE (1/0): ");
scanf("%d",&cont);
}while(cont==1);
return 0;
}
void push(int element)
{
//increment top value
top++;
//check if stack is full
if(top==20)
{
printf("\nSTACKFULL!!!!!");
}
else
{
stackk[top]=element;
printf("\nELEMENT PUSHED!!");
}
return;
}
int pop()
{
int element;
//check if stack is empty
if(top<0)
{
printf("\nSTACKEMPTY!!!!!");
//consider all elements are smaller than 99999
return 99999; //returning 99999 to indicate stackempty
}
else
{
element=stackk[top];
top--;
return element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment