Search⌘ K
AI Features

Challenge: Count the Digits in a Number Using Recursion

Learn to create a recursive function in C++ that counts the digits of any integer, including negatives and zero. This lesson guides you through implementing and testing the count_digits function, strengthening your understanding of recursion and its practical applications.

Problem statement

Your task is to write a recursive function count_digits. In the function parameter, you will pass the value of type int, and function will return an int value in the output.

Your function should count the total number of digits in a number and return the number of digits in output. Your solution should work for both positive and negative values, including 0.

Sample input

count_digits (2436);
count_digits (1);
count_digits (-1234);

Sample output

digits = 4
digits = 1
digits = 4

Coding exercise

Before diving directly into the solution, try to solve it yourself. Then, check if your code passes all the test cases.

πŸ“ Your function name should be count_digits.

πŸ“ Please write a recursive solution to the problem.

Good luck! πŸ‘

C++
/* Write your recursive function count_digits here
The function should take the value of type int in its input parameters
and return int value in the output*/
int count_digits(int number) {
return 0;
}

πŸŽ‰If you have solved the problem, congratulations!

In case you are stuck, let’s go over the solution review in the next lesson.