- 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.
CodePudding user response:
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);
CodePudding user response:
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).
CodePudding user response:
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.