Print Page Print Page

CH8 – Array Traversal

  1. Create a new class named ArrayTraversal.
  2. Add the following method named power, create a main method, and have main call the power method. Also, be certain to import the Arrays class.
import java.util.Arrays;
public class ArrayTraversal {
  public static void power(double[] a){
    for(int i = 0; i < a.length; i++){
      a[i] = Math.pow(a[i], 2.0);
    }
    System.out.println(Arrays.toString(a));
  }
  public static void main(String[] args){
    double[] a = {1.0,2.2,3.4,4.44,5.22};
    ArrayTraversal.power(a);
  }
}
  1. Compile and run the program.
$ javac ArrayTraversal.java
$ java ArrayTraversal
[1.0, 4.840000000000001, 11.559999999999999, 19.713600000000003, 27.248399999999997]
  1. Now add a search method that takes an array of doubles and a number that the method should try to find in the array.
  2. Add two calls in main to search. Also, comment the call to power so it is no longer called in main.
public static void main(String[] args){
  double[] a = {1.0,2.2,3.4,4.44,5.22};
  //ArrayTraversal.power(a);
  System.out.println(ArrayTraversal.search(a,3.4));
  System.out.println(ArrayTraversal.search(a,33.33));
}
public static int search(double[] a, double target){
  for(int i = 0; i < a.length; i++){
    if(a[i]==target){
      return i;
    }
  }
}
  1. Compile and run the program.
$ javac ArrayTraversal.java
$ java ArrayTraversal
2
-1
  1. Add a method named sum and add a call to it in main.
public static double sum(double[] a){
  double total = 0.0;
  for(int i = 0; i < a.length;i++){
    total += a[i];
  }
  return total;
}
  1. Add a call to sum in main.
System.out.println(ArrayTraversal.sum(a));
  1. Compile and run the program.
$ javac ArrayTraversal.java
$ java ArrayTraversal
2
-1
16.259999999999998

The complete class should appear as follows.

import java.util.Arrays;
public class ArrayTraversal {
  public static void power(double[] a){
    for(int i = 0; i < a.length; i++){
      a[i] = Math.pow(a[i], 2.0);
    }
    System.out.println(Arrays.toString(a));
  }
  public static void main(String[] args){
    double[] a = {1.0,2.2,3.4,4.44,5.22};
    //ArrayTraversal.power(a);
    System.out.println(ArrayTraversal.search(a,3.4));
    System.out.println(ArrayTraversal.search(a,33.33));
    System.out.println(ArrayTraversal.sum(a));
  }
  public static int search(double[] a, double target){
    for(int i = 0; i < a.length; i++){
      if(a[i]==target){
        return i;
      }
    }
    return -1;
  }
  public static double sum(double[] a){
    double total = 0.0;
    for(int i = 0; i < a.length;i++){
      total += a[i];
    }
    return total;
  }
}