Predict the output:
C
#include <stdio.h> void crazy( int n, int a, int b) { if (n <= 0) return ; crazy(n - 1, a, b + n); printf ( "%d %d %d \n" ,n,a,b); crazy(n-1, b, a+n); } int main() { crazy(3, 4, 5); return 0; } |
(A)
1 4 10 2 4 8 1 8 6 3 4 5 1 5 9 2 5 7 1 7 7
(B)
3 4 5 1 4 10 2 4 8 1 8 6 1 5 9 2 5 7 1 7 7
(C)
1 4 10 2 4 8 1 8 6 3 4 5
(D)
3 4 5 1 5 9 2 5 7 1 7 7
Answer: (A)
Explanation:
Call(3,4,5)
- crazy(3, 4, 5) calls crazy(2, 4, 5 + 3)
- crazy(2, 4, 8) calls crazy(1, 4, 8 + 2)
- crazy(1, 4, 10) calls crazy(0, 4, 10 + 1)
- crazy(0, 4, 11) returns immediately as the base case is reached. and prints 1, 4, 10.
- crazy(0, 11,4). return as the base case is reached.
Now, we wrap up the recursive calls:
- call crazy(2,4,8) prints 2,4,8 and again call for crazy(1,8, 6). which will print 1,8,6.
- call crazy(3,4,5) prints 3,4,5 and again call for crazy(2,5, 7). which will again call for (1,5,9) prints 1 5 9.
- call crazy (2,5,7) prints 2,5,7 and again call for crazy(1,7,7), which will print 1,7,7.
Hence (A) is the correct Option.
Quiz of this Question
Please comment below if you find anything wrong in the above post
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!