Page 522 - Cs_withBlue_J_C11_Flipbook
P. 522

Define a class sumofdiagonals and print the sum of diagonals of a matrix. The data members
                Program 13
                               and member methods are defined as follows:
                                Data Members
                                int n                          :  to store the size of the array
                                int a[][]                      :  to store the array
                                Member Methods
                                void printDiagonalSums()       :  to print the sum of the diagonals
                               Write the main method to call the methods and run the program.

                 1       import java.util.*;
                 2       class sumofdiagonals {

                 3           void printDiagonalSums()
                 4           {

                 5               int sum=0;
                 6               int pd = 0, sd = 0;

                 7               Scanner sc=new Scanner(System.in);
                 8               System.out.println("enter the size of the matrix");

                 9               int n=sc.nextInt();
                10               int a[][]=new int[n][n];//declaration of the array

                11               System.out.println("enter the matrix elements");
                12               for(int i=0;i<n;i++)

                13               {
                14                   for(int j=0;j<n;j++)

                15                   {
                16                       a[i][j]=sc.nextInt();

                17                   }
                18               }

                19               for (int i=0;i<n;i++)
                20               {

                21                   for (int j=0;j<n;j++)
                22                   {
                23                       // Condition for principal diagonal

                24                       if (i == j)

                25                           pd=pd+a[i][j];
                26                       // Condition for secondary diagonal
                27                       if ((i + j) == (n - 1))

                28                           sd=sd+a[i][j];




                520520  Touchpad Computer Science-XI
   517   518   519   520   521   522   523   524   525   526   527