Stack Using C Programming

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

#include<stdio.

h>
#define SIZE 5

int stack[SIZE], top=-1 ;

void push(int);
int peek(void);
int pop(void);
int isEmpty(void);
int isFull(void);
void traverse(void);

int main()
{
int ch, ele;
while(1)
{
printf("1. Push \n");
printf("2. Peek \n");
printf("3. Pop \n");
printf("4. Traverse \n");
printf("5. Quit \n");

printf("Enter your choice : ");


scanf("%d", &ch);

switch(ch)
{
case 1 : printf("Enter element to push : \n");
scanf("%d", &ele);
push(ele);
break ;

case 2 : ele = peek();


if(ele==0)
printf("Stack is Empty \n\n");
else
printf("Peek element is : %d \n\n", ele);
break;

case 3 : ele = pop();


if(ele==0)
printf("Stack is Empty \n\n");
else
printf("Popped element is : %d \n\n", ele);
break;

case 4 : traverse();
break;

case 5 : exit(0);

default: printf("Invalid choice\n\n");


}
}
return 0;
}

void push(int ele)


{
if(isFull())
{
printf("Stack is Full \n\n");
}
else
{
++top;
stack[top] = ele;
printf("Element pushed on to the stack \n\n");
}
}

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

int peek(void)
{
if(isEmpty())
{
return 0;
}
else
{
return stack[top];
}
}

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

int pop()
{
if(isEmpty())
{
return 0;
}
else
{
int ele = stack[top];
--top;
return ele;
}
}

void traverse()
{
if(isEmpty())
{
printf("Stack is Empty \n\n");
}
else
{
int i;
printf("Stack elements are : \n");
for(i=top ; i>=0 ; i--)
{
printf("%d \n", stack[i]);
}
}
}

You might also like