Javier Tan
Javier Tan

Reputation: 81

Are return statements always necessary for boolean recursion method calls?

I am trying to add the individual digits of a number together and determine whether the final answer is even or odd.

    public static boolean isSumOfDigitsOdd(int n) {
        if (n <= 0) {
            return false;
        } else if (n == 1) {
            return true;
        } else if (n == 2) {
            return false;
        } else if (n > 2) {
            int temp1 = n % 10;
            int temp2 = (n / 10) % 10;
            int tempFinal = temp1 + temp2;
            while (tempFinal > 2) {
                tempFinal -= 2;
            }
            isDigitSumOdd((n / 100) + tempFinal);
        }
    }

The issue that I am facing is whether a return statement is always necessary for the recursion call to work. As seen from the code above, when I try runnning it gives out an error message saying that the return type must be a boolean type.

However, after adding in a boolean variable, I was able to get the code to work as shown below.

    public static boolean isDigitSumOdd(int n) {
    boolean x = false;
    if (n <= 0) {
        x = false;
    } else if (n == 1) {
        x = true;
    } else if (n == 2) {
        x = false;
    } else if (n > 2) {
        int temp1 = n % 10;
        int temp2 = (n / 10) % 10;
        int tempFinal = temp1 + temp2;
        while (tempFinal > 2) {
            tempFinal -= 2;
        }
        return isDigitSumOdd((n / 100) + tempFinal);
    }
    return x;
}

In this case, after adding the boolean variable, I could run the code smoothly and it would provide me with the desired outcome.

I am fairly new to recursion and am unsure about why this happens. After looking up online, I could only figure out that a return statement is not necessary only if the return type is a void type.

Upvotes: 0

Views: 53

Answers (1)

Mamiglia
Mamiglia

Reputation: 163

In any language the return statement is necessary when the return type is non-void. There are 2 errors in the first code:

  1. no reason to put the last else if, as an else would be more appropriate
  2. you must call return isDigitSumOdd((n / 100) + tempFinal); because otherwise your function isn't returning anything. Instead if you actually call it the function returns the value returned by isDigitSumOdd((n / 100) + tempFinal);. That's the key point of recursion.

Now, I don't know if your code works aside from the errors I mentioned, so here's a cleaner solution. The ^ is a XOR operator.

public static boolean isDigitSumOdd(int n) {
    if (n == 0) return false;
    
    return isDigitSumOdd(n/10) ^ n%2 == 1;
}

Upvotes: 0

Related Questions