Practice Programs can generally be solved with a short program that directly applies the programming principles presented in this chapter.
Write a recursive function definition for a function that has one parameter n
of type int
and that returns the nth Fibonacci number. See Programming Project 6 in Chapter 3 for the definition of Fibonacci numbers. Embed the function in a program and test it.
Write a recursive version of the function indexOfSmallest
that was used in the sorting program in Display 7.12 of Chapter 7. Embed the function in a program and test it.
Write a recursive version of the search
function in Display 7.10 of Chapter 7.
There are n people in a room, where n is an integer greater than or equal to 2. Each person shakes hands once with every other person. What is the total number of handshakes in the room? Write a recursive function to solve this problem, with the following header:
int handshake(int n)
where handshake(n)
returns the total number of handshakes for n people in the room. To get you started, if there are only one or two people in the room, then:
handshake(1) = 0
handshake(2) = 1
Write a recursive function that returns true
if an input string is a palindrome and false
if it is not. You can do this by checking if the first character equals the last character, and if so, make a recursive call with the input string minus the first and last characters. You will have to define a suitable stopping condition. Test your function with several palindromes and nonpalindromes.