Free Web Hosting Provider - Web Hosting - E-commerce - High Speed Internet - Free Web Page
Search the Web

Stacks->Array Implementation->Push operation

Here, as you might have noticed, addition of an element is known as the PUSH operation. So, if an array is given to you which is supposed to act as a STACK, you know that it has to be a STATIC Stack; meaning, data will overflow if you cross the upper limit of the array. So, keep this in mind.

Algorithm:-
Step-1: Increment the Stack TOP by 1. Check whether it is < UpperLimit of the stack. If it is < the UpperLimit go to step-2 else say -"Stack Overflow"
Step-2: Put the new element at the position pointed by the TOP

C implementation:-
static int stack[uplimit];
int top=-1; /*stack is empty*/
..
..
main()
{
..
..
push(newvalue);
..
push(newvalue);
..
}

push(int new)
{
      top = top + 1;
      if(top < uplimit) stack[top] = new; /*step-1 & 2*/
        else
          printf("Stack Overflow");
}

Damn simple, no! I think no more comments are needed for this...

Note:- In array implementation, I have taken TOP = -1 to signify the empty stack, as this simplifies the implementation.

Related Operations:
Concept
Array Implementation - Push() and Pop()
Linked List Implementation - Push() and Pop()
Application of Stacks

Index || Doubts / Clarifications || Related Topics || Web Links