Skip to content
Official PYQ · 2024

GATE CS 2024 Set 1 Q38 — Programming in C

Explain with AI

​​Consider the following C\mathrm{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?

Select all correct options
View worked solution

Answer: B;D

To find the value returned by the function f(x, y), let us trace the value of xx after each iteration of the loop.

Let xix_i denote the value of xx after the ii-th iteration of the loop, with x0=xx_0 = x being the initial value.

The loop runs for i=0i = 0 to y−1y-1, which is exactly yy iterations. The recurrence relation is:

xi=2xi−1+yx_i = 2x_{i-1} + y

Let us expand this recurrence step-by-step:

x1=2x0+yx2=2(2x0+y)+y=22x0+(2+1)yx3=2(22x0+3y)+y=23x0+(4+2+1)y⋮xk=2kx0+(2k−1+2k−2+⋯+1)y=2kx0+(2k−1)y\begin{aligned} x_1 &= 2x_0 + y \\ x_2 &= 2(2x_0 + y) + y = 2^2 x_0 + (2 + 1)y \\ x_3 &= 2(2^2 x_0 + 3y) + y = 2^3 x_0 + (4 + 2 + 1)y \\ &\vdots \\ x_k &= 2^k x_0 + (2^{k-1} + 2^{k-2} + \dots + 1)y \\ &= 2^k x_0 + (2^k - 1)y \end{aligned}

Since the loop runs for yy iterations, the final value returned is xyx_y:

xy=2yx+(2y−1)y=2y(x+y)−yx_y = 2^y x + (2^y - 1)y = 2^y(x + y) - y

Now, let us evaluate each option using this closed-form expression:

  • Options A & C: x=20,y=10x = 20, y = 10 x10=210(20+10)−10=30⋅210−10=30⋅1024−10=30710x_{10} = 2^{10}(20 + 10) - 10 = 30 \cdot 2^{10} - 10 = 30 \cdot 1024 - 10 = 30710
    • Since 30710<22030710 < 2^{20} (where 220=1,048,5762^{20} = 1,048,576), Option A is FALSE.
    • Since 30710>21030710 > 2^{10} (where 210=10242^{10} = 1024), Option C is FALSE.
  • Option B: x=20,y=20x = 20, y = 20 x20=220(20+20)−20=40⋅220−20x_{20} = 2^{20}(20 + 20) - 20 = 40 \cdot 2^{20} - 20 Since 40⋅220−20>22040 \cdot 2^{20} - 20 > 2^{20}, Option B is TRUE.
  • Option D: x=10,y=20x = 10, y = 20 x20=220(10+20)−20=30⋅220−20x_{20} = 2^{20}(10 + 20) - 20 = 30 \cdot 2^{20} - 20 Since 30⋅220−20>22030 \cdot 2^{20} - 20 > 2^{20}, Option D is TRUE.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions