C LAB‎ > ‎(Sem2) Data Structures‎ > ‎

Qx10. WAP to implement Stack using Arrays.

posted Feb 1, 2011, 1:28 PM by Neil Mathew   [ updated Mar 14, 2011, 10:19 AM ]
SOURCE CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include<stdio.h>
 
void PUSH(int *a, int n, int *top, int ITEM)
{
     if(*top==-1) //Pushing First Element
     {
     *top=0;
     a[*top]=ITEM;
     }
     else if(*top==(n-1)) //Pushing into Filled array
     {
     printf(" OVERFLOW. DELETE SOME ELEMENTS. ");    
     }
     else //Normal conditions
     {
     *top=*top+1;
     a[*top]=ITEM;
     }
}
 
void POP(int *a, int *top)
{
     
     if(*top==-1) // Deleting from 
     {
     printf(" UNDERFLOW. INSERT SOME ELEMENTS. ");
     }
     else
     {
         *top=*top-1;
         printf("\n POPPED... \n");
     }
 
}         
     
void Display(int *a, int top)
{    printf("\n");
     int i=0;
     if (top!=-1)
     for(i=top; i>=0; i--)
     {
                printf("\n %d ",a[i]);
     }
     else
     printf(" NO ELEMENTS. \n");
     printf("\n");
}
 
 
 
int main()
{
  
int a[5];
int n=5; //max size
 
int top=-1;
 
int ch=1,ITEM;
 
while(ch!=4)
{
        printf("\n MENU: ");
        printf("\n 1. PUSH. ");
        printf("\n 2. POP. ");
        printf("\n 3. DISPLAY. ");
        printf("\n 4. EXIT. ");
        printf("\n Your Choice: ");
        
        scanf("%d",&ch);
        
        switch(ch)
        {
                  case 1: //INSERT
                          printf("\n ENTER ITEM: ");
                          scanf("%d",&ITEM);
                          
                          PUSH(a,n,&top, ITEM);
                          break;
                  
                  case 2: //DELETE
                          POP(a,&top);
                          break;
                          
                  case 3: //DISPLAY
                          Display(a,top);
                          break;
                  
                  case 4: printf("\n Exiting... ");
                          
        }
        
}              
  
  return 0;
}
 

OUTPUT:

 MENU:
 1. PUSH.
 2. POP.
 3. DISPLAY.
 4. EXIT.
 Your Choice: 1

 ENTER ITEM: 56

 MENU:
 1. PUSH.
 2. POP.
 3. DISPLAY.
 4. EXIT.
 Your Choice: 1

 ENTER ITEM: 89

 MENU:
 1. PUSH.
 2. POP.
 3. DISPLAY.
 4. EXIT.
 Your Choice: 3


 89
 56

 MENU:
 1. PUSH.
 2. POP.
 3. DISPLAY.
 4. EXIT.
 Your Choice: 2

 POPPED...

 MENU:
 1. PUSH.
 2. POP.
 3. DISPLAY.
 4. EXIT.
 Your Choice: 3


 56

 MENU:
 1. PUSH.
 2. POP.
 3. DISPLAY.
 4. EXIT.
 Your Choice: 4

 Exiting...


Comments