Processing Array Elements

7.2 Processing Array Elements

Individual array elements are processed like variable.
Example
/**
 * This program displays even values
 * of array.
 */
public class EvenArray
{
   public static void main(String[] args)
   {
      int[] list = { 2, 5, 16, 18, 21 };

      // Display all even elements of array
      System.out.println("The even numbers of array:");

      for (int i = 0; i < list.length; i++)
      {
         if (list[i] % 2 == 0)
         {
            System.out.print(list[i] + " ");
         }
      }

      System.out.println();
   }
}
Output :
The even numbers of array:
2 16 18

Copying arrays

When you copy an array variable, remember that you are copying a reference to the array. For example:
double[] a = new double [3];
double[] b = a;
array-copy
This code creates one array of three doubles, and sets two different variables to refer to it. This situation is a form of aliasing.
If want to allocate a new array and copy elements from one to the other.
double[] list1 = {3.9, 6.7, 13.3};          
double[] list2 = new double [list1.length];

for (int i = 0; i < list1.length; i++)
{ 
   list2[i] = list1[i];
}

Finding largest value in array

/**
 * This program find the largest value
 *  in an array
 */
public class PassArray
{
   public static void main(String[] args)
   {
      final int SIZE = 10;    // Size of the array

      // Create an array.
      int[] list = new int[SIZE];

      // Fill array with random values
      for (int i = 0; i < list.length; i++)
      {
         list[i] = (int) (Math.random() * 100);
      }

      int max = 0;    // hold index number of largest number

      // Finding largest value.
      for (int i = 0; i < list.length; i++)
      {
         if (list[i] > list[max])
         {
            max = i;
         }
      }

      // Show all elements of array
      System.out.print("Elements are : ");

      for (int i = 0; i < list.length; i++)
      {
         System.out.print(list[i] + " ");
      }

      System.out.println();

      // Show largest value of array
      System.out.println("Largest value is " + list[max]);
   }
}
Output :
Elements are : 27 8 70 5 47 36 86 89 4 40
Largest value is 89

No comments:

Post a Comment

Pages