Q:

Print 2D array with a single for loop

How to print a 2d array in java using a single for-loop?
I tried to search answers but only found solutions using multiple loops.
Example array:
[
    [1, 2, 3],
    [4, 5],
    [6, 7, 8],
    [9]
]

Example output (the exact format does not matter):
1, 2, 3, 4, 5, 6, 7, 8, 9

With a single for-loop, not a nested loop.

So not something like this:
for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
        System.out.print(array[i][j] + " ");
    }
}

A:

If you need to know any algorithm for using only one loop you may try to use some like this:
public static void main(String[] args) {
    int[][] arr = {{1, 2}, {3 ,4}};
    int currSubArrayNum = 0;
    for (int i = 0; currSubArrayNum < arr.length; i++) {
        System.out.println(arr[currSubArrayNum][i]);
        if (i == arr[currSubArrayNum].length - 1) {
            currSubArrayNum++;
            i = -1;
        }
    }
}

Output will be next:

1
  2
  3
  4

But if you need some simple solution for use in your program just use Arrays.toString:
public static void main(String[] args) {
    int[][] arr = {{1, 2}, {3 ,4}};
    for (int[] anArr : arr) {
        System.out.println(Arrays.toString(anArr));
    }
}

With output:

[1, 2]
[3, 4]

