What will be the value of s if n = 127 is given as input to the following…
What will be the value of s if n = 127 is given as input to the following pseudocode?
Read n
i = 0, s = 0
Function Sample(int n)
while (n > 0)
r = n % 10
p = 8^i
s = s + p*r
i++
n = n / 10
End While
Return s
End FunctionAnswer: C. 87 — Concept: this is a positional-number-system reconstruction. Any non-negative integer can be rebuilt from its digits d0, d1, d2, ... (d0 = least significant)…
- A.
27
- B.
187
- C.
87
- D.
120
Attempted by 28 students.
Show answer & explanation
Correct answer: C
Concept: this is a positional-number-system reconstruction. Any non-negative integer can be rebuilt from its digits d0, d1, d2, ... (d0 = least significant) once the base b is known, by weighting each digit with an increasing power of b: d0×b0 + d1×b1 + d2×b2 + ... . The while-loop peels off the DECIMAL digits of n using n%10 (the current digit) and n/10 (drop that digit), but weights each digit with p = 8^i instead of 10^i. So the code treats the decimal digits of n as though they were digits of a base-8 (octal) number, and reconstructs the equivalent base-10 value.
Application - tracing the loop for n = 127:
Start: i = 0, s = 0, n = 127.
Iteration 1 - r = 127 % 10 = 7 (last digit); p = 80 = 1; s = 0 + 1×7 = 7; i becomes 1; n becomes 127 / 10 = 12 (integer division).
Iteration 2 - r = 12 % 10 = 2; p = 81 = 8; s = 7 + 8×2 = 23; i becomes 2; n becomes 12 / 10 = 1.
Iteration 3 - r = 1 % 10 = 1; p = 82 = 64; s = 23 + 64×1 = 87; i becomes 3; n becomes 1 / 10 = 0.
n is now 0, so while(n > 0) fails and the loop exits; the function returns s = 87.
Cross-check: reading 127 directly as an octal literal gives the same value independently - 1×82 + 2×81 + 7×80 = 64 + 16 + 7 = 87. Both routes (the digit-by-digit trace and the direct octal-to-decimal formula) agree, confirming the function returns s = 87.