{"id":"arrays-length-and-loops","slug":"length-and-loops","title":"Length and loops","text":"An array knows its own size: `hours.length`.\n\n```java\nint[] hours = new int[7];\nSystem.out.println(\"The week has \" + hours.length + \" days\");\n```\n\n```output\nThe week has 7 days\n```\n\n`length` has no parentheses. It isn't a method but a **field**: a value stored with the array. That's easy to mix up, because each kind of collection says it differently:\n\n| Kind | Its size |\n|---|---|\n| a list | `list.size()` |\n| a String | `text.length()` |\n| an array | `hours.length` |\n\nWith parentheses, javac looks for a method called `length` and doesn't find one:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        int[] hours = new int[7];\n        System.out.println(hours.length());\n    }\n}\n```\n\n```javac\nMain.java:4: error: cannot find symbol\n        System.out.println(hours.length());\n                                ^\n  symbol:   method length()\n  location: variable hours of type int[]\n1 error\n```\n\n### Looping over the indexes\n\nThe indexes go from 0 to `length - 1`, so the same for loop you used with lists goes through all of them. Here one loop fills the array and a second one prints it:\n\n```java\nint[] squares = new int[5];\nfor (int i = 0; i < squares.length; i++) {\n    squares[i] = i * i;\n}\nfor (int i = 0; i < squares.length; i++) {\n    System.out.println(i + \" squared is \" + squares[i]);\n}\n```\n\n```output\n0 squared is 0\n1 squared is 1\n2 squared is 4\n3 squared is 9\n4 squared is 16\n```\n\nBecause both loops use `squares.length` instead of the number 5, changing `new int[5]` is all it takes to make the program work with a bigger array.\n\n### for-each\n\nWhen you need the values but not the indexes, a for-each loop works on an array just as it does on a list:\n\n```java\nint[] squares = new int[5];\nfor (int i = 0; i < squares.length; i++) {\n    squares[i] = i * i;\n}\nint sum = 0;\nfor (int square : squares) {\n    sum += square;\n}\nSystem.out.println(\"Sum: \" + sum);\n```\n\n```output\nSum: 30\n```\n\nThe loop variable `square` gets a copy of each element in turn. Assigning to it doesn't change the array, so filling or changing an array takes the loop over the indexes.\n\n### One past the end\n\nAn index that isn't in the array crashes the program, as it does with a list. The usual cause is `<=` where `<` belongs:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        int[] squares = new int[3];\n        for (int i = 0; i <= squares.length; i++) {\n            squares[i] = i * i;\n            System.out.println(squares[i]);\n        }\n    }\n}\n```\n\n```output\n0\n1\n4\n```\n\n```crash\nException in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3\n\tat Main.main(Main.java:5)\n```\n\nThe message names the index that failed and the array's length. An array of length 3 has the indexes 0, 1 and 2, so index 3 doesn't exist. The loop that visits every index is `for (int i = 0; i < array.length; i++)`.\n","task":"Fill in the blanks, so the first loop runs once for each element and the for-each loop goes through the array `tens`. The program prints:\n\n```\n10\n20\n30\n40\n```\n","kind":"fill","seed":"public class Main {\n    public static void main(String[] args) {\n        int[] tens = new int[4];\n        for (int i = 0; i < tens.[[length]]; i++) {\n            tens[i] = (i + 1) * 10;\n        }\n        for (int value : [[tens]]) {\n            System.out.println(value);\n        }\n    }\n}\n","solution":"public class Main {\n    public static void main(String[] args) {\n        int[] tens = new int[4];\n        for (int i = 0; i < tens.length; i++) {\n            tens[i] = (i + 1) * 10;\n        }\n        for (int value : tens) {\n            System.out.println(value);\n        }\n    }\n}\n","hints":["An array's size is its field `length`, with no parentheses.","A for-each loop names the array after the colon: `for (int value : tens)`."],"tests":[{"name":"Output","stdin":"","expect":"10\n20\n30\n40","hidden":false}],"require":[],"forbid":[],"more":[{"task":"Read a whole number `n` (at least 1). Create an array of `n` ints that holds the powers of two: the first element is 1, and every element after it is twice the one before. Then print the elements with a for-each loop. For the input `5` the program prints:\n\n```\n1\n2\n4\n8\n16\n```\n","kind":"code","seed":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        int n = Integer.valueOf(scanner.nextLine());\n\n    }\n}\n","solution":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        int n = Integer.valueOf(scanner.nextLine());\n        int[] powers = new int[n];\n        powers[0] = 1;\n        for (int i = 1; i < powers.length; i++) {\n            powers[i] = powers[i - 1] * 2;\n        }\n        for (int power : powers) {\n            System.out.println(power);\n        }\n    }\n}\n","hints":["The size can come from a variable: `int[] powers = new int[n];`. Set `powers[0] = 1;` first.","The filling loop starts at index 1, and each element is the one before it times two: `powers[i] = powers[i - 1] * 2;`"],"tests":[{"name":"Test 1","stdin":"5\n","expect":"1\n2\n4\n8\n16","hidden":false},{"name":"Test 2","stdin":"1\n","expect":"1","hidden":true},{"name":"Test 3","stdin":"10\n","expect":"1\n2\n4\n8\n16\n32\n64\n128\n256\n512","hidden":true}],"require":[{"pattern":"new\\s+int\\s*\\[\\s*\\w+\\s*\\]","message":"Keep the powers in an array: `new int[n]`."},{"pattern":"for\\s*\\(\\s*int\\s+\\w+\\s*:","message":"Print the elements with a for-each loop."}],"forbid":[{"pattern":"\\bArrayList\\b","message":"Use an array for this one, not a list."}]},{"task":"This program should read a count, fill an array with that many odd numbers (1, 3, 5 and so on), and print them from the last to the first. It crashes. Fix both loops. For the input `4` the program prints:\n\n```\n7\n5\n3\n1\n```\n","kind":"code","seed":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        int count = Integer.valueOf(scanner.nextLine());\n        int[] odd = new int[count];\n        for (int i = 0; i <= odd.length; i++) {\n            odd[i] = 2 * i + 1;\n        }\n        for (int i = odd.length; i > 0; i--) {\n            System.out.println(odd[i]);\n        }\n    }\n}\n","solution":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        int count = Integer.valueOf(scanner.nextLine());\n        int[] odd = new int[count];\n        for (int i = 0; i < odd.length; i++) {\n            odd[i] = 2 * i + 1;\n        }\n        for (int i = odd.length - 1; i >= 0; i--) {\n            System.out.println(odd[i]);\n        }\n    }\n}\n","hints":["The first loop reaches index `odd.length`, one past the last index. It should stop before it: `i < odd.length`.","The last index is `odd.length - 1`, and the first is 0, so the second loop goes from `odd.length - 1` down to `i >= 0`."],"tests":[{"name":"Test 1","stdin":"4\n","expect":"7\n5\n3\n1","hidden":false},{"name":"Test 2","stdin":"1\n","expect":"1","hidden":true},{"name":"Test 3","stdin":"6\n","expect":"11\n9\n7\n5\n3\n1","hidden":true}],"require":[{"pattern":"\\bodd\\s*\\[","min":2,"message":"Keep both loops working on the array `odd`: one fills it and one prints it."}],"forbid":[]}]}