Search

Tuesday, March 4, 2014
0 comments

Representing STACK using one-dimensional ARRAY in 'C'

5:51 AMTuesday, March 4, 2014
Representing STACK using one-dimensional ARRAY 

             STACK can be represented either horizontally or vertically as consecutive memory cells if it is implemented by Array. A variable TOP is used to store the current index. Initially when the STACK is empty TOP contains a 0 index when the lower bound of array is 1, it can be stored with -1 if the lower bound is 0.
   
Horizontal representation:


When ITEM is to be PUSHed, TOP is incremented by 1 and at TOP position of Array the ITEM is placed. When TOP is equal to N, the size of STACK, and PUSH operation is done, then ‘Overflow’ occurs. If an ITEM is to be POPped from the STACK, the ITEM placed at TOP index is removed (deleted) and TOP is decremented by 1. Remember here when deletion is done, the items stored in array are not changed only the index is changed. When POP operation is applied to an empty STACK (STACK is empty when TOP is 0) ‘Underflow’ occurs. 

Example 1: Consider a STACK of size 6.
PUSH 6 on to STACK. TOP is incremented by 1 and 6 is placed in the STACK at TOP position. TOP<---TOP+1 and STACK [TOP]<---6.
PUSH 7and 3 on STACK. To PUSH 7 TOP is incremented by 1 and 7 is placed at TOP position that is at second position. To PUSH 3 again TOP is incremented by 1 and 3 is placed at TOP position that is at third position. After these two operations the STACK becomes:
POP the STACK. To POP the ITEM stored at TOP index is copied in a variable, ITEM<---STACK[TOP],  and TOP is decremented by 1.
Example 2 Consider a STACK of size 8. The string “INDIA” CAN BE reversed using STACK.
                                                                              
Now repeatedly POP till the STACK is empty and write the POPped characters you will get the reversed string, AIDNI
Example 3: Consider a STACK of size 8. Using the STACK convert a decimal number 52 to binary number.

½=0, STOP. STACK creation is over. Now repeatedly POP till STACK is empty and write the POPped number you will get the binary equivalent of 52 i.e. 110100. 

       STACK is also used to evaluate a POSTFIX expression value and to convert an INFIX expression to POSTFIX expression.

Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top