Arrays

Note:  Please keep the programs that you create today, in case you have a dispute about your grades for the ICEs at the end of the quarter. When you're working with a partner, each person should save their own, individual copy

Part  1: Arrays (Background)

 

You create an array using the following syntax:

 

     int howManyElements = 4;

int[]   grades = new int[howManyElements];

 

            Once the program has executed this line, the variable "grades" will refer to a region of memory that can hold many values.  The region of memory is divided into separate 'spaces', or 'slots', and I often call each slot an "element".  I chose the name grades because I thought it would be easy to remember you can chose any name you want, such as array, studentGrades, gibberish, etc.  Try to pick names that are meaningful.

 

You can think of the slots as all being adjacent in memory.  So a 4 element array can be thought of as looking like this:

 

Figure 1: An illustration of the 'grades' array

 

    (And yes, there are zeros in the array elements - Java will put a default value (for numbers, this is zero) into each space in the array for you, without you having to do anything) 

            Notice that the way we refer to an element is by using the name for the whole array, then an open bracket after the name (  [  ), a subscript, which is a number that tells Java which slot to use, and then the close bracket (  ]  ).  It's also very important to notice that the first element in the array is at slot 0.  Each slot/element is, in fact, a variable, and so can hold a value.  Each slot/element holds a separate value, and so you can think of each element of the array as being a separate variable.  The only difference between a normal variable and an array element is that the array elements all share the same name (but each element has a unique subscript!)

 

            You can access array slots by saying:

 grades[1] = 3;
     int slotNumber = 1;
     System.out.println("Slot #1 contains: " + grades[slotNumber] );

     grades[ 4 ] = 10; // What does this do?  Will it compile? 

                       // Will it run ok?

 

            You can write almost any expression you want on the right hand side of the assignment operator.  For example, you could write:

 

     grades[1] = 1 + 3 * 7;

 

            Assuming that you'd declared the variables i and j, you could also write:

 

     int i = 1;

     int j = 3;

     grades [1] = i + j * 7;

 

            You can also write any expression that will evaluate to an integer number inside the brackets, as well, like so:

 

    grades [  1 + 2 ] = 81;

    grades[2] = grades[0] + grades[1];

 

            And you can use variable in these expressions, just like normal:

 

     int i = 2;

     grades[i+1] = 2;

 

            In fact, one of the most common expressions used to get an array element is just that a variable.  For example, you could quickly set the first five elements of your array to be the numbers 1 through 5 using:

 

           

int i = 0;
while(i < 4)
{
     grades[i] = (i+1);

      i++;
}

for(int i = 0; i < grades.length ; i++)
{
     grades[i] = (i+1);

}

 

 

Part  2: Array (Looking at details) 

            For each of the following examples, write out (on paper) (1) a picture of what's in the array (this should look like Figure 1, above, except that the zero's will be replaced by the values that are actually present), (2) what will be printed when the given program is run.  Also, you need to be prepared to explain, line by line, how the program produces these results.  If the program has an error in it (either a compile-time error, or a logical error), make sure that you can clearly explain what the error is. Remember that part of the point of these quick exercises is to make sure that you have a chance to try out some of the more confusing, but infrequently used, ways in which arrays are used see if you can figure out what these programs should do!

A )  
public static void main(String [] args)

{
    int [] MyAr;
    MyAr = new int[3];
    MyAr[0] = 3;
    MyAr[1] = 4-1;
    int i = 2;
    MyAr[i] = 6 * 2;
    System.out.println( MyAr[0] );
    System.out.println( MyAr[i - 1] );
    System.out.println( MyAr[2] );
    int temp = MyAr[1] + MyAr[2];
    System.out.println(temp);
}

 

B )  
public static void main(String [] args)
{
    double [] MyAr;
    MyAr = new double [3];
    MyAr[500] = 5;
    System.out.println( MyAr[0] );
}

C )  
public static void main(String [] args)
{
    double [] MyAr;
    MyAr = new double [4];
    int i;
    for( i = 0; i < MyAr.length; i++)
    {
        MyAr[i] = i;
    }
    for( i = 0; i < MyAr.length; i++)
    {
        System.out.println( MyAr[i] );
    }
}

 

D )   //Same as the previous one except the second loop condition
public static void main(String [] args)
{
    double [] MyAr;
    MyAr = new double [4];
    int i;
    for( i = 0; i < MyAr.length; i++)
    {
        MyAr[i] = i;
    }
    for( i = 0; i <= MyAr.length; i++)
    {
        System.out.println( MyAr[i] );
    }
}

 

E )  
public static void main(String [] args)
{
    double [] MyAr;
    MyAr = new double [4];
    MyAr[0] = 10;
    MyAr[1] = 9.5;
    MyAr[2] = 20;
    MyAr[3] = 40;
    double total = 0;
    for( int i = 0; i < MyAr.length; i++)
    {
        total = total + MyAr[i];
    }
    System.out.println( "total is: " + total );
}

 

F )  
public static void main(String [] args)
{
    double [] MyAr;
    MyAr = new double [4];
    MyAr[0] = 10;
    MyAr[1] = 9.5;
    MyAr[2] = 20;
    MyAr[3] = 40;
    int i;
    double min = 10000;
    for( i = 0; i < MyAr.length; i++)
    {
        if( MyAr[i] < min )
        {
            min = MyAr[i];
        }
       
    }
    System.out.println( "Min is: " + min );
}

 

 

Part  3: Array (Tracing An Example In Detail) 

            For the following code snippet, trace out the execution of the program using a detailed program trace table

   // Assume the user types on the keyboard
//        1 <enter> 2.1 <enter> 3 <enter> 0.0 <enter>
public static void main(String [] Wargs)
{
   
double [] MyAr;
    MyAr = new double [4];
    Scanner in = new Scanner(System.in);
    double usersNumber;
    int i;
    for(i = 0; i < MyAr.length; i++)
    {
        System.out.println("Type a number!");
        usersNumber = in.nextDouble();
        MyAr[i] = usersNumber;
    }
    double total = 0.0;
    for( i = 0; i < MyAr.length; i++)
    {
        System.out.println( MyAr[i] );
        total = total + MyAr[i];
    }
 System.out.println( "The last element is: " + MyAr[i-1]);
     System.out.println( "Total is: " +  total);
}

 

 

Part  4: Simple Practice Using Arrays

Create an array of doubles that has space enough for five separate values.  Write a while loop that will set the value of the first 5 elements of your array to the numbers 1 through 5.  Then write a for loop that will print out the first 5 elements of your array.  Use the provided Arrays_With_Loops.java file as a starter file.

 

Part  5: Practice Using Arrays: Grades

 

You may use any file you want to for this exercise.

Create an array of doubles that has space enough for five separate values.  Write a while loop that will go from 0 (the first element's address) up to 4 (the last one).  For each element, use keyboard I/O to ask the user for a grade (use the nextDouble() method to get the value), and store that grade into the given slot.  Once all 5 grades have been entered, use a second loop to print out the values of all the grades.  Then, create a double variable named total (which should be initialized to zero).  Use a third loop to go through the array a third time, and add the value of each slot to the total variable.  Next, print out the average of all the grades in the class.

Question: Is there a more efficient way of accomplishing this work?

 

Part  6: Practice Using Part Of An Array: Grades Again!

 

Building off the previous exercise, you should add some more code to the end of your program, which will ask the user for a number, and then use a loop to go through the array, and see if any of the values in the array match the number that the user typed in.  If there is a match, you should print out a message telling the user that their number was found in the array.  The message should also tell the user which index the number was found at.