Results 1 to 3 of 3
- 01-19-2010, 10:11 PM #1
Member
- Join Date
- Jan 2010
- Posts
- 15
- Rep Power
- 0
Help explain the FOR lines please
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.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]);
}
}
}
}
}
This program basically checks for duplicates and prints them out.
Thanks a bunch!
- 01-19-2010, 10:46 PM #2
By running that code, you'll have a better understanding of how it works. This is the output from it:
The inner loop checks if the current element matches with any other element of the array.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
starts at the first element of the array.Java Code:for (i = 0; i < arr.length; i++){
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:for (j = i + 1; j < arr.length; j++){
this basically checks if there are multiple copies of an element.Java Code:if (arr[j] == arr[i]){ System.out.println("Index " + i + " same as index " + j + " with value " + arr[i]); }"Experience is what you get when you don't get what you want" (Dan Stanford)
"Rise and rise again until lambs become lions" (Robin Hood)
- 01-19-2010, 11:52 PM #3
Member
- Join Date
- Jan 2010
- Posts
- 15
- Rep Power
- 0
Similar Threads
-
Please explain these 2 lines of code to me..
By murphaph in forum New To JavaReplies: 10Last Post: 01-19-2010, 02:11 PM -
Can someone explain why...
By Krooger in forum AWT / SwingReplies: 1Last Post: 11-19-2009, 06:59 AM -
Please explain Java
By MarkWilson in forum New To JavaReplies: 7Last Post: 07-02-2008, 08:38 AM -
Need Help Can anyone explain what this means
By Clemenza1983 in forum New To JavaReplies: 6Last Post: 02-16-2008, 03:13 AM -
need to explain this code
By reached in forum New To JavaReplies: 3Last Post: 12-03-2007, 10:01 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks