ProgrammingHardAmazon OA · Capgemini

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer val[7] = {1000, 500, 100, 50, 10, 5, 1}
String sym[7] = {"M", "D", "C", "L", "X", "V", "I"}
String s = "MCMXCIV"
Integer total = 0, v, nextv
for (each i from 0 to length(s) - 1)
    v = value of s[i] in the table
    if (i + 1 < length(s))
        nextv = value of s[i + 1] in the table
    else
        nextv = 0
    end if
    if (v < nextv)
        total = total - v
    else
        total = total + v
    end if
end for
Print total
  1. A. 2216
  2. B. 1994
  3. C. 1996
  4. D. 1904

Correct answer: B. 1994

A symbol smaller than the one after it is subtracted: M (+1000), C (−100), M (+1000), X (−10), C (+100), I (−1), V (+5). Total 1994. Adding everything gives 2216.

More Pseudocode and Code Tracing questions

Exams that ask this topic