In this program, we will create a recursive function to count the number of digits of a number using recursion and return the result to the calling function.
The source code to count the digits of a given number using recursion is given below. The given program is compiled and executed successfully.
// Rust program to count the digits
// of given number using recursion
unsafe fn CountDigits(num:i32)->i32 {
static mut count:i32=0;
if num > 0 {
count = count + 1;
CountDigits(num / 10);
}
return count;
}
fn main()
{
unsafe{
let res=CountDigits(1234);
println!("Total digits are: {}",res);
}
}
Output:
Total digits are: 4
Explanation:
In the above program, we created two functions CountDigits() and main(). The CountDigits() function is a recursive function, which is used to count the digits of the given number and return the result to the calling function.
In the main() function, we called CountDigits() function and printed the result.
Program/Source Code:
The source code to count the digits of a given number using recursion is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created two functions CountDigits() and main(). The CountDigits() function is a recursive function, which is used to count the digits of the given number and return the result to the calling function.
In the main() function, we called CountDigits() function and printed the result.
need an explanation for this answer? contact us directly to get an explanation for this answer