sandy1603 sandy1603 - 1 month ago 6
Java Question

0,s are appending to my arrays in java programm

if i print my array long pair[] , 0's are appending in empty slots what is wrong any help is welcome Thank You

for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
diff = arr[j] - arr[i];
if (ndiff == diff) {
pair[x] = arr[i];
x++;
pair[x] = arr[j];
x++;
}
}
}

for(i=0;i!=pair.length;i++){
System.out.print(pair[i]+" ");
}

Answer

If you want to print only the values you put in pair, your for loop should run only up to the element with index x-1:

for(i=0; i < x; i++){
    System.out.print(pair[i]+" ");
}
Comments