Title: CS1101X: Programming Methodology Recitation 9 Recursion II
1CS1101X Programming MethodologyRecitation 9
Recursion II
2Task 1 Mystery (1/6)
Study the code below and if you like, trace the
recursive method mystery(). What is the smaller
version of the task on which the recursive call
works? How does the original problem relate to
the smaller problem? What does the method compute?
3Task 1 Mystery (2/6)
public static void main(String args) //
code to read values into array - omitted
System.out.print("Answer "
mystery(list, list.length) //
pre-cond n gt 0 public static int mystery(int
a, int n) if (n 1) return a0 else
int m mystery(a, n-1) return
an-1 gt m ? an-1 m
4Task 1 Mystery (3/6)
Is the code a going-up, going-down or
split-half recursion? Write the other two
versions. You may also try other versions.
5Task 1 Mystery (4/6)
Going-up version
6Task 1 Mystery (5/6)
Split-half version
7Task 1 Mystery (6/6)
Other version
8Task 2 Transpose Matrix (1/6)
To transpose a square matrix, the columns become
the rows and the rows become columns. For
example, the 5?5 matrix on the left below is
transposed into the matrix on the right.
9Task 2 Transpose Matrix (2/6)
Write a recursive method to transpose a square
matrix. Hint If the original problem is an n?n
matrix that extends from m00 to mn-1n-1,
then the smaller problem is the (n-1)?(n-1)
matrix that extends from m00 to mn-2n-2.
10Task 2 Transpose Matrix (3/6)
import java.util. class Transpose public
static void main(String args) int
matrix createMatrix()
System.out.println("Before transpose")
printMatrix(matrix) transpose(matrix,
matrix.length) System.out.println()
System.out.println("After transpose")
printMatrix(matrix) . . .
Write the methods createMatrix, printMatrix, and
transpose.
11Task 2 Transpose Matrix (4/6)
createMatrix
12Task 2 Transpose Matrix (5/6)
printMatrix
13Task 2 Transpose Matrix (6/6)
transpose
14End of Recitation 9