ProgrammingHardTCS NQT · Accenture pattern
What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)
What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)
Integer n = 20, steps = 0
while (n != 1)
if (n mod 2 == 0)
n = n / 2
else
n = n - 1
end if
steps = steps + 1
end while
Print n, steps- A. 1 4
- B. 1 5
- C. 0 5
- D. 1 6
Correct answer: B. 1 5
20->10->5->4->2->1, taking exactly 5 steps (halving when even, subtracting 1 when odd) before n reaches 1.
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 (counting all subsets of a set of size n)? Function countSubsets(Integer n) if (n ==…
- What will be the output of the following pseudocode (counting set bits using Brian Kernighan's trick, for each value 0 to 7)? (& is…
- What will be the output of the following pseudocode (longest common prefix of a list of strings)? Function lcp(List strs) String prefix =…
- What will be the output of the following pseudocode (finding the kth smallest element by sorting)? (Arrays are indexed from 0.) Integer…
- What will be the output of the following pseudocode (number of ways to climb n stairs, taking 1 or 2 steps at a time)? Function…
- What will be the output of the following pseudocode (product of array except self, without using division)? (Arrays are indexed from 0.)…