GATE CS 2025 Set 1 | Question 61

NAT · 2 marks

#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)

Answer

5

Explanation

Each call compares the first two elements and then moves one place to the right. It adds 1 whenever the two neighbours differ, and the last single element adds 1 more (the size 1 case). So foo returns the number of unequal neighbour pairs plus 1, which is the number of runs of equal values.

In 0, 1, 2, 2, 2, 0, 0, 1, 1 there are 4 unequal pairs: (0, 1), (1, 2), (2, 0) and (0, 1). They split the array into the runs 0 | 1 | 2 2 2 | 0 0 | 1 1.

Value printed \(= 4 + 1 = 5\).

Answer: 5