Compare each Pair of Elements in Array Without Repetition

We want to go over each pair of elements in array A A once.

1
2
3
4
for (let i = 0; i < A.length - 1; i++) {
  // inner loop
  ...
}

What is the correct expression for the inner loop?

for (j = i + 1; j < arr.length; j++) for (j = i; j < arr.length; j++) for (j = 0; j < arr.length; j++) for (j = i; j <= arr.length; j++)

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

I have objections to all of the answers. The first objection that it should not be arr; but, A. The second objection is that it should be ++j and not j++. Yes, modern compilers optimize away the unnecessary save of the original value of j. Yes, the example of a for loop on page 57 of the first edition of The C Programming Language by K&R shows a preincrement. As Dr. Kernighan worked short distance away from me at Bell Labs, I asked him about the use of a preincrement in this case and he said it was a mistake not caught in proofreading.

Keshav Garg
Dec 2, 2018

for (let i = 0; i < A.length - 1; i++) {

#means we are starting with A[0] upto A[A.lenght-1]

for(j=i+1;j< arr.length;j++){

#means we are starting the inner loop with A[i+1] upto A[A.lenght] ,whatever i is in the main loop ,our j will be one more than that

#which means the element with index i will have a pair with element with index i+1 which truly meets the required condition of not having the same pair twice

# 0,1 0,2 0,3 0,4 ....

#1,2 1,3 1,4.......

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...