Why does for write 0 to the array?

Why does for write 0 to the array? I understand that he counts indexes, but how do I make him write numbers?

    int n = 2;
    int x = 3;

    int mult = n*x;

    int[] array1 = new int[]{};

    for (int i = 0; i < mult; i++) {
        System.out.println(i);

        array1 = new int[i];
        System.out.println(Arrays.toString(array1));

    }

I need to create an array of numbers equal to the multiplication of two numbers. Example: 2 * 3 = 6 ==> {1, 2, 3, 4, 5, 6}. But i get{0, 0, 0, 0, 0, 0}

>Solution :

For the actual multiplication of the number with iterator above answer is correct, however I believe this is what you’re looking for from example given.

Also fits your demands which are actually to fill array with natural numbers starting with 1 up to multiplication result of the two given numbers: 2 * 3 = 6 ==> {1, 2, 3, 4, 5, 6}

If you declare arrays using curly brackets, this will create and fill the array with numbers given inside {}, if nothing is passed here your array will be made with 0-zeros.

As mentioned above, keep in mind what happens inside loop and what outside of it.

int n = 2;
int x = 3;

int mult = n*x;

int[] array1 = new int[mult];

for (int i = 0; i < mult; i++) {
    array1[i]= i+1; //population of array inside loop
}
System.out.println(Arrays.toString(array1)); //array printing outside

Leave a Reply