Page 96 - CTS - CSA TP - Volume 2
P. 96

COMPUTER SOFTWARE APPLICATION - CITS





                   for (int i = 0; i < matrix.length; i++) {
                       for (int j = 0; j < matrix[i].length; j++) {
                           System.out.print(matrix[i][j] + “ “);
                       }

                       System.out.println(); // Move to the next line after printing each row
                   }
               }
           }



           Output:


















           Explanation:
              •  A two-dimensional array in Java is an array of arrays. It is a matrix-like structure with rows and columns.
              •  In the above program, a 2D array named matrix is declared and initialized with integer values.

              •  The declaration int[][] matrix indicates that matrix is a two-dimensional array of integers.
              •  The array initializer { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } initializes the 2D array with three rows and three
                 columns.

              •  The outer loop for (int i = 0; i < matrix.length; i++) iterates over the rows of the array, and the inner loop
                 for (int j = 0; j < matrix[i].length; j++) iterates over the columns of each row.
              •  Within the nested loops, matrix[i][j] is used to access each element of the 2D array.
              •  The program prints each element of the 2D array row-wise, with each row printed on a separate line.

           Two-dimensional arrays are commonly used to represent tabular data, matrices, grids, and other structured
           data in Java programs. They offer a convenient way to organize and manipulate data in rows and columns. In
           this example, the 2D array matrix represents a 3x3 matrix with integer values. The nested loops are used to
           iterate over each element of the array and perform operations as needed.


           TASK 2: Java program that allows the user to input two matrices through the keyboard and displays their
                    sum:
           import java.util.Scanner;

           public class MatrixSum {
               public static void main(String[] args) {
                   Scanner scanner = new Scanner(System.in);
                   // Prompt the user to enter the dimensions of the matrices





                                                           81
                                CITS : IT & ITES - Computer Software Application - Exercise 93
   91   92   93   94   95   96   97   98   99   100   101