Monday, November 21, 2011

Stack in C using functions

Stack in C: Stack is a very useful data structure in C, It is used in many situations. Implementing stack can be done using a global array and a global pointer of the stack. although this implementation reveals how good OOP is for such situations. There will be three basic functions of the stack. One will be push() operation, which will push the given element to the stack. Pop() function  will pop out the element from the top. A show function to show the content of the stack.

The size of the stack will be controlled by a preprocessor called SIZE. we will always check for boundaries of the stack. Modular approach for such situation is not safe. A better OO way is there, that I will discuss later.
The code to implement Stack in C using functions is as follows :-

Code :
#include<stdio.h>
#include<dos.h>

#define SIZE 5
int cursor=0;//global
int stack[SIZE];
void initstack()
{
        int i=0;
        for(i=0;i<SIZE;i++)
       {
            stack[i]=0;//set all element of the stack to 0
         }
}
void show()
{
       int i=0;
       for(i=0;i<SIZE;i++)
       {
           printf("\n %d",stack[i]);
        }
}
void push(int v)
{
       if(cursor==SIZE)
        {
             printf("\n -----Stack is full------");
         }
         else
         {

           stack[cursor]=v;
           cursor++;
          }

}
int pop()
{
        int t;
         if(cursor==0)
         {
            printf("\n Stack is empty");
         }
        else
        {
               cursor--;
                t=stack[cursor];
              stack[cursor]=0;
          return(t);
        }
}


int main()
{
           char c='a';
           int v,k;
             k=1;

while(k)
{
               printf("\n Enter your choice: 1:Push\n 2:Pop \n3:Show \n4:Exit\nyour choice::");
               scanf("%c",&c);
               switch(c)
               {
                   case '1':
                   printf("\n enter a value:");
                  scanf("%d",&v);
                      push(v);
                      break;
                  case '2':
                  pop();
                  break;
                  case '3':
                  show();
                  break;
                  case '4':
                     k=0;//will break the while loop
                     break;
                 }



   }
}