Tuesday 1 July 2014

Stack in C Language

Stack in C Language
A Stack is a linear data structure in which a data item is inserted and deleted at one record. A stack is called a Last In First Out (LIFO) structure. Because the data item inserted last is the data item deleted first from the stack.
Stacks are used most used is system software such as compilers, operating systems, etc.In fact, many compilers store the local variables inside a function on the stack.
Writing a value to the stack is called as a 'Push' operation, where as reading a value from it is called as a 'Pop' operation. A pop operation in stack is destructive. That is, once an item is popped from stack, then it is no longer available.

Simple Program on Stack : 
   
 #include <stdio.h>
    #define Stacksize 5
    void push(int);
    int pop();
    //int getSize();
    int s[Stacksize];
    int top=-1;
    void main()
    {
        int k;
        push (33);
        push (44);
        push (77);
        k=pop();
        printf("\n popped element : %d",k);
        k=pop();
        printf("\n popped element : %d",k);
       
    }
    void push(int ele)
    {
         if(top==(Stacksize-1))
        {
             printf("\n Stack overflow");
             return;
        }
         else
        {
             s[++top]=ele;
        }
    }
    int pop()
    {
         if(top==-1)
        {
             printf("\n Stack underflow");
             return -1;
        }
         else
        {
             return s[top--];
        }
    }
----------------------------------------------------------------------------------------------------
Article by
--------------
CSE Department
Mother Teresa Institute of science and technology (MIST) 



No comments:

Post a Comment