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- A. 64 false
- B. 70 true
- C. 76 false
- 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.
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 right shift, & is bitwise AND) Integer bits[0..15], total = 0 bits[0] = 0 for…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[6] = {3, 2, 2, 3, 4, 3}, k = 0, val = 3 for…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 7, c = 1 for (each…
- What will be the output of the following pseudocode? Integer count = 0 String last = "" Procedure gen(String s, Integer n) if (length(s)…
- What will be the output of the following pseudocode? Integer p[4] = {2, 0, 3, 1} // coefficients of 2x³ + 0x² + 3x + 1 Integer x = 3, m =…
- What is the time complexity of the following pseudocode, as a function of n? Procedure f(Integer n) if (n <= 1) return end if for (each i…