Traversing an array or list means visiting some or all of the elements and doing something with each element visited.

The examples assume familiarity with for loops. Some examples also feature enhanced for loops.

The examples below are also available as Traversals in the AP CSP pseudocode language.

Sum of all elements in array

public static int getSum(int[] nums)
{
    int sum = 0;
    
    for(int i = 0; i < nums.length; i++)
    {
        sum = sum + nums[i];
    }
    
    return sum;
}

The variable i represents an index in the array nums. The for loop sets the value of i to each valid index in nums (0, 1, up to but not including nums.length).

The loop body runs once per valid index. nums[i] accesses the element at index i. The element is added to sum.

The method computes and returns the sum of the elements in nums.

Sum using an enhanced for loop

public static int getSum(int[] nums)
{
    int sum = 0;
    
    for(int n : nums)
    {
        sum = sum + n;
    }
    
    return sum;
}

As in the first example, this code computes the sum of all elements in nums. The code uses an enhanced for loop to visit each element in nums without using an index.

Each time the loop runs, n is set to a copy of the value of an element in nums. The value of n is added to sum.

Average of range in list

public static double getAverageInRange(
        ArrayList<Double> nums,
        int start, int end)
{
    double sum = 0;
    int count = 0;
    
    for(int i = start; i <= end; i++)
    {
        sum += nums.get(i);
        count++;
    }
    
    return sum / count;
}

As in the previous examples, the variable i represents the index of an element. The for loop sets i to each value in the range start up to and include end, one at a time.

nums.get(i) returns the element at index i in nums. Java uses different syntax for list access than for array access.

count represents the number of elements visited. This could alternatively be calculated from the values of start and end.

Count Evans

public static int countEvans(String[] names)
{
    int evans = 0;
    
    for(String n : names)
    {
        if(n.equals("Evan"))
            evans++;
    }
    
    return evans;
}

The method counts and returns the number of times the string "Evan" appears in the array names.

String objects in Java should be compared using the equals method. See Strings on the AP CS A Exam.

Filter evens

public static ArrayList<Integer> filterEvens(ArrayList<Integer> nums)
{
    ArrayList<Integer> evens = new ArrayList<Integer>();
    
    for(Integer n : nums)
    {
        if(n % 2 == 0)
            evens.add(n);
    }
    
    return evens;
}

The method returns a new ArrayList containing all and only the even values in nums.

The body of an enhanced for loop cannot structurally modify (add to or remove from) the list being looped through (in this case nums). Structurally modifying a different list (in this case evens) is fine.

Filter palindromes

public static boolean isPalindrome(String str)
{
    if(str.length() <= 1)
        return true;
    
    return str.substring(0, 1).equals(str.substring(str.length() - 1)) &&
            isPalindrome(str.substring(1, str.length() - 1));
}

public static ArrayList<String> getPalindromes(String[] words)
{
    ArrayList<String> palindromes = new ArrayList<String>();
    
    for(String w : words)
    {
        if(isPalindrome(w))
            palindromes.add(w);
    }
    
    return palindromes;
}

The getPalindromes method returns an ArrayList containing the elements from the array words that are palindromes.

getPalindromes passes each element from words to the isPalindrome method to determine if the element is a palindrome.

The isPalindrome method is implemented using recursion, which is beyond the scope of most introductory programming courses. See Writing recursive methods. Calling a method and using the return value does not require understanding how the method works internally. This is an example of abstraction.

Make zero above threshold

public static void makeZero(ArrayList<Integer> nums, int threshold)
{
    for(int i = 0; i < nums.size(); i++)
    {
        if(nums.get(i) > threshold)
        {
            nums.set(i, 0);
        }
    }
}

The method replaces each value in nums that exceeds threshold with 0.

Additional resources

Many Standard algorithms traverse arrays or lists. Some standard algorithms are simple, while others are considerably more complex.

See ArrayList practice for examples of code that adds elements to, or removes elements from, a list.

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Traversing arrays and lists