ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (num[i] - '0' converts a digit character to its value)

What will be the output of the following pseudocode? (num[i] - '0' converts a digit character to its value)
String num = "79927398713"
Integer s = 0, d, pos = 0
for (each i from length(num) - 1 down to 0)
    d = num[i] - '0'
    if (pos mod 2 == 1)
        d = d * 2
        if (d > 9)
            d = d - 9
        end if
    end if
    s = s + d
    pos = pos + 1
end for
Print s, s mod 10 == 0
  1. A. 64 false
  2. B. 70 true
  3. C. 76 false
  4. D. 80 true

Correct answer: B. 70 true

This is the Luhn check. From the right, every second digit is doubled (subtracting 9 if above 9): the doubled digits 1, 8, 3, 2, 9 become 2, 7, 6, 4, 9 = 28, and the other digits 3, 7, 9, 7, 9, 7 add to 42. s = 70, a multiple of 10: 70 true.

More Pseudocode and Code Tracing questions

Exams that ask this topic