Oct 11, 2011

C Program for Stack Operations using arrays.

Data structures using C,
Stack is a data structure in which the objects are arranged in a non linear order. In stack, elements are added or deleted from only one end, i.e. top of the stack. Here we implement the PUSH, POP, DISPLAY stack operations using the array. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                                  Happy Coding
***********************************************************/
#include<stdio.h>
#define SIZE 5            /* Size of Stack */
int s[SIZE], top = -1; /* Global declarations */

push(int elem) { /* Function for PUSH operation */
 if (Sfull())
  printf("\n\n Overflow!!!!\n\n");
 else {
  ++top;
  s[top] = elem;
 }
}

int pop() { /* Function for POP operation */
 int elem;
 if (Sempty()) {
  printf("\n\nUnderflow!!!!\n\n");
  return (-1);
 } else {
  elem = s[top];
  top--;
  return (elem);
 }
}

int Sfull() { /* Function to Check Stack Full */
 if (top == SIZE - 1)
  return 1;
 return 0;
}

int Sempty() { /* Function to Check Stack Empty */
 if (top == -1)
  return 1;
 return 0;
}

display() { /* Function to display status of Stack */
 int i;
 if (Sempty())
  printf(" \n Empty Stack\n");
 else {
  for (i = 0; i <= top; i++)
   printf("%d\n", s[i]);
  printf("^Top");
 }
}

main() { /* Main Program */
 int opn, elem;
 do {
  clrscr();
  printf("\n ### Stack Operations ### \n\n");
  printf("\n Press 1-Push, 2-Pop,3-Display,4-Exit\n");
  printf("\n Your option ? ");
  scanf("%d", &opn);
  switch (opn) {
  case 1:
   printf("\n\nRead the element to be pushed ?");
   scanf("%d", &elem);
   push(elem);
   break;
  case 2:
   elem = pop();
   if (elem != -1)
    printf("\n\nPopped Element is %d \n", elem);
   break;
  case 3:
   printf("\n\nStatus of Stack\n\n");
   display();
   break;
  case 4:
   printf("\n\n Terminating \n\n");
   break;
  default:
   printf("\n\nInvalid Option !!! Try Again !! \n\n");
   break;
  }
  printf("\n\n\n\n  Press a Key to Continue . . . ");
  getch();
 } while (opn != 4);
}

 
Read more Similar C Programs
Data Structures

Learn C Programming
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!