#include <stdio.h> int foo(int S[], int size) { if(size == 0) return 0;…

2025

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

Attempted by 31 students.

Show answer & explanation

Correct answer: 5

Answer: 5

Reasoning:

The function returns the number of groups of consecutive equal elements in the array. For size 0 it returns 0, for size 1 it returns 1 (one group). For larger sizes, it compares the first two elements: if they differ it counts a new group (adds 1) and recurses on the rest; if they are equal it continues without incrementing.

Apply this to the array {0, 1, 2, 2, 2, 0, 0, 1, 1}: it splits into the consecutive groups 0 | 1 | 2 2 2 | 0 0 | 1 1, which are 5 groups in total.

  • Group 1: 0

  • Group 2: 1

  • Group 3: 2, 2, 2

  • Group 4: 0, 0

  • Group 5: 1, 1

Therefore the program prints 5.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir