KnowledgeBoat Logo

Computer Applications

Write a program that inputs a 2D array and displays how the array elements will look in row major form and column major form.

Java

Java Arrays

9 Likes

Answer

import java.util.Scanner;

public class KboatDDARowColMajor
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter number of rows: ");
        int rows = in.nextInt();
        System.out.print("Enter number of columns: ");
        int cols = in.nextInt();
        int arr[][] = new int[rows][cols];
        
        System.out.println("Enter the 2D array:");
        for (int i = 0; i < rows; i++) {
            System.out.println("Enter elements of row " + (i + 1));
            for (int j = 0; j < cols; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        System.out.println("Input array :");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
        
        System.out.println("Array in row major form:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(arr[i][j] + " ");
            }
        }
        
        System.out.println();
        
        System.out.println("Array in column major form:");
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                System.out.print(arr[j][i] + " ");
            }
        }

    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program that inputs a 2D array and displays how the array elements will look in row major form and column major form.

Answered By

1 Like


Related Questions