Search⌘ K

Solution Review: Count the Digits in a Number Using Recursion

Explore how to use recursion in C++ to count the digits in an integer. This lesson guides you through writing a recursive function that divides the number by 10 each call until only one digit remains. You will understand the base case and recursive logic needed to solve this problem effectively.

We'll cover the following...

Solution

Press the RUN button and see the output!

C++
#include <iostream>
using namespace std;
// Recursive count_digits function
int count_digits(int number) {
// Base Case
if (abs(number)/10 == 0) {
return 1;
}
// Recursive Case
else {
return 1 + count_digits(number / 10);
}
}
// main function
int main() {
// Initialize number
int number = 8625;
// Declare variable result
int result;
// Call count_digits function in main and store the returned value in result
result = count_digits(number);
// Print value of result
cout << "Number of digits = " << result;
return 0;
}

Explanation

count_digits function

The recursive ...