{"id":"recursion-calling-itself","slug":"calling-itself","title":"A method that calls itself","text":"This module is an extra: the MOOC doesn't cover it. Recursion means solving a problem by solving a smaller copy of the same problem first. It's worth knowing because a lot of data is built from smaller copies of itself: folders inside folders, the two halves of a sorted array, the branches of a tree. Code for such data is often shortest and clearest when it's recursive, and recursive code turns up in other people's programs and in library code.\n\n### A method can call itself\n\nSince module 10, methods have called other methods. A method can also call itself. A set of nesting dolls is a doll with a smaller set of dolls inside it, so opening the whole set is: open this doll, then open the smaller set the same way.\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        openDolls(3);\n        System.out.println(\"All open\");\n    }\n\n    public static void openDolls(int size) {\n        if (size == 0) {\n            return;\n        }\n        System.out.println(\"Opening the doll of size \" + size);\n        openDolls(size - 1);\n    }\n}\n```\n\n```output\nOpening the doll of size 3\nOpening the doll of size 2\nOpening the doll of size 1\nAll open\n```\n\n`openDolls(3)` prints its line and calls `openDolls(2)`, which prints its line and calls `openDolls(1)`, and so on. A method that calls itself is **recursive**, and the call is a **recursive call**. Two parts make it work:\n\n- The **base case**: an input so small that the method answers it without calling itself. Here that's `size == 0`: no doll left, so the method just returns.\n- The **recursive case**: everything else. The method does its own small part of the work and calls itself on a smaller input, `size - 1`, which brings it one step closer to the base case.\n\nWithout the base case, the calls would never end. Step 4 shows what happens then.\n\n### Every call has its own variables\n\nEach call of a method gets its own parameters and variables, so `openDolls(3)`, `openDolls(2)` and `openDolls(1)` each have a `size` of their own, and none of them changes another one's. While `openDolls(1)` runs, the calls for 3 and 2 aren't finished: each waits at its recursive call, to go on after it once that call returns. Java keeps the unfinished calls on the call stack (module 11), the newest on top. It's the same list of calls that a crash report prints, one `at` line per call. Here is the run, with each call indented under the one that made it:\n\n```text\nmain calls openDolls(3)\n    openDolls(3) prints its line, calls openDolls(2)\n        openDolls(2) prints its line, calls openDolls(1)\n            openDolls(1) prints its line, calls openDolls(0)\n                openDolls(0) returns at once (the base case)\n            openDolls(1) has nothing left to do, returns\n        openDolls(2) returns\n    openDolls(3) returns\nmain prints \"All open\"\n```\n\n### Recursion and loops\n\nThis method could just as well be a `while` loop that counts `size` down. A loop is simpler here, and it doesn't keep a call per round on the call stack. Recursion pays off when a problem splits into smaller problems of the same kind, as in steps 5 and 6. The first steps use small problems, so that you can follow every call.\n","task":"A quiz show's timer counts down the seconds of a round. `countDown(seconds)` prints the seconds from `seconds` down to 1, one per line. Fill in the blank, the value that the recursive call is given, so that the program prints:\n\n```\n5\n4\n3\n2\n1\nTime is up\n```\n","kind":"fill","seed":"public class Main {\n    public static void main(String[] args) {\n        countDown(5);\n        System.out.println(\"Time is up\");\n    }\n\n    public static void countDown(int seconds) {\n        if (seconds == 0) {\n            return;\n        }\n        System.out.println(seconds);\n        countDown([[seconds - 1‖seconds-1]]);\n    }\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        countDown(5);\n        System.out.println(\"Time is up\");\n    }\n\n    public static void countDown(int seconds) {\n        if (seconds == 0) {\n            return;\n        }\n        System.out.println(seconds);\n        countDown(seconds - 1);\n    }\n}\n","hints":["Each call prints its own number, then leaves the rest of the countdown to a call with a smaller number.","The next number to print is one less than this call's: `seconds - 1`. When it reaches 0, the base case stops the calls."],"tests":[{"name":"Output","stdin":"","expect":"5\n4\n3\n2\n1\nTime is up","hidden":false}],"require":[],"forbid":[],"more":[{"task":"A tall building's stairwell has the floor number painted on each landing, and someone climbing it passes them in order. Write the method `floorsUp(int top)`, which prints the floors from 1 up to `top`, one per line, with recursion and no loop. For a `top` of 0 it prints nothing.\n\nThe trick: call `floorsUp(top - 1)` first, so that the lower floors are printed, and only then print `top`. The check runs `floorsUp(4);` and expects:\n\n```\n1\n2\n3\n4\n```\n","kind":"code","seed":"public class Main {\n    public static void main(String[] args) {\n        floorsUp(4);\n    }\n\n    // Write the method floorsUp here.\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        floorsUp(4);\n    }\n\n    public static void floorsUp(int top) {\n        if (top == 0) {\n            return;\n        }\n        floorsUp(top - 1);\n        System.out.println(top);\n    }\n}\n","hints":["The base case is a `top` of 0: there's nothing to print, so the method returns.","Otherwise, call `floorsUp(top - 1)` first. When it returns, floors 1 to `top - 1` are printed, and the method prints `top` after them."],"tests":[{"name":"floorsUp(4);","stdin":"","call":"floorsUp(4);\n","expect":"1\n2\n3\n4","hidden":false},{"name":"floorsUp(1);","stdin":"","call":"floorsUp(1);\n","expect":"1","hidden":true},{"name":"Test 3","stdin":"","call":"floorsUp(0);\nSystem.out.println(\"ground\");\nfloorsUp(7);\n","expect":"ground\n1\n2\n3\n4\n5\n6\n7","hidden":true}],"require":[{"pattern":"\\bpublic\\s+static\\s+void\\s+floorsUp\\s*\\(\\s*int\\s+\\w+\\s*\\)","message":"Write the method as `public static void floorsUp(int top)`."},{"pattern":"\\bfloorsUp\\s*\\(","min":3,"message":"`floorsUp` should call itself (the method's header, the call in `main` and the recursive call)."}],"forbid":[{"pattern":"\\b(for|while)\\b","message":"Do it with recursion, without a loop."}]},{"task":"A bucket goes down a well, one level per call, and comes back up. `lower` prints a line before its recursive call and another after it. What does this program print?\n","kind":"predict","seed":"public class Main {\n    public static void main(String[] args) {\n        lower(1);\n    }\n\n    public static void lower(int level) {\n        if (level > 3) {\n            System.out.println(\"splash\");\n            return;\n        }\n        System.out.println(\"down \" + level);\n        lower(level + 1);\n        System.out.println(\"up \" + level);\n    }\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        lower(1);\n    }\n\n    public static void lower(int level) {\n        if (level > 3) {\n            System.out.println(\"splash\");\n            return;\n        }\n        System.out.println(\"down \" + level);\n        lower(level + 1);\n        System.out.println(\"up \" + level);\n    }\n}\n","hints":["The lines before the recursive call come out on the way down: `down 1`, `down 2`, `down 3`. Then `lower(4)` is the base case.","A call prints its `up` line only after the call it made has returned, so the deepest call's `up` line comes first: `up 3`, then `up 2`, then `up 1`."],"tests":[{"name":"Output","stdin":"","expect":"down 1\ndown 2\ndown 3\nsplash\nup 3\nup 2\nup 1","hidden":false}],"require":[],"forbid":[],"lines":["down 1","down 2","down 3","splash","up 3","up 2","up 1"]}]}