10,555 views
35 votes
35 votes

Consider the C program below

#include <stdio.h>
int *A, stkTop;
int stkFunc (int opcode, int val)
{
    static int size=0, stkTop=0;
    switch (opcode) {
        case -1: size = val; break;
        case 0: if (stkTop < size ) A[stkTop++]=val; break;
        default: if (stkTop) return A[--stkTop];
    }
    return -1;
}
int main()
{
    int B[20]; A=B; stkTop = -1;
    stkFunc (-1, 10);
    stkFunc (0, 5);
    stkFunc (0, 10);
    printf ("%d\n", stkFunc(1, 0)+ stkFunc(1, 0));
}

The value printed by the above program is ________.

4 Answers

47 votes
47 votes

Initially stack is empty = -1

stkFunc (-1, 10); this function

case -1: size = val; break; and static size= 10 // size memory declare one time only// and control comes out of switch b/c of break

stkFunc (0, 5); this function run

case 0: if (stkTop < size ) A[stkTop++]=val; break; here stktop is static value so memory declare at compile time only now check if condition 0< 10 true then A[stktop++== A[0+1]=val= 5 i.e. push 5 into stack break comes so control comes outside

stkFunc (0, 10); this comes

case 0: if (stkTop < size ) A[stkTop++]=val; break; same as above make A[stkTop++]= 10 i,e. push 10 into stack and break comes so control comes outside

printf ("%d\n", stkFunc(1, 0)+ stkFunc(1, 0));

this function  

stkFunc(1, 0) this will run

default: if (stkTop) return A[--stkTop] return top of stack which is 10

stkFunc(1, 0) this will run

default: if (stkTop) return A[--stkTop] return top of stack which is 5

printf ("%d\n", stkFunc(1, 0)+ stkFunc(1, 0));= 5+10=15 15 will be printed

edited by
7 votes
7 votes
By Analyzing the above code it shows that.. this is simply stack implementation with 3 choices:-

Case (-1):-->>[Set Size of the Stack]

Code :-->>size = val

Case (0):-->>[ Push Operation]

                 Step1:- verify stack is full or not?

                 Step2:-  If not full then push the  element  in stkTop And increment stkTop.

                  Code:-->>if (stkTop < size )    //   step1

                  A[stkTop++]=val;  //step 2+3

Case (default):--(here when 1 is as choice)[Pop Operation]

                  step1:-> if stack is not empty thenPop the element from stkTop

                 Step2:->decrement stkTop

                 Code:->>if (stkTop) return A[--stkTop];// step 1+2

 

So simply in this program

1.set stack size 10

2.push 2 elements in top of the stack as

5 and 10

3.pop both ;then add them

So result is 15.

PS:->>But in exam we should directly trace the code and write the answer.
Answer:

Related questions

35 votes
35 votes
12 answers
1
go_editor asked Feb 12, 2015
30,005 views
A binary tree T has $20$ leaves. The number of nodes in T having two children is ______.
35 votes
35 votes
4 answers
2