Section 12.5 Practice Your Recursion!
Pick one of the three options below to try!
Subsection 12.5.1 Practice 1
Activity 12.3.
Write a function sum()
that takes an integer n
as an argument and recursively finds the sum of the numbers from 1 through n
.
The function should return that sum. The function sum()
should not use any loops!
The main function is already given to you so that you can focus on the recursive function sum()
. Example output:
"The sum of the numbers from 1 through 10 equals 55."
admin.....open in new window
Subsection 12.5.2 Practice 2
Activity 12.4.
Write a recursive function sumOfDigits()
that computes and returns the sum of the digits of an integer number that’s been passed to the function. Your function should not use any loops!
The main function is already given to you so that you can focus on the recursive function sumOfDigits()
. Example output:
"The sum of the digits of the number 132436 equals 19."
admin.....open in new window
Subsection 12.5.3 Practice 3
Activity 12.5.
Write a recursive function fib()
that takes an integer argument n
and returns the nth Fibonacci number. Your function should not use any loops! Recall that the first and second Fibonacci numbers are 0 and 1, whereas each subsequent Fibonacci number is the sum of the two previous ones. For example, here are the first 10 Fibonacci numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
The main function is already given to you so that you can focus on the recursive function fib()
.
Example output:
"The 9th Fibonacci number is 21."
admin.....open in new window