Java Reference
In-Depth Information
4. Write a recursive function named sumSquares that returns the sum of the
squares of the numbers from 0 to num , where num is a nonnegative int
variable. Do not use global variables, use appropriate parameters. Also write
a program to test your function.
5. Write a recursive method that finds and returns the sum of the elements of
an int array. Also, write a program to test your method.
6. A palindrome is a string that reads the same both forward and backward. For
example, the string '' madam '' is a palindrome. Write a program that uses a
recursive method to check whether a string is a palindrome. Your program
must contain a value-returning recursive method that returns true if the
string is a palindrome and false otherwise. Use appropriate parameters in
your method.
7. Write a program that uses a recursive method to print a string backward.
Your program must contain a recursive method that prints the string back-
ward. Use appropriate parameters in your method.
8. Write a recursive method, reverseDigits , that takes an integer as a
parameter and returns the number with the digits reversed. Also, write a
program to test your method.
9. Write a recursive method, power , that takes as parameters two integers x
and y such that x is nonzero and returns x y . You can use the following
recursive definition to calculate x y . If y 0:
8
<
1
if y ¼ 0
power ð x ; y Þ¼
x
if y ¼ 1
:
x power ð x ; y 1 Þ
if y > 1
If y < 0:
1
power ð x ; y Þ
power ð x ; y Þ¼
Also, write a program to test your method.
10. Greatest Common Divisor. Given two integers x and y, the following
recursive definition determines the greatest common divisor of x and y,
written gcd(x,y):
gcd ð x ; y Þ¼ x
if y ¼ 0
gcd ð y ; x % y Þ
if y 0
(Note: In this definition, % is the mod operator.)
(This algorithm to determine the gcd of two integers is called the Eucli-
dean algorithm.) Write a recursive method, gcd , that takes as parameters
two integers and returns the greatest common divisor of the numbers. Also,
write a program to test your method.
Search WWH ::




Custom Search