Setting the counter (j) for (inner for loop)

34 views Asked by At

enter image description hereCan anyone tell me why we should set the counter j in the inner for loop to (i+1) not (i=0) (beacause I think setting j to i = 0 will get all elements in the array). And why we using break; I am new in programming. Thanks in advance.

Here I check for the duplicates and if I set (j = i+1) the first element in the array will be skipped (with the index 0) from the comparison isn't it ?

2

There are 2 answers

0
getrithekd On

So when checking for duplicates in an array (that's what I think the algorithm is for; correct me if I'm wrong), you want to check each element against each other element once. Let's have a 2D array of all possible pairs of elements you can check.

For an array with 4 elements, the 2D array would look like this:

[(0,0),(0,1),(0,2),(0,3),
 (1,0),(1,1),(1,2),(1,3),
 (2,0),(2,1),(2,2),(2,3),
 (3,0),(3,1),(3,2),(3,3)]

We can traverse this 2D array like you said.

double[] array = new double[] {1,2,3,4}
for (int i=0;i<array.length;i++){
  for (int j=0;j<array.length;j++){
    if(array[i]==array[j]){
      break;
    }
  }
  
}

However, this checks both (1,0) and (0,1) which is redundant. All we have to do is check the elements above and including the diagonal from the top left to the bottom right. This makes it so that we have to set j to i+1.

1
Naz On

Please provide the source code next time. But I want to answer on why we use break in general.

  • The break statement is used to exit a loop prematurely if a certain condition is met.
  • In this context, once we find a duplicate element, there's no need to continue searching for more duplicates.
  • By using break, we exit the inner loop as soon as we find the first duplicate, saving time and unnecessary iterations.