Traversing-tutorial
In Java, traversing an array means accessing each element of the array one by one. This is a common operation when working with arrays, especially when you want to display, process, or analyze all the values.
Key Point
- Array traversal uses a loop to access elements from index 0 to length-1.
- Commonly used loop types: for, while, or for-each.
- It is a fundamental step in most array-based algorithms.
Example: Traverse an Array
package QuipoHouse.ArrayOperations;
public class Traversing {
public static void main(String[] args) {
// Array declaration and initialization int arr[] = { 1, 25, 15, 16, 18, 19, 147 };
// Traversing array using for loop for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } }}
Output:
1 25 15 16 18 19 147
Explanation
Line | Description |
---|---|
int arr[ ] = {. . . }; | Declares and initializes an integer array |
arr.length | Returns the numbers of elements in the array |
for (int i = 0; i < arr.length; i++); | Iterates through each index ( from 0 to 6 in this case ) |
System.out.print(arr[i]) | Prints each element of the array |
Use Cases of Array Traversing
- Displaying all array elements
- Performing operations like sum, max, min
- Searching and filtering data