Creating multiple variables "name + i" in a for loop (JAVA)

JustLearnin :

Hey is there a way to create multiple variables in a for loop? Here is an example of what i "want" my code to look like

for(int i=0; i<10; i++) {
    int[] arr(i) = new int[i+1];
    for(int j=0; j<=i; j++) {
        arr(i)[j] = j+1;
    } //for
} //for

I want to create 10 arrays like this:

arr0: [1]
arr1: [1, 2]
arr2: [1, 2, 3]
arr3: etc
...
Arvind Kumar Avinash :

You can do it using a 2-D array as shown below:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] arr = new int[10][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[i + 1];
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = j + 1;
            }
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.println("arr" + i + ": " + Arrays.toString(arr[i]));
        }
    }
}

Output:

arr0: [1]
arr1: [1, 2]
arr2: [1, 2, 3]
arr3: [1, 2, 3, 4]
arr4: [1, 2, 3, 4, 5]
arr5: [1, 2, 3, 4, 5, 6]
arr6: [1, 2, 3, 4, 5, 6, 7]
arr7: [1, 2, 3, 4, 5, 6, 7, 8]
arr8: [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr9: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415621&siteId=1