ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)
Function countDigits(Integer n)
    if (n == 0)
        return 1
    end if
    Integer c = 0
    while (n > 0)
        n = n / 10
        c = c + 1
    end while
    return c
End Function

Print countDigits(94857)
  1. A. 4
  2. B. 5
  3. C. 6
  4. D. 9

Correct answer: B. 5

Each pass strips one digit by integer-dividing by 10: 94857->9485->948->94->9->0, which is 5 divisions, matching the 5 digits of 94857.

More Pseudocode and Code Tracing questions

Exams that ask this topic