ProgrammingHardTCS NQT · Infosys · Capgemini
What will be the output of the following pseudocode? (Division is integer division; arrays are 0-indexed.)
What will be the output of the following pseudocode? (Division is integer division; arrays are 0-indexed.)
Integer a[9] = {2, 3, 3, 3, 5, 8, 8, 13, 21}
Integer lo = 0, hi = 9, steps = 0
While lo < hi
Integer mid = (lo + hi) / 2
If a[mid] < 8 Then
lo = mid + 1
Else
hi = mid
End If
steps = steps + 1
End While
Print lo, steps- A. 6 3
- B. 7 3
- C. 5 4
- D. 5 3
Correct answer: C. 5 4
This is a lower-bound search: it finds the first index whose value is at least 8, which is index 5 (the first 8). The interval shrinks 9 -> 4 -> 2 -> 1 -> 0, and the loop ends after the number of steps shown; using <= instead of < would return index 7.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (& is bitwise AND; arrays are 0-indexed.) Integer m[4][4] For i = 0 to 3 For j = 0 to…
- What will be the output of the following pseudocode? Function J(n, k) If n = 1 Then Return 0 Return (J(n - 1, k) + k) mod n End Function…
- What will be the output of the following pseudocode? Integer n = 1, s = 0 Repeat s = s + n n = n 2 + 1 Until s >= 100 Print n, s
- What will be the output of the following pseudocode? Integer s = 0 for (each i from 1 to 5) s = s + i i end for Print s
- What will be the output of the following pseudocode? Integer i = 10 while (i > 2) i = i - 3 end while Print i
- What will be the output of the following pseudocode? Integer n = 4096, c = 0 while (n > 0) n = n / 10 c = c + 1 end while Print c