11.6. Code Practice for Recursion¶
Replace the “ADD CODE HERE” below with the code to complete the findSum method. The method should take the sum of every value that is less than or equal to n. For example, findSum(3) should return 6. The output of the program should be 15.
Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
In order to find the sum of all the numbers that are less than or equal to n, we can use recursion. When findSum(5) is called, since 5 is not equal to 0, the program will go to the else statement. The method will then return 5 + findsum(4). findSum(4) will return 4 + findSum(3), findSum(3) will return 3 + findSum(2), findSum(2) will return findSum(1), findSum(1) will return 1 + findSum(0). findSum(0) will return 0. Therefore, findSum(5) will be 5+4+3+2+1+0, which is euqal to 15.
If you would like to try writing recursive methods check out the recursion problems at CodingBat at http://codingbat.com/java/Recursion-1.