Task 7 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.2 Array algorithms — comparing neighbours

Lesson

Смотреть на пару соседей

Some questions are not about single elements but about pairs: is the array sorted? where does it jump? are there two equal values in a row? For these you look at arr[i] and arr[i + 1] together.


Где остановить цикл

for (int i = 0; i < arr.length - 1; i++) {   // note: length - 1
    System.out.println(arr[i] + " -> " + arr[i + 1]);
}

⚠️ The condition is i < arr.length - 1, not i < arr.length. On the last element there is no arr[i + 1], and reaching for it throws an ArrayIndexOutOfBoundsException.

Simple check: an array of 4 elements has 3 neighbouring pairs.


▶ Try it: run this, then change something and run it again.



When comparing arr[i] with arr[i + 1], the loop must stop at...


An array of 6 elements has how many neighbouring pairs?


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    int[] v = {2, 4, 6};
    for (int i = 0; i < v.length - 1; i++) {
        System.out.println(v[i + 1] - v[i]);
    }
}}

What happens with i < arr.length and arr[i + 1] inside?


True or false?