Bird
Raised Fist0
Javaprogramming~5 mins

Array traversal in Java

Choose your learning style10 modes available
Introduction

Array traversal means looking at each item in an array one by one. It helps us check or use every element inside the array.

When you want to print all items in a list of names.
When you need to find the biggest number in a list of scores.
When you want to add up all values in a list of prices.
When you want to check if a certain value exists in a list.
When you want to change or update each item in a list.
Syntax
Java
public class ArrayTraversal {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        for (int index = 0; index < numbers.length; index++) {
            int currentElement = numbers[index];
            // Use currentElement here
        }
    }
}

The for loop starts at index 0 because arrays in Java start at 0.

numbers.length gives the total number of elements in the array.

Examples
This shows what happens if the array is empty. The loop does not run at all.
Java
int[] emptyArray = {};
for (int index = 0; index < emptyArray.length; index++) {
    System.out.println(emptyArray[index]);
}
This shows traversal when there is only one element in the array.
Java
int[] singleElementArray = {99};
for (int index = 0; index < singleElementArray.length; index++) {
    System.out.println(singleElementArray[index]);
}
This example shows how to identify the first, last, and middle elements during traversal.
Java
int[] numbers = {5, 10, 15, 20};
for (int index = 0; index < numbers.length; index++) {
    if (index == 0) {
        System.out.println("First element: " + numbers[index]);
    } else if (index == numbers.length - 1) {
        System.out.println("Last element: " + numbers[index]);
    } else {
        System.out.println("Middle element: " + numbers[index]);
    }
}
Sample Program

This program shows how to look at each score in an array, print it, add 5 points to each, and then print the updated scores.

Java
public class ArrayTraversal {
    public static void main(String[] args) {
        int[] scores = {85, 90, 78, 92, 88};
        System.out.println("Scores before traversal:");
        for (int index = 0; index < scores.length; index++) {
            System.out.println("Score at index " + index + ": " + scores[index]);
        }
        System.out.println("\nAdding 5 bonus points to each score...");
        for (int index = 0; index < scores.length; index++) {
            scores[index] = scores[index] + 5;
        }
        System.out.println("\nScores after adding bonus points:");
        for (int index = 0; index < scores.length; index++) {
            System.out.println("Score at index " + index + ": " + scores[index]);
        }
    }
}
OutputSuccess
Important Notes

Time complexity is O(n) because we visit each element once.

Space complexity is O(1) since we only use a few extra variables.

A common mistake is going beyond the last index by using <= instead of < in the loop condition.

Use array traversal when you need to process or check every element. For searching a single item, consider stopping early.

Summary

Array traversal means visiting each element one by one using a loop.

Start from index 0 and go up to length - 1.

It helps to read, update, or check all items in the array.

Practice

(1/5)
1. What does array traversal mean in Java?
int[] arr = {1, 2, 3};
easy
A. Creating a new array with the same elements
B. Visiting each element of the array one by one using a loop
C. Sorting the array elements in ascending order
D. Deleting elements from the array

Solution

  1. Step 1: Understand array traversal meaning

    Array traversal means going through each element in the array one by one.
  2. Step 2: Match with given options

    Only Visiting each element of the array one by one using a loop describes visiting each element using a loop, which is traversal.
  3. Final Answer:

    Visiting each element of the array one by one using a loop -> Option B
  4. Quick Check:

    Array traversal = visiting elements one by one [OK]
Hint: Traversal means visiting all elements step-by-step [OK]
Common Mistakes:
  • Confusing traversal with sorting
  • Thinking traversal means deleting elements
  • Mixing traversal with creating new arrays
2. Which of the following is the correct syntax to traverse an array int[] nums in Java?
easy
A. for(int i = 0; i < nums.length; i++) { System.out.println(nums[i]); }
B. for(int i = 1; i <= nums.length; i++) { System.out.println(nums[i]); }
C. for(int i = 0; i <= nums.length; i++) { System.out.println(nums[i]); }
D. for(int i = 0; i < nums.length - 1; i++) { System.out.println(nums[i]); }

Solution

  1. Step 1: Check loop start and end conditions

    The loop should start at 0 and run while i is less than nums.length to cover all indices.
  2. Step 2: Validate array access inside loop

    Accessing nums[i] is correct if i is within 0 to length-1. for(int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } satisfies this.
  3. Final Answer:

    for(int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } -> Option A
  4. Quick Check:

    Loop from 0 to length-1 = correct traversal [OK]
Hint: Loop from 0 to less than length for full traversal [OK]
Common Mistakes:
  • Starting loop at 1 instead of 0
  • Using <= length causing index out of bounds
  • Stopping loop early at length - 1
3. What will be the output of the following code?
int[] arr = {5, 10, 15};
for(int i = 0; i < arr.length; i++) {
  System.out.print(arr[i] + " ");
}
medium
A. 5 10 15
B. 15 10 5
C. 5 10 15 0
D. Error: ArrayIndexOutOfBoundsException

Solution

  1. Step 1: Understand the loop iteration

    The loop runs from i=0 to i=2 (arr.length=3), printing arr[i] each time.
  2. Step 2: Check printed values

    Values printed are arr[0]=5, arr[1]=10, arr[2]=15, each followed by a space.
  3. Final Answer:

    5 10 15 -> Option A
  4. Quick Check:

    Print elements in order = 5 10 15 [OK]
Hint: Prints elements in order from index 0 to length-1 [OK]
Common Mistakes:
  • Assuming reverse order output
  • Expecting extra zero at end
  • Thinking loop causes index error
4. Identify the error in this array traversal code:
int[] data = {2, 4, 6};
for(int i = 0; i <= data.length; i++) {
  System.out.println(data[i]);
}
medium
A. System.out.println should be outside the loop
B. Array declaration is incorrect
C. Loop condition should be i < data.length, not <= data.length
D. No error, code runs fine

Solution

  1. Step 1: Analyze loop condition

    The loop runs while i <= data.length, which means i can be equal to data.length (3).
  2. Step 2: Check array index access

    Accessing data[3] causes ArrayIndexOutOfBoundsException because valid indices are 0 to 2.
  3. Final Answer:

    Loop condition should be i < data.length, not <= data.length -> Option C
  4. Quick Check:

    Index must be less than length to avoid error [OK]
Hint: Use i < length, not i <= length in loops [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Ignoring array index limits
  • Thinking loop runs without error
5. Given an array int[] nums = {3, 6, 9, 12, 15};, write code to print only the even numbers by traversing the array.
hard
A. for(int i = 0; i < nums.length - 1; i++) { System.out.print(nums[i] + " "); }
B. for(int i = 1; i <= nums.length; i++) { if(nums[i] % 2 == 0) System.out.print(nums[i] + " "); }
C. for(int i = 0; i < nums.length; i++) { if(nums[i] % 2 != 0) System.out.print(nums[i] + " "); }
D. for(int i = 0; i < nums.length; i++) { if(nums[i] % 2 == 0) System.out.print(nums[i] + " "); }

Solution

  1. Step 1: Traverse the array correctly

    Loop from i=0 to i < nums.length to visit all elements safely.
  2. Step 2: Check condition for even numbers

    Use nums[i] % 2 == 0 to find even numbers and print them.
  3. Final Answer:

    for(int i = 0; i < nums.length; i++) { if(nums[i] % 2 == 0) System.out.print(nums[i] + " "); } -> Option D
  4. Quick Check:

    Traverse all and print only even numbers [OK]
Hint: Check nums[i] % 2 == 0 inside loop to print evens [OK]
Common Mistakes:
  • Using wrong loop bounds causing errors
  • Printing odd numbers instead of even
  • Missing condition inside loop
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard