Question: Java Coding: Given a non-empty array where each integer is in [0, 99], the following program aims to output the mode number(s) of the array.
Java Coding: Given a non-empty array where each integer is in [0, 99], the following program aims to output the mode number(s) of the array. The mode number is the most frequently occurring number in the array. There could be more than one mode number in an array. For example, the array {7, 9, 9, 4, 5, 6, 7, 7, 9} has two mode numbers, which are 7 and 9.
There are five syntax, runtime and logical errors in the program. Circle the line numbers, underline the errors directly on the program, and correct the errors on the right hand box.
DO NOT provide more than 5 errors; otherwise marks will be deducted accordingly.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | public class Q3 { public static void main(String[] args) { int[] numbers = {7, 9, 9, 4, 5, 6, 7, 7, 9}; int[] modes = mode(numbers); for (int i = 0; i < modes.length; ++i) { System.out.print(modes[i] + " "); } }
public static void mode(int[] numbers) { // initialize a counter for each possible integer in [0, 99] int[] count = new int[100]; // count for (int i = 0; i < numbers.length; ++i) { ++count[numbers[i]]; }
// find out the max count and determine how many mode // numbers in total int max = 0; int num_mode; for (int i = 0; i <= count.length; ++i) { if (count[i] > max) { max = count[i]; num_mode = 1; } else if (count[i] == max) { ++num_mode; } }
// find out all mode numbers int modes = new int[num_mode]; int index = 0; for (int num = 0; num < 100; ++num) { if (count[num] == max) { modes[++index] = num; } } return modes; } } |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
