Page 359 - ComputerScience_Class_11
P. 359

The output of the preceding program is as follows:

                         BlueJ: Terminal Window - Java
                     Options

                    Enter a number: 4
                    Enter a number: 7
                    Enter a number: 2
                    Enter a number: 6
                    Enter a number: 3
                    Enter a number: 9
                    Enter a number: 8
                    Enter a number: 5
                    Enter a number: 10
                    Sum of Numbers: 24




                 Using Direct Input Method
                 In this method, the values to be inserted are taken in as parameters by the user.



                   Program 20    Write a Java program to create an array of size 4 × 4, take values using parameter and display
                                 the diagonals and also display the sum of numbers present in the diagonal position.

                   1       import java.util.Scanner;

                   2       public class DiagonalSum

                   3       {

                   4           public static void main(int[][] arr)

                   5           {

                   6               int mainDiagonalSum = 0;
                   7               int secondaryDiagonalSum = 0;

                   8               System.out.println("Main Diagonal:");

                   9               for (int i = 0; i < 4; i++)

                   10              {

                   11                  mainDiagonalSum += arr[i][i];

                   12              }

                   13              System.out.println("\nSum of Main Diagonal: " + mainDiagonalSum);

                   14              System.out.println("\nSecondary Diagonal:");

                   15              for (int i = 0; i < 4; i++)






                                                                                                           Arrays  357
   354   355   356   357   358   359   360   361   362   363   364