GATE CS 2024 Set 1 — Question 48

MSQ+2 / -0MediumControl FlowC ProgrammingProgramming & Data Structures

Programming & Data Structures → C Programming → Control Flow

Last updated

Question

Consider the following C function definition.
```c
int f(int x, int y) {
for (int i=0; i
A.
If the inputs are x=20,y=10x=20, y=10, then the return value is greater than 2202^{20}
B.
If the inputs are x=20,y=20x=20, y=20, then the return value is greater than 2202^{20}
C.
If the inputs are x=20,y=10x=20, y=10, then the return value is less than 2102^{10}
D.
If the inputs are x=10,y=20x=10, y=20, then the return value is greater than 2202^{20}

Correct answer

(B) If the inputs are x=20, y=20, then the return value is greater than 2²⁰; (D) If the inputs are x=10, y=20, then the return value is greater than 2²⁰

Solution

The function updates the variable xx in a loop that iterates yy times. Let xix_i denote the value of xx after ii iterations, with x0x_0 being the initial input xx. The update rule in each iteration is:xi+1=xi+xi+y=2xi+yx_{i+1} = x_i + x_i + y = 2x_i + yThis is a linear recurrence relation. We can find the general term by observing the first few iterations:
  • x1=2x0+yx_1 = 2x_0 + y
  • x2=2(2x0+y)+y=22x0+(2+1)yx_2 = 2(2x_0 + y) + y = 2^2 x_0 + (2+1)y
  • x3=2(22x0+3y)+y=23x0+(22+2+1)yx_3 = 2(2^2 x_0 + 3y) + y = 2^3 x_0 + (2^2 + 2 + 1)y
In general, after ii iterations:xi=2ix0+(2i1)y=2i(x0+y)yx_i = 2^i x_0 + (2^i - 1)y = 2^i(x_0 + y) - yThe function returns the value after yy iterations, which is f(x,y)=2y(x+y)yf(x, y) = 2^y(x + y) - y.
Evaluating the options:
  • (A) and (C): For x=20,y=10x=20, y=10, the return value is f(20,10)=210(20+10)10=30102410=30710f(20, 10) = 2^{10}(20 + 10) - 10 = 30 \cdot 1024 - 10 = 30710.
  • 3071030710 is much smaller than 220=1,048,5762^{20} = 1,048,576, so (A) is false.
  • 3071030710 is greater than 210=10242^{10} = 1024, so (C) is false.
  • (B): For x=20,y=20x=20, y=20, the return value is f(20,20)=220(20+20)20=4022020f(20, 20) = 2^{20}(20 + 20) - 20 = 40 \cdot 2^{20} - 20. Since 4022020>22040 \cdot 2^{20} - 20 > 2^{20}, (B) is true.
  • (D): For x=10,y=20x=10, y=20, the return value is f(10,20)=220(10+20)20=3022020f(10, 20) = 2^{20}(10 + 20) - 20 = 30 \cdot 2^{20} - 20. Since 3022020>22030 \cdot 2^{20} - 20 > 2^{20}, (D) is true.
Thus, the correct options are B and D.

More questions on C Programming

Practice GATE CS PYQs with adaptive difficulty

Timed practice, skill tracking, and AI explanations — free to start.

Start practicing free