'How to Iterate the array index in java?

  1. How can I iterate the array index?

for example

int []arr = new int [] {23, 85, 90, 34,15}
int []data = new int [] {45, 35, 65}
int count = 0;
for(arr[0] = 0; arr[0] < data[0]; arr[0]++, data[0]++){
     count++
     System.out.println(count);
}

what I want to do is after it checks arr[0] < data[0] it will go to next and check if

arr[1] < data[1] and after that it will check

arr[2] < data[2] and so on.

until it reaches the last index.



Solution 1:[1]

Here's an indexed for loop that makes sure "i" is within the bounds of both arrays:

int[] arr = new int[] {23, 85, 90, 34, 15};
int[] data = new int[] {45, 35, 65};
int count = 0;
for(int i=0; i<arr.length && i<data.length; i++) {
  if (arr[i]<data[i]) {
    count++;  
  }
}
System.out.println(count);

Solution 2:[2]

As i know, you can iterate 2 arrays at once easy if you have 2 arrays same sizes with for-loop:

int count = 0;
for(int i = 0; i < arr.length; i++){
 if(arr[i] < data[i]){
   count++
 }
 System.out.println(count);
}

Or you can define some logic (etc: iterate until last index of shorter array).

Solution 3:[3]

You are trying to compare arrays within for-loop syntax which won't traverse arrays.

(i.e for(arr[0] = 0; arr[0] < data[0]; arr[0]++, data[0]++)

Try this code.

int []arr = new int [] {23, 85, 90, 34,15}
int []data = new int [] {45, 35, 65}
int count = 0;
for(int i = 0; i < Math.min(data.length, arr.length); i++){
     if(arr[i]<data[i]){
         count++;
      }
}

System.out.println(count);

Make sure to import Math library.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Idle_Mind
Solution 2 Hoàng Nguy?n
Solution 3