CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Arrays

Arrays
Basic skills
Enhanced for loops

How to use enhanced for loops with arrays

  • Java 5.0 provides a new form of the for loop called an enhanced for loop.
  • The enhanced for loop is sometimes called a foreach loop because it lets you process each element of an array.
  • Within the parentheses of an enhanced for loop, you declare a variable with the same type as the array followed by a colon and the name of the array.
  • With each iteration of the loop, the variable that's declared by the for loop is assigned the value of the next element in the array.

The syntax of the enhanced for loop

for (type variableName : arrayName)
{
    statements
}

Code that prints an array of prices to the console

double[] prices = {14.95, 12.95, 11.95, 9.95};
for (double price : prices)
{
   System.out.println(price);
}

The console output

14.95
12.95
11.95
9.95

Code that computes the average of the array of prices

double sum = 0.0;
for (double price : prices)
{
   sum += price;
}
double average = sum/prices.length;
Previous | Create | Assign | for loops | Enhanced for loops | Next