Recursion
![Question 61, GATE 2025: In C, foo(S,size) returns 0 for size=0, 1 for size=1, otherwise returns 1+foo(S+1,size−1) if S[0]≠S[1], and foo(S+1,size−1) otherwise. main prints foo(A,9) for A={0,1,2,2,2,0,0,1,1}. What is printed?](../../assets/questions/CS-2025-S1-Q61-1.webp)
Answer & solution
Official answer: 5
Step through it (17 steps)
Approach: Interpret each recursive step as testing one adjacent boundary, with the final single element supplying the first run count.
For a nonempty array, every call with size greater than one advances the pointer by one and decreases size by one. It adds 1 exactly when the two currently adjacent values differ. The size-one base case returns 1, so the total is 1 plus the number of adjacent changes.
Here the adjacent-change indicators are 1,1,0,0,1,0,1,0 for the pairs (0,1),(1,2),(2,2),(2,2),(2,0),(0,0),(0,1),(1,1). Their sum is 4; adding the base-case 1 yields 5.
Equivalently, the maximal equal-value runs are [0], [1], [2,2,2], [0,0], [1,1]. There are five runs, so the program prints 5. It does not count distinct numerical values; although only 0,1,2 occur, repeated values separated into different runs contribute separately.