Page 145 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 145

Fundamentals of Data Structures




                    Notes              printf(“ STACK FULL, cannot insert more elements”);
                                       exit(0);
                                     }
                                   stack[top]=element; /*Inserting an element to the stack which is an
                                   array*/
                                   printf(“THE TOP OF STACK IS %d”, stack[top]);
                                   }
                                   In the above code we can notice that line starts the beginning of the push() function which
                                   accepts one argument that is the element to be inserted. The first operation we perform is to
                                   increment the variable top which is a variable that holds the index value of the array and
                                   practically holds the value of the TOP of stack. Initially the value of top is initialized to –1 which
                                   means that the stack is empty initially. Hence it is incremented first so that the value of top will
                                   be zero and it will be the first index of the array.

                                                            Figure 9.8: TOP = -1(no elements)



























                                   Source: http://newtonapples.com/operations-on-stack-c-language/

                                   The variable size holds the size of the stack, i.e. the value of it suggests the maximum elements
                                   that can be accepted by the stack. Hence in line 4 the condition top == stack-1 suggests practically
                                   if the stack is full or not. The stack full condition is even known as stack overflow.




                                     Notes  The top variable increments on every insertion of element and when the value of
                                     top is equal to the value of size–1 (–1 since stack is an array and it starts with 0), it means
                                     that the stack cannot accept more elements.

                                   Hence in line 5 we print a message that the stack is full and we cannot insert more elements. Line
                                   6 executes the exit() function because it is not logical to get further in the function since we
                                   cannot insert any more elements.








          138                               LOVELY PROFESSIONAL UNIVERSITY
   140   141   142   143   144   145   146   147   148   149   150