Monday, 25 August 2014

C program to implement STACK.

STACK IN C




  Stack is a LIFO data structure 
  LIFO - Last in First Out

  Perform PUSH (insert operation)
  POP (Delete operation) 
  Display (Display stack)

// CODE //


#include <stdio.h>
#include <conio.h>
#define MAXSIZE 5

int st[MAXSIZE];
int top;


/* Function declaration/Prototype*/

void push (void);
int  pop(void);
void display (void);

void main ()
{
int choice;
int option = 1;

clrscr ();

top = -1;

printf ("STACK OPERATION\n");
while (option)
{
printf ("------------------------------------------\n");
printf ("   1 --> PUSH           \n");
printf ("   2 --> POP           \n");
printf ("   3 --> DISPLAY           \n");
printf ("   4 --> EXIT   \n");
printf ("------------------------------------------\n");

printf ("Enter your choice\n");
scanf ("%d", &choice);

switch (choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: return;
}

fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}

/*Function to add an element to the stack*/
void push ()
{
int num;
if (top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
top = top + 1;
st[top] = num;
}
return;
}


/*Function to delete an element from the stack*/
int pop ()
{
int num;
if (top == - 1)
{
printf ("Stack is Empty\n");
return (top);
}
else
{
num = st[top];
printf ("poped element is = %d\n", st[top]);
top = top - 1;
}
return(num);
}

/*Function to display the status of the stack*/
void display ()
{
int i;
if (top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\nThe status of the stack is\n");
for (i = top; i >= 0; i--)
{
printf ("%d\n", st[i]);
}
}
printf ("\n");
}



Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Powered By: TechyBuz

0 comments:

Post a Comment