Wednesday, 17 December 2014

// The "UsingArraysExample1A" class.  Page 313.
// (from the Carter book)

// Example 1A:
//
// Having seen how to create arrays in Java, let us now
// examine some of the ways that we can operate on them
// and their elements.
//
// 1. The elements of an array can be treated like any other
// variable of that type.  We can assign values to them,
// print them, use them in expressions, and so on.
// 2. Often, we want to perform some operation on every
// element of an array.  We sometimes refer to this as
// 'indexing' through the array.
// 3. For example, if we wanted to create an array called
// "flags" containing 100 boolean values all set to true
// (rather than the standard initialization to false), we
// could use the code below:

public class UsingArraysExample1A
{
    public static void main (String[] args)
    {
        System.out.println ("Using Arrays - Example 1A");
        System.out.println ();
        boolean[] flags = new boolean [100];
        System.out.println ("boolean [] flags = new boolean [100];");
        // to cycle through (index through)
        // all of the array's elements, we do this:

        for (int i = 0 ; i < flags.length ; i++)
        {
            flags [i] = true;
        } // end of for loop # 1

        // now, if you want to see the values that the array
        // flags now holds, do this:
        for (int i = 0 ; i < flags.length ; i++)
        {
            System.out.println (i + "\t" + flags [i]);
        } // end of fro loop # 2

    } // main method
} // UsingArraysExample1A class
//
// Example 1A (continued):
//
// 4. In this example, we used a 'for' loop to index through
// the array. We also could have used a 'while' or 'dowhile'
//(a.k.a. 'do') loop to do the same thing, but using a 'for'
// loop is simplest.  It is almost always the case that a 'for'
// loop is the best way to index through an array.
// 5. Notice also the use of 'flags.length' to determine the
// upper bound of the array.  This is more reliable and probably
// clearer to a reader than using the value 100 instead.

No comments:

Post a Comment