1. Member
Join Date
Jan 2010
Posts
15
Rep Power
0

## Help explain the FOR lines please

int[] arr = {1, 2, 2, 3, 4, 2, 4, 3, 0, 5, 3, 2};

int i, j;

for (i = 0; i < arr.length; i++){
for (j = i + 1; j < arr.length; j++){
if (arr[j] == arr[i]){
System.out.println("Index " + i + " same as index " + j + " with value " + arr[i]);
}

}
}
}
}
Hey everyone Im quite new to java and when it comes to arrays and complex sequences like this i get sooo lost. Please explain the steps of each of the FOR and IF line.

This program basically checks for duplicates and prints them out.

Thanks a bunch!

2. By running that code, you'll have a better understanding of how it works. This is the output from it:

Java Code:
```Index 1 same as index 2 with value 2
Index 1 same as index 5 with value 2
Index 1 same as index 11 with value 2
Index 2 same as index 5 with value 2
Index 2 same as index 11 with value 2
Index 3 same as index 7 with value 3
Index 3 same as index 10 with value 3
Index 4 same as index 6 with value 4
Index 5 same as index 11 with value 2
Index 7 same as index 10 with value 3```
The inner loop checks if the current element matches with any other element of the array.

Java Code:
`for (i = 0; i < arr.length; i++){`
starts at the first element of the array.

Java Code:
`     for (j = i + 1; j < arr.length; j++){`
starts at the 2nd element in the array. This loop finishes once it reaches the end of the array. Then the outer loop starts. Finally, flow control reaches this loop for the 2nd time, but this time, it starts at the 3rd element. (i equals 1; thus, 1+1=2, which is the third element (0 = first element; 1 = second element; 2 = third element) The inner loop (the one w/ j = i + 1) will loop until the last element of the array is reached. Once again, the outer loop starts again. Flow control is given to the inner loop, which starts at the 4th element.

Java Code:
```     if (arr[j] == arr[i]){
System.out.println("Index " + i + " same as index " + j + " with value " + arr[i]);
}```
this basically checks if there are multiple copies of an element.

3. Member
Join Date
Jan 2010
Posts
15
Rep Power
0

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•