C language MCQ

What will the below function return when it is called for n=1 as fun(1). Treat is as the first call to fun function, so i is not initialized earlier.
    int fun(int n)
    {
        static int i = 1;
        if (n >= 5)
            return n;
        n += i;
        i++;
        return fun(n);
    }

Your options are 
A) 5    B) 6  C)7    D) 8

This question was asked in the GATE (Computer Science) Exam.

Answer: C)  7

Note that i is static variable, so it will be initialized only once. And it is only incremented by 1 per call (unlike n)

Function Call i n Incremented i
fun(1) 1 2 2
fun(2) 2 4 3
fun(4) 3 7 -

Hence the final value returned will be 7.

Tags:

C Language MCQ

0 Comments

Leave a comment