πΆββοΈ What is Array Traversal?
Array traversal means accessing each element of the array one by one, usually to:
Display elements
Perform calculations (sum, max, etc.)
Search for a specific value
π Using for Loop
int[] arr = {10, 20, 30, 40, 50};
for(int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " + arr[i]);
}Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50π Using while Loop
int[] arr = {1, 2, 3, 4, 5};
int i = 0;
while(i < arr.length) {
System.out.println(arr[i]);
i++;
}1
2
3
4
5π Using do-while Loop
int[] arr = {5, 10, 15};
int i = 0;
do {
System.out.println(arr[i]);
i++;
} while(i < arr.length);5
10
15π§Ύ Using for-each Loop (Enhanced For Loop)
This is the most concise and readable way to traverse arrays when index isn't needed.
int[] arr = {7, 14, 21, 28};
for(int num : arr) {
System.out.println(num);
}7
14
21
28π Note: for-each cannot be used if you need the index or to modify specific elements.
π§ When to Use What?
Loop Type | Use Case |
|---|---|
| When you need index or modifying |
| When you use external conditions |
| When loop must run at least once |
| For read-only access |