ProgrammingHardAmazon OA · Infosys SP
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 = 100, 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 steps- A. 6
- B. 8
- C. 2
- D. 9
Correct answer: B. 8
100 → 50 → 25 → 24 → 12 → 6 → 3 → 2 → 1: 8 steps. In binary (1100100) each bit after the first costs one halving (6) and each extra 1 bit costs one subtraction (2). 6 counts only the halvings, 2 only the subtractions, and 9 counts the 9 values visited instead of the moves.
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? (All variables are integers, so / is integer division) Integer dp[0..10] dp[1] = 0…
- What will be the output of the following pseudocode? (& is bitwise AND on two's-complement integers) Integer c = 0 for (each i from 0 to…
- What will be the output of the following pseudocode? (^ is XOR, & is AND; x & (−x) keeps the lowest 1-bit) Integer a[6] = {2, 4, 7, 9, 2…
- What will be the output of the following pseudocode? String w[3] = {"flower", "flow", "flight"} String p = w[0] for (each i from 1 to 2)…
- What will be the output of the following pseudocode? (substring(s, i, 2) is the 2 characters from index i; sorted(t) puts t's letters in…
- What will be the output of the following pseudocode? (strings are indexed from 0) String p = "ABABCABAB" Integer f[9], k = 0 f[0] = 0 for…