To iterate through an array in Java using a while
loop, you can use the following approach:
int[] arr = {1, 2, 3, 4, 5}; int i = 0; while (i < arr.length) { System.out.println(arr[i]); i++; }
In this example, the while
loop continues to iterate as long as i
is less than the length of the arr
array. The value of i
is incremented by 1 at the end of each iteration.
Inside the loop, the element at the current index i
is accessed using the arr[i]
notation and printed to the console using the System.out.println()
method.
This approach allows you to iterate through the entire array, from the first element to the last. You can also use a while
loop to iterate through the array in reverse order, by starting at the last element and decrementing the value of i
at the end of each iteration.