Nested Loops with Arrays

When processing arrays, it is sometimes necessary to put a loop inside of another loop – this is called a nested loop.

Suppose we want to ask the user for 10 numbers, store them in an array, and then find and print the mode of the array. (The mode of a list of numbers is the most frequently occurring element. In the case of a tie, we will accept any of the most frequently occurring elements as the mode. For example, the mode of {1,2,4,1,2,1,3} is 1, and the mode of {2,4,1,4,2,4,2} is either 4 or 2.)

Here is the code:

Scanner s = new Scanner(System.in);

//create an array to hold the numbers
int[] nums = new int[10];

//get the input numbers
for (int i = 0; i < nums.length; i++) 
{
    System.out.print("Enter a positive number: ");
    nums[i] = s.nextInt();
}

//the index of (one of) the mode values
int modeIndex = 0;

//the number of times our mode value appears in nums
int modeCount = 0;

//for each element in the array, count how many times that element appears
for (int i = 0; i < nums.length; i++) 
{
    int count = 0;
    //count how many times the element at position i appears
    for (int j = 0; j < nums.length; j++) 
    {
        //did we find another occurrence of the element at nums[i]?
        if (nums[i] == nums[j])
        {
            count++;
        }
    }

    //is our count better than our previous best?
    if (count > modeCount)
    {
        //we have a new best modeCount
        modeCount = count;

        //we have a new mode index
        modeIndex = i;
    }
}

//print the mode
System.out.printf("The mode is %d, which appeared %d times%n", nums[modeIndex], modeCount);

Notice that every time our outer loop executes, we go through each iteration of the inner loop. This allows our outer loop to keep track of which element we are counting, and our inner loop to actually count the number of occurrences of that element.

(Note: the implementation above is not the most efficient way to calculate the mode. We could modify our inner loop to not have to make quite as many iterations, but still compute the correct value. This idea is left as an exercise to the reader. Another even faster implementation is to use a data structure called a hash table, which we will see at the end of the text book.)