Arrays
Basic skills
for loops
How to use for loops with arrays
- You can use the length field of an array to determine how many elements are defined for the array.
- For loops are often used to process each element in an array.
The syntax for getting the length of an array
arrayName.length
Code that puts the numbers 0 through 9 in an array
int[] values = new int[10]; for (int i = 0; i < values.length; i++) { values[i] = i; }
Code that prints an array of prices to the console
double[] prices = {14.95, 12.95, 11.95, 9.95}; for (int i = 0; i < prices.length; i++) { System.out.println(prices[i]); }
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 (int i = 0; i < prices.length; i++) { sum += prices[i]; } double average = sum/prices.length;
Another way to compute the average in a for loop
double sum = 0.0; for (int i = 0; i < prices.length; sum += prices[i++]); average = sum/prices.length;