{"id":"arrays-searching","slug":"searching-an-array","title":"Searching an array","text":"Searching an array works just like searching a list with a loop: go through the indexes, and look at each element. This program reads a week of midday temperatures and does the three searches that come up most often:\n\n```java\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        int[] temperatures = new int[7];\n        for (int i = 0; i < temperatures.length; i++) {\n            temperatures[i] = Integer.valueOf(scanner.nextLine());\n        }\n\n        int firstFrost = -1;\n        for (int i = 0; i < temperatures.length; i++) {\n            if (temperatures[i] < 0) {\n                firstFrost = i;\n                break;\n            }\n        }\n        if (firstFrost == -1) {\n            System.out.println(\"No frost this week\");\n        } else {\n            System.out.println(\"First frost on day \" + firstFrost);\n        }\n\n        int warmDays = 0;\n        for (int temperature : temperatures) {\n            if (temperature >= 10) {\n                warmDays++;\n            }\n        }\n        System.out.println(\"Warm days: \" + warmDays);\n\n        int warmest = temperatures[0];\n        int warmestDay = 0;\n        for (int i = 1; i < temperatures.length; i++) {\n            if (temperatures[i] > warmest) {\n                warmest = temperatures[i];\n                warmestDay = i;\n            }\n        }\n        System.out.println(\"Warmest: \" + warmest + \" on day \" + warmestDay);\n    }\n}\n```\n\n```input\n8\n12\n3\n-2\n11\n-4\n5\n```\n\n```output\nFirst frost on day 3\nWarm days: 2\nWarmest: 12 on day 1\n```\n\n- **Finding an index.** `firstFrost` starts at -1, which is never an index, so it means \"not found yet\". At the first match, the loop stores the index and leaves with `break`. If nothing matched, it's still -1 after the loop.\n- **Counting.** A counter and an `if`. The index isn't needed, so a for-each loop is enough.\n- **The largest value and its index.** Start from the first element, not from 0: in a week where every day is below zero, 0 would beat them all, and the answer would be a temperature that never happened. Keep the index next to the value, and update both together.\n\nWith `>`, the first of two equal values wins, because a later one isn't bigger. With `>=`, the last one would win.\n","task":"The program reads the five jumps of a long jump contest, in centimeters. Fill in the blanks, so it finds the longest jump and the round it was in (the round is the index plus one). For the input `540`, `575`, `612`, `598` and `602` it prints:\n\n```\nBest jump: 612 cm, in round 3\n```\n","kind":"fill","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[] jumps = new int[5];\n        for (int i = 0; i < jumps.length; i++) {\n            jumps[i] = Integer.valueOf(scanner.nextLine());\n        }\n        int best = jumps[0];\n        int bestIndex = 0;\n        for (int i = 1; i < jumps.length; i++) {\n            if (jumps[i] > [[best]]) {\n                best = jumps[i];\n                bestIndex = [[i]];\n            }\n        }\n        System.out.println(\"Best jump: \" + best + \" cm, in round \" + (bestIndex + 1));\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[] jumps = new int[5];\n        for (int i = 0; i < jumps.length; i++) {\n            jumps[i] = Integer.valueOf(scanner.nextLine());\n        }\n        int best = jumps[0];\n        int bestIndex = 0;\n        for (int i = 1; i < jumps.length; i++) {\n            if (jumps[i] > best) {\n                best = jumps[i];\n                bestIndex = i;\n            }\n        }\n        System.out.println(\"Best jump: \" + best + \" cm, in round \" + (bestIndex + 1));\n    }\n}\n","hints":["Each jump is compared with the best one so far.","When a jump is better, the loop remembers both its value and its index, which is `i`."],"tests":[{"name":"Test 1","stdin":"540\n575\n612\n598\n602\n","expect":"Best jump: 612 cm, in round 3","hidden":false},{"name":"Test 2","stdin":"700\n650\n690\n600\n640\n","expect":"Best jump: 700 cm, in round 1","hidden":true},{"name":"Test 3","stdin":"500\n520\n510\n530\n530\n","expect":"Best jump: 530 cm, in round 4","hidden":true}],"require":[],"forbid":[],"more":[{"task":"The program reads the number of students in a class, then each student's locker number: student 1's first, then student 2's, and so on. Then it reads one more locker number. Search the array for it, and print which student has that locker (the index plus one), or that the locker is free. For the input `4`, `17`, `5`, `42`, `8` and then `42` the program prints:\n\n```\nLocker 42 belongs to student 3\n```\n\nFor the locker `99` it would print `Locker 99 is free`.\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 students = Integer.valueOf(scanner.nextLine());\n        int[] lockers = new int[students];\n        for (int i = 0; i < lockers.length; i++) {\n            lockers[i] = Integer.valueOf(scanner.nextLine());\n        }\n        int wanted = 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 students = Integer.valueOf(scanner.nextLine());\n        int[] lockers = new int[students];\n        for (int i = 0; i < lockers.length; i++) {\n            lockers[i] = Integer.valueOf(scanner.nextLine());\n        }\n        int wanted = Integer.valueOf(scanner.nextLine());\n        int student = -1;\n        for (int i = 0; i < lockers.length; i++) {\n            if (lockers[i] == wanted) {\n                student = i + 1;\n                break;\n            }\n        }\n        if (student == -1) {\n            System.out.println(\"Locker \" + wanted + \" is free\");\n        } else {\n            System.out.println(\"Locker \" + wanted + \" belongs to student \" + student);\n        }\n    }\n}\n","hints":["Start with `int student = -1;` to mean \"not found\". In the loop, when `lockers[i] == wanted`, store `i + 1` and `break`.","After the loop, `student == -1` means the locker number wasn't in the array."],"tests":[{"name":"Test 1","stdin":"4\n17\n5\n42\n8\n42\n","expect":"Locker 42 belongs to student 3","hidden":false},{"name":"Test 2","stdin":"4\n17\n5\n42\n8\n99\n","expect":"Locker 99 is free","hidden":true},{"name":"Test 3","stdin":"3\n31\n12\n7\n31\n","expect":"Locker 31 belongs to student 1","hidden":true},{"name":"Test 4","stdin":"3\n31\n12\n7\n7\n","expect":"Locker 7 belongs to student 3","hidden":true}],"require":[],"forbid":[{"pattern":"\\bArrayList\\b","message":"Search the array, without a list."}]},{"task":"Read a count, then that many whole numbers. Print their average, and then how many of the numbers are above the average. The numbers must be kept in an array: the average is known only after the last one is read, and only then can they be compared with it. For the input `4`, `2`, `9`, `4` and `7` the program prints:\n\n```\nAverage: 5.5\nAbove average: 2\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\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[] numbers = new int[count];\n        int sum = 0;\n        for (int i = 0; i < numbers.length; i++) {\n            numbers[i] = Integer.valueOf(scanner.nextLine());\n            sum += numbers[i];\n        }\n        double average = (double) sum / numbers.length;\n        int above = 0;\n        for (int number : numbers) {\n            if (number > average) {\n                above++;\n            }\n        }\n        System.out.println(\"Average: \" + average);\n        System.out.println(\"Above average: \" + above);\n    }\n}\n","hints":["Read the numbers into an array of `count` ints, and add them up as you go. `(double) sum / count` keeps the decimals of the average.","Then a second loop over the array counts the numbers that are `> average`."],"tests":[{"name":"Test 1","stdin":"4\n2\n9\n4\n7\n","expect":"Average: 5.5\nAbove average: 2","hidden":false},{"name":"Test 2","stdin":"3\n5\n5\n5\n","expect":"Average: 5.0\nAbove average: 0","hidden":true},{"name":"Test 3","stdin":"5\n1\n2\n3\n4\n100\n","expect":"Average: 22.0\nAbove average: 1","hidden":true},{"name":"Test 4","stdin":"1\n-3\n","expect":"Average: -3.0\nAbove average: 0","hidden":true}],"require":[{"pattern":"new\\s+int\\s*\\[","message":"Keep the numbers in an array."}],"forbid":[{"pattern":"\\bArrayList\\b","message":"Use an array for this one, not a list."}]}]}