Sum of multidimensional Array using Recursion

evie ren
2 min readOct 3, 2018

--

In this tutorial, I will explain how recursion works in solving multidimensional array.

lets pretend that we want to find the sum of this array:
[ 3 , 5 , [6] , 7 ,[ 10 ,[ 9 , 1] ] ]

  1. create a variable sum and make it equal to 0, so we will have a space to save the total.
  2. in the for-loop, we checking the variable at the index if it is an Array, if not, we sum up the num
    when index = 0 , sum += 3 , sum = 3
    when index = 1 , sum += 5 , sum = 8
  3. when index =2, its an array, we start a new function
    sum inside the new function starts with 0,
    index =0, sum+= 6, sum = 6
    end of 1 digit for-loop
    now we return this sum = 6
    end of 1st recursion
  4. we come out from the recursion,
    grabbing the 6 return from the function
    and add the sum we got from index 1
    so the sum will now be 14
  5. when index =3, sum +=7, sum =21
  6. when index =4, its an array, recursion 1
    at index = 0 , sum += 10, sum =10
  7. at index = 1 , recursion 2
    at index = 0, sum +=9, sum =9
    at index = 1, sum+=1, sum=10
    end of array, return sum =10
  8. grabbing the 10 return from recursion 2
    and add the sum we got from index 4, which is 10
    so the sum will now be 20
    end of array, return 20
  9. add sum we got before going to the recursion, which is 21, with
    the sum return from the recursion, which is 20
  10. we got the final sum =41

--

--