0

In the Recursion when I write res += countNatNum(++len, sum + i, k, d); I have a StackOverFlow mistake. But when I change pre-increment on len + 1 res res += countNatNum(len + 1, sum + i, k, d); everything is OK. I don't understand why does it happen because I check the condition with if (len == 3) ?

public static int countNatNum(int len, int sum, int k, int d){
        int base = 9;
        if (d > base * k) return 0;
        else if (len == k){
            if (sum == d){
                return 1;
            }
            else return 0;
        }
        int res = 0;
        int c = (len == 0 ? 1 : 0);
        for (int i = c; i <= base; i++){
            res += countNatNum(len + 1, sum + i, k, d);
        }
        return res;
        }
    }

The Program should count the number of natural numbers where sum of digits == another natural number. The program works correct but i don't understand why does pre-increment works in such strange way.

Istiaque Hossain
  • 2,157
  • 1
  • 17
  • 28
  • This is an excellent example of several things: 1. infinite recursion and 2. why you should not use recursion – DwB Aug 03 '19 at 14:12

1 Answers1

1

If you use "++" the updated value is stored again. ""len +1" on the other hand does not increment "len".

Florian Reisinger
  • 2,638
  • 4
  • 23
  • 34