Array traversal means looking at each item in an array one by one. It helps us check or use every element inside the array.
Array traversal in Java
public class ArrayTraversal { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for (int index = 0; index < numbers.length; index++) { int currentElement = numbers[index]; // Use currentElement here } } }
The for loop starts at index 0 because arrays in Java start at 0.
numbers.length gives the total number of elements in the array.
int[] emptyArray = {}; for (int index = 0; index < emptyArray.length; index++) { System.out.println(emptyArray[index]); }
int[] singleElementArray = {99}; for (int index = 0; index < singleElementArray.length; index++) { System.out.println(singleElementArray[index]); }
int[] numbers = {5, 10, 15, 20}; for (int index = 0; index < numbers.length; index++) { if (index == 0) { System.out.println("First element: " + numbers[index]); } else if (index == numbers.length - 1) { System.out.println("Last element: " + numbers[index]); } else { System.out.println("Middle element: " + numbers[index]); } }
This program shows how to look at each score in an array, print it, add 5 points to each, and then print the updated scores.
public class ArrayTraversal { public static void main(String[] args) { int[] scores = {85, 90, 78, 92, 88}; System.out.println("Scores before traversal:"); for (int index = 0; index < scores.length; index++) { System.out.println("Score at index " + index + ": " + scores[index]); } System.out.println("\nAdding 5 bonus points to each score..."); for (int index = 0; index < scores.length; index++) { scores[index] = scores[index] + 5; } System.out.println("\nScores after adding bonus points:"); for (int index = 0; index < scores.length; index++) { System.out.println("Score at index " + index + ": " + scores[index]); } } }
Time complexity is O(n) because we visit each element once.
Space complexity is O(1) since we only use a few extra variables.
A common mistake is going beyond the last index by using <= instead of < in the loop condition.
Use array traversal when you need to process or check every element. For searching a single item, consider stopping early.
Array traversal means visiting each element one by one using a loop.
Start from index 0 and go up to length - 1.
It helps to read, update, or check all items in the array.
