Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading