1. Write a program to create store and display the value of 2 dimensional array with mXn martix.
import java.util.Scanner;
public class TwoDimensional {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows (m): ");
int m = scanner.nextInt();
System.out.print("Enter number of columns (n): ");
int n = scanner.nextInt();
int[][] matrix = new int[m][n];
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
System.out.println("\nThe matrix is:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
Output;
Enter number of rows (m): 2
Enter number of columns (n): 2
Enter the elements of the matrix:
12
13
14
15
The matrix is:
12 13
14 15
2. Write a program to create store and display the value of jagged array with each row has different
number of columns.
import java.util.Scanner;
public class TwoDimension1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
int[][] jaggedArray = new int[rows][];
for (int i = 0; i < rows; i++) {
System.out.print("Enter the number of columns for row " + (i + 1) + ": ");
int cols = scanner.nextInt();
jaggedArray[i] = new int[cols];
System.out.println("Enter elements for row " + (i + 1) + ": ");
for (int j = 0; j < cols; j++) {
System.out.print("Element at [" + i + "][" + j + "]: ");
jaggedArray[i][j] = scanner.nextInt();
System.out.println("\nThe jagged array is:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
System.out.println();
}
Output;
Enter the number of rows: 3
Enter the number of columns for row 1: 0
Enter elements for row 1:
Enter the number of columns for row 2: 2
Enter elements for row 2:
Element at [1][0]: 6
Element at [1][1]: 5
Enter the number of columns for row 3: 4
Enter elements for row 3:
Element at [2][0]: 3
Element at [2][1]: 5
Element at [2][2]: 8
Element at [2][3]: 7
The jagged array is:
65
3587