Traverse an Array:
Traversing an array means to visit every element of an array one by one. We will traverse array elements one by one from their index number. As index of an array always starts from 0. So,we will start loop from 0.
Steps:
- Firstly we will declare and initialize the array.
- Start the loop from index 0 and it should be till size of array -1.( Here we have taken n as array length so it should be n-1).
- Then print the array. Index of array is specified by i.
CODE:
public class Traverse_array {
public static void main(String[] args) {
int[] arr ={1,2,3,4,5,8};
int n = arr.length;
System.out.println("Traversed Array is: ");
for(int i=0; i<n; i++)
{
System.out.println("Element at arr["+i+"] is: "+arr[i]);
}
}
}
public static void main(String[] args) {
int[] arr ={1,2,3,4,5,8};
int n = arr.length;
System.out.println("Traversed Array is: ");
for(int i=0; i<n; i++)
{
System.out.println("Element at arr["+i+"] is: "+arr[i]);
}
}
}
OUTPUT:
Traversed Array is:
Element at arr[0] is: 1
Element at arr[1] is: 2
Element at arr[2] is: 3
Element at arr[3] is: 4
Element at arr[4] is: 5
Element at arr[5] is: 8
Process finished with exit code 0