Traverse an Array in Java - Iterating over Arrays in Java

 

Traverse an Array in Java - Iterating over Arrays in Java

Traversing through an array


Traversing of an array visiting of an 
array is accessing of each element of an array at least once for processing. The array is a linear data structure. Traversing of its elements is very simple and easy.

How do you traverse an array?

Array traversing is done for printing every element, calculating the total number of elements, or execution of any process on these elements

We can use a ‘for’ loop to traverse or visit each element of an array. We can start the index at 0 and loop while an index is less than the length of the array.


public class ArrayTraverseWithForLoop

{

    public static void main(String args[])

    {

        int i;

        int n[]={5,6,7,3,2,4,9,8,10,12}; //Array

        for(i=0; i<n.length; i++)

        {

            System.out.println("Position:"+ i +" " +n[i]);

        }

    }

}

In the above java array traversing program, the array ‘n’ contains elements. Using for loop, each element traverse once and print the elements.

Enhanced for(for-each) Loop to Iterate Java Array

public class ArrayTraverseWithForEachLoop

{

    public static void main(String args[])

    {

        int no[]={5,6,7,3,2,4,9,8,10,12};  // Array

       // for each loop

       for(int x : no)

        {

            System.out.println("Array element " + x) ;

        }

    }

}

Traversing ArrayList elements

import java.util.*; 

class TraverseArrayList

{ 

    public static void main(String args[])

    { 

        //Creating a list of elements 

        ArrayList<Integer> list=new ArrayList<Integer>(); 

        list.add (10); 

        list.add (20); 

        list.add (30);

        list.add (40);

        list.add (50);

        // Visiting each elements using for-each loop 

        for(int no : list){ 

            System.out.println(no); 

        } 

    }  

}

Output

10

20

30

40

50

In the above program, we defined an ArrayList list integer data elements with the add() method. After then we visit or traverse each element with the help of for each loop.

Traversing of an array using while loop in Java

In the following java program, we traverse array with the help of a while loop. In this program, the loop starts with x=0 and iterate till no.length-1 and x++ will do loop iteration.

public class TraverseArrayWithWhile

{

   public static void main(String args[])

    {

        int x=0;

        int no[]={5,6,7,3,2,4,9,8,10,12}; //Array

        // using while loop array traverse

        while(x!=no.length-1)

        {

            System.out.print(no[x] + " ");

            x++;

        }

    }

}


More Tutorial and Programs



SHARE THIS
Previous Post
Next Post