2

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,

5 Answers 5

6

Of course:

static int totalNumbers(int a)
  { 
    if(a <= 0)
      return 0;
    else
    {
      return (a % 10) + totalNumbers(a/10);
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Why else if you return? ;)
Thanks :-) so simple but didn't saw it. Learned something new !
4
static int totalNumbers(int a)
{
    return a < 10 ? a : (a % 10) + totalNumbers(a / 10);
}

Comments

2

Of course:

static int totalNumbers(int a, int sum)
{ 
  if(a <= 0)
    return sum;
  else
  {
    return totalNumbers(a/10, sum + a % 10);
  }
}

static int totalNumbers(int a) {
  return totalNumbers(a, 0);
}

This version is tail-recursive, but it doesn't give you anything in Java.

Comments

1

Sure, it's even better to not have static "sum" variable. I would write it in such way:

 static int totalNumbers(int a) {
    if (a <= 0) return 0;

    return a%10 + totalNumbers(a/10);
 }

Comments

1

Of course you can!

public static int totalNumbers(int a) {
    if (a == 0)
        return 0;
    return (a % 10) + totalNumbers(a / 10);
}

By using a static int attribute you're missing the point of recursive functions, a function in the purest mathematical sense, doesn't depend on external values, and you can be certain that every time you call it with the same input, it will return the same output - something you can not say about your method, which will give different results every time you call it with the same input, unless you manually reset to zero the external static int attribute between calls.

For instance, try calling your implementation two or more times in a row, like this:

System.out.println(totalNumbers(123));
System.out.println(totalNumbers(123));
System.out.println(totalNumbers(123));

See what I mean?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.