Question

#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 C program is _______ . (Answer in integer)

Official answer and solution
Official answer
5
From
Official GATE 2025 answer key

Solution

Observe that foo(S, size) counts 1 for the final element plus 1 for each adjacent pair with S[i] != S[i+1], which equals the number of contiguous runs of identical elements.

For A = {0, 1, 2, 2, 2, 0, 0, 1, 1} of size = 9:

  • foo adds 1 whenever S[0] != S[1] (a transition between adjacent elements) and returns 1 at the base case size == 1.
  • In {0, 1, 2, 2, 2, 0, 0, 1, 1}, the transitions A[i] != A[i+1] occur at:
    1. 0 != 1
    2. 1 != 2
    3. 2 != 0
    4. 0 != 1
  • Adding 1 from the base case size == 1 gives 4+1=54 + 1 = 5 (the 5 contiguous runs [0], [1], [2,2,2], [0,0], [1,1]).
Final answer

5

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2025 Computer Science and Information Technology - Session 1 (CS1)
Question
61 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.