0% found this document useful (0 votes)
88 views

Stack Using C Programming

The document defines functions for a stack data structure including push(), pop(), peek(), isEmpty(), isFull(), and traverse(). It uses a static array to store the stack elements and a top variable to track the current top index. The main() function contains a menu loop that calls the stack functions and allows the user to push, pop, peek at, and traverse the stack until quitting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views

Stack Using C Programming

The document defines functions for a stack data structure including push(), pop(), peek(), isEmpty(), isFull(), and traverse(). It uses a static array to store the stack elements and a top variable to track the current top index. The main() function contains a menu loop that calls the stack functions and allows the user to push, pop, peek at, and traverse the stack until quitting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 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