extra element being added in my int array by my for loop, I don't understand why

Viewed 53

so I'm doing a small exercise called 'array of multiples', where I am multiplying a number and displaying all the multiples of the number until the answer is reached by an array.

for example: arrayOfMultiples(7, 5) ➞ [7, 14, 21, 28, 35].

My issue is that I have an additional element being added to my array with a value of 0, and I do not understand why. I've tried to understand why but I need help!

this is my code:

public static void main(String[] args) {
    //invoke method
    int[] test = arrayOfMultiples(7, 6);
    //convert array to string to print entire thing
    System.out.println(Arrays.toString(test));
}

public static int[] arrayOfMultiples(int num, int length) {
    //array is initalised with original number
    int [] array = new int [num];
    //variable to keep num the same
    int add = num;
    // loop for adding the new multiples to the array
    for (int i = 0; i < length; i++) {
        array[i] = num;
        num += add;
    }
    return array;
}

my output is: [7, 14, 21, 28, 35, 42, 0]

thank you!

2 Answers

Your issue is that for the initialization of the array you used the num variable instead of length to specify the size of the array and since int is a premitive data type it cannot be null, rather it has a default value of 0. Try this:

public static void main(String[] args) {
    //invoke method
    int[] test = arrayOfMultiples(7, 6);
    //convert array to string to print entire thing
    System.out.println(Arrays.toString(test));
}

public static int[] arrayOfMultiples(int num, int length) {
    //array is initalised with original number
    int [] array = new int [length];
    //variable to keep num the same
    int add = num;
    // loop for adding the new multiples to the array
    for (int i = 0; i < length; i++) {
        array[i] = num;
        num += add;
    }
    return array;
}

The problem is that you are making the size of the array as the number for which you have to find the multiples. You need to make the size equal to int length. Just imagine if num = 1000 and length = 10 i.e. you want to find 10 multiples of 1000. The way you have done is, you will get an array with 990 elements as 0 which is the default value assigned at each index in an int [].

Replace

int [] array = new int [num];

with

int [] array = new int [length];
Related