Orlov Andrey Orlov Andrey - 6 days ago 7
Java Question

How to print the index of an array

I have method where I run an array.

public static void findPairs(double[] c) {

for (int i = 0; i < c.length; i++) {
if (c[i] * c[i + 1] >= c[i] + c[i + 1]) {
System.out.println();
}
}
}


The array value:

c[0]0.5
c[1]1.5
c[2]2.0
c[3]2.0
c[4]3.0
c[5]5.02


I need to print the indexes of the array which are suitable in
if
expression.
Is there some method and I don't know it?

For example:

(1,4) because 1.5*3.0 = 4.5 >= 4.5 = 1.5+3.0

(2,4) and (3,4) because 2.0*3.0 = 6.0 >= 5.0 2.0+3.0

etc.

Thanks

Answer

Replace

System.out.println();

with

System.out.println('(' + c[i] + ',' + c[i+1] + ')');

Oh and one more thing, since you are not trying to pair a number with itself, you only want to reach second-to-last element, which you will try to pair with the last element. So also replace

for (int i = 0; i < c.length; i++) {

with

for (int i = 0; i < c.length - 1; i++) {

But this still would not produce the result you want, i.e. (1,4) because you only try to pair n-th element with n+1-th element. You will need to use two loops, like this:

for (int i = 0; i < c.length - 1; i++) {
  for (int j = i; j < c.length; j++) {
    if (c[i] * c[j] >= c[i] + c[j]) {
       System.out.println('(' + c[i] + ',' + c[j] + ')');
    }
  }   
}