Nested Loops and Recursive Functions

these two concepts are making knots on my mind. Specially recursive functions. What were the examples of codes and/or analogies that worked best FOR YOU personally and made it click?

For me the thing that helped is that a recursive function is structured like a proof by induction.

If you can go into more detail about what does and doesn’t confuse you, I’d be happy to try explaining things in a way that makes sense to you.

2 Likes
function sum(arr, n) {
   if (n <= 0) {
      return 0;
    } else {
      return sum(arr, n - 1) +arr[n - 1];
    }
}

Take this function that sums the first n elements of an array for example.
sum(arr, n - 1) is the part that confuses me most. I get that +arr[n -1] is gonna sum the elements of the array from the highest n to the beginning of the array, index 0, going one index down each time the function is called. But i don’t get to what it sums, if that makes sense.

The function sum() will always return a number (as long as arr is an array of numbers). If n is zero (or less), then it will return 0. If n is more than zero, it will add whatever number sum(arr, n-1) is to the number in arr at position n-1.

One of the tasks that helped me to really appreciate recursive functions is “inverting a binary tree”.
While you can write a lot of loops as recursive functions, they usually seem wasted, if not worse. But for inverting a binary tree, it’s just beautiful in it’s simplicity.

Nested loops on the other hand never were a problem for me ^^