The Generalized for Loop

double[] data = . . .;

double sum = 0;

for (double e : data) // You should read this loop as "for each e in data"

{

  sum = sum + e;

}

double[] data = . . .;

double sum = 0;

for (int i = 0; i < data.length; i++)

{

     double e = data[i];

     sum = sum + e;

}

 

Click here for an example.

  ArrayList<BankAccount> accounts = . . . ;

  double sum = 0;

  for (BankAccount a : accounts)

  {

     sum = sum + a.getBalance();

  }

  double sum = 0;

  for (int i = 0; i < accounts.size(); i++)

  {

     BankAccount a = accounts.get(i);

     sum = sum + a.getBalance();

  }

Write a "for each" loop that prints all elements in the array data.

   Answer:    for (double x : data) System.out.println(x);
 

Why is the "for each" loop not an appropriate shortcut for the following ordinary for loop?

 
for (int i = 0; i < data.length; i++) data[i] = i * i;

   Answer: The loop writes a value into data[i]. The "for each" loop does not have the index variable i.