Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

HW 5

R-5.10 - Describe a way to use recursion to compute the sum of all the elements in an n×n (two-
dimensional) array of integers.

We can define a recursive method called arraySum. The method takes the array and the size 'n' as
parameters. In the base case, when 'n' is 0, the method returns 0 as there are no elements to sum.
Otherwise, it initializes a variable sum to 0 and iterates through each element in the array, adding
it to the sum. It then makes a recursive call to arraySum with the updated size 'n-1' and adds the
returned sum to the current sum. Finally, it returns the sum, which represents the sum of all
elements in the array

C-5.16 -In the Towers of Hanoi puzzle, we are given a platform with three pegs, a, b, and c,
sticking out of it. On peg a is a stack of n disks, each larger than the next, so that the smallest is
on the top and the largest is on the bottom. The puzzle is to move all the disks from peg a to peg
c, moving one disk at a time, so that we never place a larger disk on top of a smaller one. See
Figure 5.15 for an example of the case n = 4. Describe a recursive algorithm for solving the
Towers of Hanoi puzzle for arbitrary n. (Hint: Consider first the subproblem of moving all but
the nth disk from peg a to another peg using the third as “temporary storage.”)

To solve the Towers of Hanoi puzzle recursively, we can define a function called hanoi that takes
four parameters: the number of disks 'n', the source peg 'a', the destination peg 'c', and the
auxiliary peg 'b'. The base case is when 'n' is 1, where we move the disk directly from the source
peg to the destination peg. For larger 'n', we recursively move 'n-1' disks from the source peg to
the auxiliary peg using the destination peg as temporary storage, then move the remaining largest
disk from the source peg to the destination peg, and finally recursively move the 'n-1' disks from
the auxiliary peg to the destination peg using the source peg as temporary storage.

P-5.28
See .java file
P-5.29
See .java file

You might also like