0

Trying to better understand the double parameter in this recursion question. Any help is appreciated. Just a little lost on how to apply it to other programs ie pascalValue(i, j)

   public static int pascalValue(int i, int j) {
    if (j == 0) {
        return 1;
    } else if (j == i) {
        return 1;
    } else {
        return pascalValue(i - 1, j - 1) + pascalValue(i - 1, j);
    }
}

public static void computeRow(int n) {
    int counter;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++) {
            System.out.print(pascalValue(i, j) + " ");
        }
        System.out.println();
    }
}
Amine
  • 3
  • 1
  • 3
    Welcome to SO. Your question is unclear at the moment - what exactly don't you understand and what do you mean by "how to apply it to other programs"? – sprinter Feb 25 '20 at 04:03

1 Answers1

0

See, Double parameter recursion works like any other parameterized recursion. More parameters are just some more/extra information for you to evaluate the result. What you want to achieve with it is up to you.

So let's understand thispascalValue(i, j) function in breif.

let's look at the last return statement in the function

return pascalValue(i - 1, j - 1) + pascalValue(i - 1, j);

So pascalValues(i, j) function is being called twice as:

  1. pascalValue(i - 1, j - 1)
  2. pascalValue(i - 1, j)

Now here are the base conditions:

  1. if (j == 0) { return 1; }
  2. else if (j == i) { return 1; }

Base conditions are nothing but telling the function where to stop, otherwise, the recursive calls will keep on happening and eventually stack will overflow.

So when the base condition is reached, specified value is returned to its previous invocation and result is computed based on the expression which in our case is addition of pascalValue(i - 1, j - 1) and pascalValue(i - 1, j)

Remember each call will meet its base condition, so if pascalValue(i - 1, j - 1) reaches its base condition, specified value will be returned which is the result of previous invocation and this result will be combined(because in our case we are adding the result) with the other pascalValue(i, j) invocation i.e. pascalValue(i - 1, j) with the then i, j values.

And this will keep on happening until all the invocations are computed and a result is returned.

Look at this SO answer on recursion for better understanding.

Arpit J.
  • 1,108
  • 12
  • 20
  • when pascalValue(i, j) prints out, are i and j multiplied? I'm just confused on how they interact – Amine Feb 25 '20 at 14:05
  • @Amine I have updated my answer. check and let me know if you understood anything out of it. – Arpit J. Feb 25 '20 at 16:03