Skip to main content

Command Palette

Search for a command to run...

code in java

Updated
1 min readView as Markdown
public class AlternateMatrixPrint {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 16}
        };

        printMatrixInAlternateOrder(matrix);
    }

    public static void printMatrixInAlternateOrder(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;

        for (int i = 0; i < rows; i++) {
            if (i % 2 == 0) {
                // Print row left-to-right
                for (int j = 0; j < cols; j++) {
                    System.out.print(matrix[i][j] + " ");
                }
            } else {
                // Print row right-to-left
                for (int j = cols - 1; j >= 0; j--) {
                    System.out.print(matrix[i][j] + " ");
                }
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}

More from this blog

Amit singh's blog

235 posts