-1

The usage of i - 1 concerns me the most. Should i use another variable for the indexing or is this fine?


public class MainClass {

    public static void main(String[] args) {
        int[] array = new int[5];

        for(int i = 1; i<=array.length; i++) {
            array[i-1] = i;
        }

        for(int x: array)
            System.out.println(x);
    }

}

Glamy
  • 1
  • 2

1 Answers1

-1

Technically, it doesn't matter. However, you may do

for (int i = 0; i < array.length;)
    array[i] = ++i;

to generate the same output:

1
2
3
4
5
Leon Willens
  • 356
  • 1
  • 16
  • @lucid Yes, that is one way of doing so, but you can simplify it by writing `int[] array = {1, 2, 3, 4, 5};` – Glamy May 13 '20 at 17:58
  • I just thought of a more flexible way, say if it wouldn't be about `1..5` but other enumerations, such as `5..99`. But yes, that is possible too – Leon Willens May 13 '20 at 18:08