IAE Academy

GATE 2024 CS1 Q.48: solution and answer

GATE 2024 · CS1Q.48 · 2 marks · MSQ

Consider the following C function definition.

int f(int x, int y) {
  for (int i=0; i<y; i++) {
    x=x+x+y;
  }
  return x;
}

Which of the following statements is/are TRUE about the above function?

  1. (A)

    If the inputs are x=20, y=10, then the return value is greater than

  2. (B)

    If the inputs are x=20, y=20, then the return value is greater than

  3. (C)

    If the inputs are x=20, y=10, then the return value is less than

  4. (D)

    If the inputs are x=10, y=20, then the return value is greater than

See the question in the paper

Answer and solution

ANSWER

Statements (B) and (D) are TRUE; the correct answer is (B) and (D).

Official answer: B, DSource: Official answer key, GATE 2024 CS1 (IISc Bengaluru)

  1. The for (int i=0; i<y; i++) loop executes exactly times (i = 0 to y−1), and each iteration performs x=x+x+y, i.e. .

  2. This defines the linear recurrence with (the input value of x).

  3. Solving by unrolling/induction: , , and in general .

  4. So the value returned after the loop (n = y iterations) is

  5. (A) x=20, y=10: . Since and , statement (A) is FALSE.

  6. (B) x=20, y=20: , which is greater than . Statement (B) is TRUE.

  7. (C) x=20, y=10: (from step 5), and . Since , the claim 'less than ' is FALSE.

  8. (D) x=10, y=20: , which is greater than . Statement (D) is TRUE.

  9. Only (B) and (D) are TRUE.

KEY IDEA

The loop runs exactly times, and each iteration replaces x by x=x+x+y, i.e. the linear recurrence . Unrolling this recurrence gives a closed form , which lets every option be checked by a single arithmetic comparison instead of by re-running the loop by hand.

WATCH OUT FOR

Reading x=x+x+y as x = 2x and forgetting the +y term each iteration (or, symmetrically, treating the recurrence as instead of ), which changes the growth rate and can flip (D) to false when it is actually true; also common is comparing the final value to instead of the specific power asked for in each option (e.g. checking against for option A instead of ).

From the GATE 2024 CS1 paper. Every question of this paper · Download the full paper · All 7 C basics questions, with notes

More C basics questions