# Help explain the FOR lines please

• 01-19-2010, 11:11 PM
hydride
Help explain the FOR lines please
Quote:

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!
• 01-19-2010, 11:46 PM
Lil_Aziz1
By running that code, you'll have a better understanding of how it works. This is the output from it:

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.

Code:

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

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.

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.
• 01-20-2010, 12:52 AM
hydride
Thanks a bunch!:)