Iterating through an array

The combination of the For loop and an array is a powerful one. It lets us go through every element in order, using it's index without having to write repeated code (in fact we have already written very similar code to access the characters at any given position in a string). Example code to iterate through an array called someIntArray is shown here:

for (int i = 0; i < someIntArray.length; i++) {
     int individualItemValue = someIntArray[i];
     //do something with individualItemValue
 }
To use this for any other type of array just requires you to know the name of the array, and the type of contents (e.g. String, double etc.) that it contains

Using arrays for calculations

One use of arrays can be to perform calculations, taking an array of integers for example, we can use a variable declared outside the loop to keep a running total, as follows

int[] bankDeposits = {2999,7000,1000,35000}; //values in pence
int runningTotal = 0;

for (int i = 0; i < bankDeposits.length; i++) {
    int individualDeposit = bankDeposits[i];
    runningTotal += individualDeposit;
}
System.out.println("Total deposits: " + runningTotal);

Populating an array using a loop

In the same way we can read values in an array using a loop we could populate them - the following example code shows how prompt a user for information until an array has been populated

//array to store films
String[] fav3Films = new String[3];
//create the scanner outside the loop so it doesnt get created multiple times
java.util.Scanner inputScanner = new java.util.Scanner(System.in);

for (int i = 0; i < fav3Films.length; i++) {
    System.out.println("Please type (another) favourite film");
    String favFilm = inputScanner.nextLine();
    fav3Films[i] = favFilm;
}

Task

  1. Create a new command line application in IntelliJ
  2. Create an empty array to store predicted module results for 6 modules (as integers)
  3. Use a loop to prompt the user to enter their predicted grade for each of the 6 modules (and store them in the array)
  4. Use techniques learned above with some adaptation, to calculate and print the predicted average mark across all 6 modules
  5. Based on the average value, output the predicted degree classification (70+ = 1st, 60-69 = 2:1, 50-59 = 2:2, 40 - 49 = 3rd, under 40 = Fail)