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.
We'll cover the following...
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! π
πIf you have solved the problem, congratulations!
In case you are stuck, letβs go over the solution review in the next lesson.