I'm having a question about recursive functions.
I've made this little example program that counts the individual numbers in an integers: example: 123 = 6 because 1 + 2 + 3 = 6.
Now I've made it with a static int and this recursive functions:
static int totalNumbers(int a)
{
if(a <= 0)
return sum;
else
{
sum += a % 10;
return totalNumbers(a/10);
}
}
The function works like a charm but my question is, can I make it without a static int called sum? Is there a way that I can define a integer sum in the function and let them count up with a local var or is it not possible?
Kind regards,
Of course:
static int totalNumbers(int a)
{
if(a <= 0)
return 0;
else
{
return (a % 10) + totalNumbers(a/10);
}
}
static int totalNumbers(int a)
{
return a < 10 ? a : (a % 10) + totalNumbers(a / 10);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With