{"id":"recursion-base-case","slug":"base-case-and-return","title":"Base case and return value","text":"The methods of step 1 printed something and returned nothing. A recursive method can also return a value, and that's where recursion gets useful: the method builds its answer from the answer to a smaller problem.\n\n### Counting digits\n\nHow many digits does a whole number have? A number below 10 has one digit. A larger number has one digit more than the number without its last digit, and `n / 10` drops the last digit (module 4): 4096 has one digit more than 409.\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        System.out.println(digits(7));\n        System.out.println(digits(4096));\n    }\n\n    public static int digits(int n) {\n        if (n < 10) {\n            return 1;\n        }\n        return 1 + digits(n / 10);\n    }\n}\n```\n\n```output\n1\n4\n```\n\nRead the method as two sentences: \"a number below 10 has 1 digit\" and \"any other number has 1 more digit than `n / 10`\". The base case answers the smallest problem directly; the recursive case trusts the recursive call to give the right answer for the smaller problem, and adds its own part.\n\n### Following the calls\n\n`digits(4096)` can't return until it knows `digits(409)`, which waits for `digits(40)`, which waits for `digits(4)`. That one is a base case, and returns 1. Then the waiting calls finish, from the newest to the oldest, each adding 1 to what it got back:\n\n```text\ndigits(4096) = 1 + digits(409)\n                   digits(409) = 1 + digits(40)\n                                     digits(40) = 1 + digits(4)\n                                                      digits(4) = 1\n                                     digits(40) = 1 + 1 = 2\n                   digits(409) = 1 + 2 = 3\ndigits(4096) = 1 + 3 = 4\n```\n\nTwo questions check a recursive method:\n\n1. Is every base case answered correctly, without a recursive call?\n2. Does every other input get closer to a base case with each call? Here, dividing by 10 makes any number of 10 or more smaller, so the calls end up below 10.\n\nIf both are true, and the recursive case is right whenever the smaller call returns the right answer, the method is right for every input.\n\n### Where the base case comes from\n\nChoose the smallest input for which the answer is obvious. For a sum of the numbers from 1 to n, that's n = 0: there's nothing to add, and the sum is 0. Picking 0 rather than 1 also makes the method work when it's called with 0.\n","task":"A grocer stacks oranges in a triangle: the bottom row has `rows` oranges, the row above it one fewer, and so on up to a single orange at the top. Write the method `oranges(int rows)`, which returns how many oranges the stack has, with recursion and no loop. A stack of 0 rows has 0 oranges. The check runs:\n\n```java\nSystem.out.println(oranges(4));\nSystem.out.println(oranges(1));\n```\n\nand expects:\n\n```\n10\n1\n```\n","kind":"code","seed":"public class Main {\n    public static void main(String[] args) {\n        System.out.println(oranges(4));\n        System.out.println(oranges(1));\n    }\n\n    public static int oranges(int rows) {\n        return 0;\n    }\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        System.out.println(oranges(4));\n        System.out.println(oranges(1));\n    }\n\n    public static int oranges(int rows) {\n        if (rows == 0) {\n            return 0;\n        }\n        return rows + oranges(rows - 1);\n    }\n}\n","hints":["The base case: a stack of 0 rows has 0 oranges.","A stack of `rows` rows is its bottom row, `rows` oranges, plus a stack of `rows - 1` rows on top: `return rows + oranges(rows - 1);`"],"tests":[{"name":"Test 1","stdin":"","call":"System.out.println(oranges(4));\nSystem.out.println(oranges(1));\n","expect":"10\n1","hidden":false},{"name":"Test 2","stdin":"","call":"System.out.println(oranges(0));\nSystem.out.println(oranges(2));\nSystem.out.println(oranges(10));\n","expect":"0\n3\n55","hidden":true},{"name":"Test 3","stdin":"","call":"System.out.println(oranges(100));\nSystem.out.println(oranges(1000));\n","expect":"5050\n500500","hidden":true}],"require":[{"pattern":"\\boranges\\s*\\(","min":4,"message":"`oranges` should call itself."}],"forbid":[{"pattern":"\\b(for|while)\\b","message":"Do it with recursion, without a loop."}],"more":[{"task":"A bookshop owner wants to know in how many different orders a number of books can stand on a shelf. One book stands in 1 order. With 2 books there are 2 orders, and with 3 books 6: any of the 3 can stand first, and the other 2 stand after it in 2 orders. In general, `n` books stand in `n` times as many orders as `n - 1` books. That's the factorial of `n`, written `n!`. An empty shelf counts as 1 order (`0! = 1`).\n\nThe numbers grow fast, so write the method `orders(int books)` that returns a `long`, with recursion and no loop. A `long` holds factorials up to `20!`. The check runs:\n\n```java\nSystem.out.println(orders(3));\nSystem.out.println(orders(0));\nSystem.out.println(orders(15));\n```\n\nand expects:\n\n```\n6\n1\n1307674368000\n```\n","kind":"code","seed":"public class Main {\n    public static void main(String[] args) {\n        System.out.println(orders(3));\n        System.out.println(orders(0));\n        System.out.println(orders(15));\n    }\n\n    // Write the method orders here.\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        System.out.println(orders(3));\n        System.out.println(orders(0));\n        System.out.println(orders(15));\n    }\n\n    public static long orders(int books) {\n        if (books == 0) {\n            return 1;\n        }\n        return books * orders(books - 1);\n    }\n}\n","hints":["The base case is an empty shelf: `if (books == 0)`, return 1.","Otherwise the answer is `books` times the orders of one book fewer: `return books * orders(books - 1);`. Since `orders` returns a long, the multiplication is done with longs."],"tests":[{"name":"Test 1","stdin":"","call":"System.out.println(orders(3));\nSystem.out.println(orders(0));\nSystem.out.println(orders(15));\n","expect":"6\n1\n1307674368000","hidden":false},{"name":"Test 2","stdin":"","call":"System.out.println(orders(1));\nSystem.out.println(orders(2));\nSystem.out.println(orders(5));\nSystem.out.println(orders(10));\n","expect":"1\n2\n120\n3628800","hidden":true},{"name":"Test 3","stdin":"","call":"System.out.println(orders(13));\nSystem.out.println(orders(20));\n","expect":"6227020800\n2432902008176640000","hidden":true}],"require":[{"pattern":"\\bpublic\\s+static\\s+long\\s+orders\\s*\\(\\s*int\\s+\\w+\\s*\\)","message":"Write the method as `public static long orders(int books)`."},{"pattern":"\\borders\\s*\\(","min":5,"message":"`orders` should call itself."}],"forbid":[{"pattern":"\\b(for|while)\\b","message":"Do it with recursion, without a loop."}]},{"task":"A sheet of paper doubles in thickness each time it's folded in half; a strip cut in three and stacked triples. Write the method `power(int base, int exponent)`, which returns `base` multiplied by itself `exponent` times, as a `long`: `power(2, 5)` is 2 * 2 * 2 * 2 * 2, 32. Any number to the power of 0 is 1, and that's the base case. Use recursion, no loop and no `Math.pow`. The exponent is never negative. The check runs:\n\n```java\nSystem.out.println(power(2, 5));\nSystem.out.println(power(3, 4));\nSystem.out.println(power(7, 0));\n```\n\nand expects:\n\n```\n32\n81\n1\n```\n","kind":"code","seed":"public class Main {\n    public static void main(String[] args) {\n        System.out.println(power(2, 5));\n        System.out.println(power(3, 4));\n        System.out.println(power(7, 0));\n    }\n\n    // Write the method power here.\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        System.out.println(power(2, 5));\n        System.out.println(power(3, 4));\n        System.out.println(power(7, 0));\n    }\n\n    public static long power(int base, int exponent) {\n        if (exponent == 0) {\n            return 1;\n        }\n        return base * power(base, exponent - 1);\n    }\n}\n","hints":["`power(2, 5)` is 2 times `power(2, 4)`: the base stays the same, and the exponent gets one smaller with each call.","When the exponent is 0, return 1. Otherwise, `return base * power(base, exponent - 1);`"],"tests":[{"name":"Test 1","stdin":"","call":"System.out.println(power(2, 5));\nSystem.out.println(power(3, 4));\nSystem.out.println(power(7, 0));\n","expect":"32\n81\n1","hidden":false},{"name":"Test 2","stdin":"","call":"System.out.println(power(10, 1));\nSystem.out.println(power(5, 3));\nSystem.out.println(power(1, 50));\nSystem.out.println(power(0, 4));\n","expect":"10\n125\n1\n0","hidden":true},{"name":"Test 3","stdin":"","call":"System.out.println(power(2, 40));\nSystem.out.println(power(10, 15));\nSystem.out.println(power(-3, 3));\n","expect":"1099511627776\n1000000000000000\n-27","hidden":true}],"require":[{"pattern":"\\bpublic\\s+static\\s+long\\s+power\\s*\\(\\s*int\\s+\\w+\\s*,\\s*int\\s+\\w+\\s*\\)","message":"Write the method as `public static long power(int base, int exponent)`."},{"pattern":"\\bpower\\s*\\(","min":5,"message":"`power` should call itself."}],"forbid":[{"pattern":"\\b(for|while)\\b","message":"Do it with recursion, without a loop."},{"pattern":"Math\\s*\\.\\s*pow","message":"Don't use `Math.pow`: multiply, with recursion."}]}]}