ITPEC FE Subject B April 2024 Question 4

From the answer group below, select the correct combination of answers to be inserted into A and B in the program.

The function sumDigits receives a non-negative integer value num as argument, and returns the sum of the digits of num.

[Program]
○ integer: sumDigits(integer: num)
integer: sum ← 0
while (num > 0)
sum ← A
num ← B
endwhile
return sum

Answer group

OptionAB

Explanation

A: sum + num mod 10, B: integer part of (num ÷ 10) — add the ones digit to sum, then drop it from num, until no digits are left.

  • •num mod 10 is the ones digit of num; adding it to the running total gives A, sum + num mod 10.
  • •Integer division by 10 removes the ones digit and shifts the rest right: B is the integer part of (num ÷ 10).
  • •num loses one digit per pass, so the loop stops at 0.

Trace for 123:

num at startnum mod 10sumnum after B
1233312
12251
1160

The function returns 6, which is 1 + 2 + 3.

Answer (b)

Why not others:

  • •(a), (c), (e) and (g) — B num mod 10 keeps the ones digit instead of dropping it: 123 becomes 3 and stays 3, so the loop never ends unless that digit is 0
  • •(d) — A sum × 10 + num mod 10 appends each digit instead of adding it, so it returns the digits reversed: 321 for 123
  • •(f) — A adds the number without its last digit: for 123 it adds 12, then 1, then 0, returning 13
  • •(h) — A shifts sum left and adds the number without its last digit: 123 gives 12, then 121, then 1210

Key rule: mod 10 reads the last digit and integer division by 10 removes it; the loop variable must shrink through the division, or the loop never reaches 0.

Math & Numbers · AI-written, may contain errors

This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.