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
View worked solution
Answer: B
To find the return value of the function, we need to determine the final value of the variable . Let's analyze the loops step-by-step:
-
Outer Loop:
for (i = n/2; i <= n; i++)
The loop variable starts at and increments by until it reaches .
The number of iterations of this loop is: -
Inner Loop:
for (j = 2; j <= n; j = j*2)
The loop variable starts at and doubles in each iteration ().
The number of iterations of this loop is:
Total Executions of the Inner Statement:
Since the loops are nested and independent of each other's loop variables, the statement inside the inner loop is executed:
Calculating the Return Value :
In each execution of the inner statement, the value added to is , which is .
Therefore, the final value of returned by the function is:
Thus, the return value of the function is .
Free practice · Your answers on this page are not saved.
