Tuesday, 20 September 2011

IMPLEMENTATION OF STACKS USING ARRAYS IN C

Datastructures is an important subject in CS engineering.Implementation of stacks using arrays is a common concept.If you google "implementation of stack using arrays", you will find hundreds of programs explaining this. Most of the programs would have declared array globally, but finding the program which uses structures is difficult :P .So I thought of uploading my program.

Here's the program in C:


#include<stdio.h>
#define SIZE 100

struct stack
{
 int top;
 int array[SIZE];
}s;



void push(int x)
{
 if((s.top)==(SIZE-1))
 printf("STACK OVERFLOW\n");
 (s.array[++(s.top)])=x;
}

int pop(int x)
{
 if((s.top)==-1)
 printf("STACK UNDERFLOW\n");
 else
 printf("The element popped out of the stack is %d\n",s.array[(s.top)--]);
}

void display()
{
 int i;
 if((s.top)==-1)
  printf("STACK IS EMPTY\n");
 else
 {
  printf("The contents of the stack are:\n");
  for(i=s.top;i>=0;i--)
   printf("%d\n",s.array[i]);
 }
}

int main()
{
 int ch,x;
 s.top = -1;
 while(1)
 {
  printf("Enter your choice of operation\n");
  printf("1.PUSH\n2.POP\n3.DISPLAY THE STACK\n4.EXIT\n");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1: printf("Enter the element to be pushed\n");
             scanf("%d",&x);
             push(x);
             break;
   case 2: pop(x);
              break;
   case 3: display();
              break;
   default:return;
         
  }
 }
}

No comments:

Post a Comment