Search code examples
javarecursionmethodsinfinite

Why this recursive method for counting all the odd digits of a number makes infinite recursion?


I have this exercise that asks me to create a program to count the odd digits of a number, so if the number is 12345 it will count to 3, because of 1, 3 and 5. I started creating a recursive method, my very first one, with a ramified if-else. The point of using it was to see if (inputNumber % 2 == '0'). If yes, the last digit of the number would be a 0, 2, 4, 6 or 8, because only those digits give 0 if moduled by 2, so oddDigitsCounter wouldn't grow. Else, if (inputNumber % 2 == '1'), the last digit of the number would be 1, 3, 5, 7 or 9. oddDigitCounter++;, so. To check digit by digit I tried to divide the number by ten because it is a int variable, so it doesn't saves any digit after the floating point. This is the method since now:

public static int oddDigitCounter (int number) {

    int oddCount, moduledNumber, dividedNumber, absoluteInput;

    oddCount = 0;
    absoluteInput = Math.abs(number);
    moduledNumber = absoluteInput % 2;
    dividedNumber = absoluteInput / 10;

    if (absoluteInput == '0') {
        oddCount = oddCount;  }
    else if (moduledNumber == '0') {
        oddCount = oddCount;
        oddDigitCounter(dividedNumber); }
    else // (number % 2 != 0) 
        oddCount++;
        oddDigitCounter(dividedNumber); }

    return oddCount;

Why it gives me an infinite recursion? What's wrong? Why? Any other way to solve this? Any idea for improving my program?


Solution

  • Declare odd counter outside of recursion and you should get results :

    static int oddCounts;
    
    public static int oddDigitCounter(int number) {
        int moduledNumber, dividedNumber, absoluteInput = 0;
    
        absoluteInput = Math.abs(number);
        moduledNumber = absoluteInput % 2;
        dividedNumber = absoluteInput / 10;
    
        if (absoluteInput == 0) {
            return 0;
        } else if (moduledNumber == 0) {
            return oddDigitCounter(dividedNumber);
        } else {
            oddCounts++;
            return 1 + oddDigitCounter(dividedNumber);
        }
    }