Consider the following C function.
int fun1 (int n) {
int i, j, k, p, q = 0;
for (i = 1; i < n; ++i)
{
p = 0;
for (j = n; j > 1; j = j/2)
++p;
for (k = 1; k < p; k = k * 2)
++q;
}
return q;
}
Which one of the following most closely approximates the return value of the function ?
View worked solution
Answer: D
To find the return value of the function fun1(n), let us analyze the behavior of each loop step-by-step:
- Outer Loop:
The outer loopfor (i = 1; i < n; ++i)runs exactly times. - First Inner Loop:
Inside the outer loop,pis initialized to . The loopfor (j = n; j > 1; j = j/2)repeatedly divides (starting at ) by until .
The number of iterations is the number of times we can divide by , which is approximately . Thus, after this loop terminates: - Second Inner Loop:
The loopfor (k = 1; k < p; k = k * 2)starts with and doubles in each iteration until .
The number of iterations of this loop is approximately . Sinceqis incremented by in each iteration, the increment toqper outer loop iteration is:
Total Value of q:
Since the outer loop runs times, and each iteration increments q by times, the final value of q returned is:
Therefore, the return value is most closely approximated by .
Free practice · Your answers on this page are not saved.
