Java Array Recursion

后端 未结 7 1385
醉梦人生
醉梦人生 2021-01-17 02:46

The purpose of this assignment is to learn recursive methods. For this particular problem, I need to print the values of list, one per line. The skeleton of the

7条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 03:22

    When your doing recursion, it can sometimes be helpful to write out how you would perform the same task using a loop:

    public void list(String[] list) {
        for(int index = 0; index < list.length; index++) {
            System.out.println(list[index]);
        }
    } 
    

    Now, say we wanted to get closer to a recursive solution. The first step might be to get rid of the interior part of the for loop:

    public void list(String[] list) {
        for(int index = 0; index < list.length; index++) {
            list(list, index);
        }
    }
    
    public void list(String[] list, int index) {
        System.out.println(list[index]);
    }
    

    Okay, now we are really close to the recursive solution. We just need to take the last two tasks that the loop is handling, incrementing index and checking if index < list.length. These look like they might be great candidates for a reduction step and a base case.

提交回复
热议问题