Traversing Arrays
Most array work is "do something with every element": add up a bill, find the highest score, count the free seats. Visiting each element in turn is called traversing the array. You have two loops for it, the counting for and the for-each, and each is better at different jobs.
Two Ways to Walk Through
public class Bill {
public static void main(String[] args) {
int[] prices = {340, 165, 190, 45};
int total = 0;
for (int price : prices) {
total += price;
}
System.out.println("Total: Rs. " + total);
}
}public class BillIndex {
public static void main(String[] args) {
int[] prices = {340, 165, 190, 45};
int total = 0;
for (int i = 0; i < prices.length; i++) {
total += prices[i];
}
System.out.println("Total: Rs. " + total);
}
}Total: Rs. 740Both add up all four prices. The for-each version has no index to get wrong; the counting version knows where it is in the array.
Finding the Largest, and Where It Is
public class TopScore {
public static void main(String[] args) {
String[] names = {"Navika", "Srihitha", "Advitha"};
int[] scores = {82, 95, 88};
int best = 0;
for (int i = 1; i < scores.length; i++) {
if (scores[i] > scores[best]) {
best = i;
}
}
System.out.println("Top: " + names[best] + " with " + scores[best]);
}
}Top: Srihitha with 95How it works
bestholds the index of the best score so far, starting with index 0.- The loop starts at 1 and compares each score with the best so far.
- Because we keep the index, we can print the matching name from the second array.
This needs a counting for: for-each would give the score, but not its position.
Try it yourself: change it to find the lowest score instead.
Backwards, and Every Other Element
public class Order {
public static void main(String[] args) {
int[] stops = {1, 2, 3, 4, 5, 6};
for (int i = stops.length - 1; i >= 0; i--) {
System.out.print(stops[i] + " ");
}
System.out.println();
for (int i = 0; i < stops.length; i += 2) {
System.out.print(stops[i] + " ");
}
System.out.println();
}
}6 5 4 3 2 1
1 3 5Only a counting loop can start at the end (length - 1) or jump in steps of 2.
Common Mistakes
Starting best at 0 for a "largest value" search when values can be negative. Start from the first element instead, as TopScore does with its index.
Using i <= length. It goes one past the end and throws ArrayIndexOutOfBoundsException.
Changing elements through a for-each variable. It's a copy; the array doesn't change.
Practice
- Easy: Count how many marks in
{45, 82, 17, 93, 60, 34}are below 35. - Harder: Find the second-highest value in an array in a single loop, keeping two variables:
highestandsecond.
Key Takeaways
Was this tutorial helpful?