C Program for Stack Operations – Using Array

Source: Dr. G T Raju, Professor & Head, Dept. of CSE, RNSIT

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
#define SIZE 5            /* Size of Stack */
int s[SIZE],top=-1;       /* Global declarations */
 
push(int elem)
{                       /* Function for PUSH operation */
    if( Sfull()) printf("\n\n Overflow!!!!\n\n");
    else
    {
        ++top;
        s[top]=elem;
    }
}
 
int pop()
{                      /* Function for POP operation */
    int elem;
    if(Sempty()){ printf("\n\nUnderflow!!!!\n\n");
    return(-1); }
    else
    {
        elem=s[top];
        top--;
        return(elem);
    }
}
 
int Sfull()
{                     /* Function to Check Stack Full */
    if(top == SIZE-1) return 1;
    return 0;
}
 
int Sempty()
{                    /* Function to Check Stack Empty */
    if(top == -1) return 1;
    return 0;
}
 
display()
{                  /* Function to display status of Stack */
    int i;
    if(Sempty()) printf(" \n Empty Stack\n");
    else
    {
        for(i=0;i<=top;i++)
            printf("%d\n",s[i]);
        printf("^Top");
    }
}
 
main()
{                         /* Main Program */
    int opn,elem;
    do
    {
        clrscr();
        printf("\n ### Stack Operations ### \n\n");
        printf("\n Press 1-Push, 2-Pop,3-Display,4-Exit\n");
        printf("\n Your option ? ");
        scanf("%d",&opn);
        switch(opn)
        {
        case 1: printf("\n\nRead the element to be pushed ?");
            scanf("%d",&elem);
            push(elem); break;
        case 2: elem=pop();
            if( elem != -1)
                printf("\n\nPopped Element is %d \n",elem);
            break;
        case 3: printf("\n\nStatus of Stack\n\n");
            display(); break;
        case 4: printf("\n\n Terminating \n\n"); break;
        default: printf("\n\nInvalid Option !!! Try Again !! \n\n");
            break;
        }
        printf("\n\n\n\n  Press a Key to Continue . . . ");
        getch();
    }while(opn != 4);
}

Leave a Reply