Skip to content
Official PYQ · 2025

GATE CS 2025 Set 1 Q51 — Recursion

Explain with AI

 

#include <stdio.h>
int foo(int S[],int size) {
    if(size == 0) return 0;
    if(size == 1) return 1;
    if(S[0] != S[1]) return 1+foo(S+1,size-1);
    return foo(S+1,size-1);
}
int main() {
    int A[]={0,1,2,2,2,0,0,1,1};
    printf("%d",foo(A,9));
    return 0;
}

The value printed by the given CC program is ___________. (Answer in integer)

View worked solution

Answer: 5:5

The function foo(S, size) recursively traverses the array S from left to right. Let us analyze its behavior:

  • Base Cases: If size == 0, it returns 0. If size == 1, it returns 1.
  • Recursive Step: If the current element S[0] is not equal to the next element S[1], it adds 1 to the result of the recursive call on the remaining array. Otherwise, it simply returns the result of the recursive call without adding 1.

Thus, the function counts the number of adjacent mismatches (S[i]≠S[i+1]S[i] \neq S[i+1]) in the array and adds 11 (from the base case when size == 1 is reached).

For the array A = {0, 1, 2, 2, 2, 0, 0, 1, 1} with size = 9, we check the adjacent pairs:

  1. A[0] != A[1] (0≠10 \neq 1) →\rightarrow True (adds 1)
  2. A[1] != A[2] (1≠21 \neq 2) →\rightarrow True (adds 1)
  3. A[2] != A[3] (2≠22 \neq 2) →\rightarrow False
  4. A[3] != A[4] (2≠22 \neq 2) →\rightarrow False
  5. A[4] != A[5] (2≠02 \neq 0) →\rightarrow True (adds 1)
  6. A[5] != A[6] (0≠00 \neq 0) →\rightarrow False
  7. A[6] != A[7] (0≠10 \neq 1) →\rightarrow True (adds 1)
  8. A[7] != A[8] (1≠11 \neq 1) →\rightarrow False

The recursion terminates at size == 1 (for the element A[8]), returning 1.

Total Value=1 (from transitions)+1 (from transitions)+1 (from transitions)+1 (from transitions)+1 (base case)=5\text{Total Value} = 1 \text{ (from transitions)} + 1 \text{ (from transitions)} + 1 \text{ (from transitions)} + 1 \text{ (from transitions)} + 1 \text{ (base case)} = 5

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Recursion questions