• edited by
514 views
1 1 vote

#include <stdio.h>

int mystery(int n) {
    if (n == 0) {
        return 0;
    } else if (n % 2 == 0) {
        return mystery(n / 2);
    } else {
        return 1 + mystery(n / 2);
    }
}

int main() {
    int result = mystery(13);
    printf("%d\n", result);
    return 0;
}


What will be the output of the program?

2 Answers

1 1 vote
Output will be 3.

In the first iteration n= 13 so return 1+ f(13/6)

In the 2nd iteration n = 6 so return f(3)

In the 3rd iteration n= 3 so return 1 + f(3/2)

In the 4th iteration n = 2 so return f(2/1)

In the 5th iteration n= 1 so return 1+ f(1/2)

In the 6th iteration n=0 so return 0

Hence finally return = 1 + 1+1 = 3

So, result= 3

So , 3 will be output of the program.
0 0 votes
mystery(13) → 13 is ODD  → 1 + mystery(6)
mystery(6)  → 6  is EVEN →     mystery(3)
mystery(3)  → 3  is ODD  → 1 + mystery(1)
mystery(1)  → 1  is ODD  → 1 + mystery(0)
mystery(0)  → BASE CASE  → 0

ans 3
Position:
Show:

Related questions

2 2 votes
3 answers 3 answers
1.9k
1.9k views
jverma asked May 23, 2022
1,856 views
#include <stdio.h>int f(int n){ static int r = 0; if (n <= 0) return 1; r=n; return f(n-1) + r;}int main() { printf("output is %d", f(5)); return 0;}Ou...
5 5 votes
2 2 answers
230
230 views
GO Classes asked Jun 13
230 views
What is the output of the following code?#include <stdio.h int sum(int n) { if (n == 1) return 1; return n + sum(n - 1); } int main() { printf("%d", sum(5)); return 0; }
0 0 votes
1 1 answer
1.3k
1.3k views
Manisha Jaishwal asked Aug 6, 2022
1,307 views
Consider the following recursive function which is used by dynamic programming. T(n) = { 0; if n<1 1; if n=1 T(n-1)+T(n-2)+1; if n>1}Assume ...
4 4 votes
3 answers 3 answers
2.1k
2.1k views
Diksha Aswal asked Jun 27, 2017
2,061 views
int fun(int n) { int s=0,i; if(n<=1) return 1; for(i=1; i*i<n; i++) s+=n; return fun(n/4)+fun(n/4)+s; } what will be the time complexity, returning value and no. of recur...