Question
Consider the following function:
int unknown(int n){
int i, j, k=0;
for (i=n/2; i<=n; i++)
for (j=2; j<=n; j=j*2)
k = k + n/2;
return (k);
}
The return value of the function is
Official answer and solution
- Official answer
- B
- From
- Official GATE 2013 answer key
Solution
Count the number of iterations of the nested loops and sum the incremental updates to variable k.
Let us analyze the loops in unknown(int n):
-
Outer loop:
for (i = n/2; i <= n; i++)
The index ranges from to . The number of iterations is: -
Inner loop:
for (j = 2; j <= n; j = j * 2)
The index takes values .
The number of iterations is . -
Loop body:
k = k + n/2;
This statement executes for each combination of the outer and inner loop iterations:In each execution, the value added to is . Since starts at 0, the final value returned is:
Thus, the return value of the function is .
B
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2013 Computer Science and Information Technology (CS)
- Question
- 31 of 65, printed as CS Q.31
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.