Consider the following ANSI-C function. The maximum possible value that can be…

2026

Consider the following ANSI-C function.

image.png

The maximum possible value that can be returned from this function is ____________. (answer in integer)

Attempted by 21 students.

Show answer & explanation

Correct answer: 1

To find the maximum return value, we analyze how the 'length' variable changes in each recursive call.

1. If length % 3 == 0: length decreases by 1 (start increases by 1).

2. If length % 3 == 1: length decreases by 1 (end decreases by 1), and 1 is added to the result.

3. If length % 3 == 2: length decreases by 2 (start increases by 2).

Notice the cycle of remainders modulo 3:

- From 1 mod 3, we go to 0 mod 3 (add 1).

- From 0 mod 3, we go to 2 mod 3 (subtract 1).

- From 2 mod 3, we go to 0 mod 3 (subtract 2).

Once the length is not congruent to 1 mod 3, it enters a cycle between 0 and 2, never returning to 1. Thus, the value '1' is added at most once.

The maximum possible value is 1.

Explore the full course: Gate Guidance By Sanchit Sir