Home > Enterprise >  Why are several 0 in array when filling it with for loop
Why are several 0 in array when filling it with for loop

Time:11-27


import java.util.Arrays;
import java.util.Scanner;

public class Sieth {
    public static void main(String[] args) {
        Scanner bound = new Scanner(System.in);
        int n = bound.nextInt();

        int[] list = new int[n];

        for (int f = 2; f <= n - 1; f  ) {

            list[f] = f;
        }

        System.out.println(Arrays.toString(list));

    }
}

I want to fill my array from 2 to n. When I assign for example 20 to n, than the array will contain undesired several 0 and the last number in the array, which actually should be 20, is than 19, because of decrementing n by one, which otherwise will cause and exception. Why?

Example session with input and output:

20
[0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

CodePudding user response:

You are starting the loop from 2.

for (int f = 2; f <= n - 1; f  ) 

So the first entry in the loop is in list[2] = 2; and list[0] and list[1] is set as 0.

CodePudding user response:

I want to fill my array from 2 to n

Arrays are zero-indexed, so you can fill them to n - 1 index only. For example, if we have int[] arr = new int[3], then available indexes are:

arr[0], arr[1], arr[2]

and arr[3] would cause index out of bound exception.

the array will contain undesired several 0

Because default value for int is 0. If you are expecting to see null there, use Integer instead.

the last number in the array, which actually should be 20, is than 19

No, it's should be 19. Because f <= n - 1; -> 19 <= 20 - 1 is true, but 20 <= 20 - 1; is false and loop will be terminated.

  •  Tags:  
  • java
  • Related