Question:

The value printed by the given C program is __________ (Answer in integer).

Show Hint

To trace recursive functions, break down each recursive call step by step and evaluate the base cases and recursive conditions. This helps in understanding how the function processes the data.
Updated On: Jan 30, 2026
Hide Solution
collegedunia
Verified By Collegedunia

Correct Answer: 5

Solution and Explanation

We are given the following C program:#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,2,0,0,1,1};    printf("%d",foo(A,9));    return 0; } The function `foo` performs the following steps: 1. Base Case 1: If the size is 0, it returns 0.
2. Base Case 2: If the size is 1, it returns 1.
3. Recursive Case: If the first element of the array is different from the second, it returns 1 plus the result of the recursive call on the rest of the array. If the first and second elements are the same, it simply recurses on the next part of the array without adding 1. We are tasked with finding the value of `foo(A, 9)`.
Initial call is `foo(A, 9)`, where \( A = [0, 1, 2, 2, 2, 2, 0, 0, 1, 1] \).
Step-by-step execution:
`foo(A, 9)` → `S[0] = 0`, `S[1] = 1` (different), so return `1 + foo(A+1, 8)`
`foo(A+1, 8)` → `S[0] = 1`, `S[1] = 2` (different), so return `1 + foo(A+2, 7)`
`foo(A+2, 7)` → `S[0] = 2`, `S[1] = 2` (same), so return `foo(A+3, 6)`
`foo(A+3, 6)` → `S[0] = 2`, `S[1] = 2` (same), so return `foo(A+4, 5)`
- `foo(A+4, 5)` → `S[0] = 2`, `S[1] = 2` (same), so return `foo(A+5, 4)`
`foo(A+5, 4)` → `S[0] = 2`, `S[1] = 0` (different), so return `1 + foo(A+6, 3)`
`foo(A+6, 3)` → `S[0] = 0`, `S[1] = 0` (same), so return `foo(A+7, 2)`
`foo(A+7, 2)` → `S[0] = 0`, `S[1] = 1` (different), so return `1 + foo(A+8, 1)`
`foo(A+8, 1)` → size is 1, so return 1.
Thus, the total count is: \( 1 + 1 + 0 + 0 + 0 + 1 + 0 + 1 + 1 = 5 \). 
Final result: The value printed is 5.

Was this answer helpful?
0
0

Top Questions on Programming and Data Structures

View More Questions