The GATE Grind

GATE 2025 CS (CS1) – Question 61

Programming and Data Structures · Recursion · 2 marks · Numerical answer

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

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 5

Explanation

`foo` compares the first two elements of the array and recurses on the rest.

So `foo` returns $1+$ (the number of adjacent unequal pairs).

For $0,1,2,2,2,0,0,1,1$ the adjacent pairs are: $(0,1)\ne$, $(1,2)\ne$, $(2,2)=$, $(2,2)=$, $(2,0)\ne$, $(0,0)=$, $(0,1)\ne$, $(1,1)=$. That is 4 unequal pairs.

Printed value $=4+1=\mathbf{5}$.

More Recursion questions

All Recursion questions →