Open In App
Related Articles

GATE | GATE-CS-2006 | Question 15

Improve Article
Save Article
Like Article

Consider the following C-program fragment in which i, j and n are integer variables.

for (i = n, j = 0; i >0; i /= 2, j += i);

Let val(j) denote the value stored in the variable j after termination of the for loop. Which one of the following is true?
(A) val(j) = \theta(logn)
(B) vaI(j) = \theta(sqrt(n))
(C) val(j) = \theta(n)
(D) val(j) = \theta(nlogn)

(A) A
(B) B
(C) C
(D) D

Answer: (C)

Explanation: The variable j is initially 0 and value of j is sum of values of i. i is initialized as n and is reduced to half in each iteration.

j = n/2 + n/4 + n/8 + .. + 1 = Θ(n)

Note the semicolon after the for loop, so there is nothing in the body.

Same as question 1 of

Quiz of this Question

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads