#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 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 returns0. Ifsize == 1, it returns1. - Recursive Step: If the current element
S[0]is not equal to the next elementS[1], it adds1to the result of the recursive call on the remaining array. Otherwise, it simply returns the result of the recursive call without adding1.
Thus, the function counts the number of adjacent mismatches () in the array and adds (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:
A[0] != A[1]() True (adds 1)A[1] != A[2]() True (adds 1)A[2] != A[3]() FalseA[3] != A[4]() FalseA[4] != A[5]() True (adds 1)A[5] != A[6]() FalseA[6] != A[7]() True (adds 1)A[7] != A[8]() False
The recursion terminates at size == 1 (for the element A[8]), returning 1.
Free practice · Your answers on this page are not saved.
