C++20 sections · 1024 units
Open in Course

Problem: Count Digits

Recursion or loops

Write int countDigits(int n) returning digit count. Use a loop: divide by 10 until 0, count iterations. Or recursion: if n < 10, return 1, else 1 + countDigits(n/10). Test with 42 (2 digits), 1000 (4 digits), 0 (1 digit).

If you get 0 for the number 0, your base case is wrong. This shows both approaches. Loops are clearer for beginners. Recursion is clean but harder to trace. Pick whichever makes sense.