Write a program to input and store integer elements in a double dimensional array of size 3 x 3 and find the sum of elements in the left diagonal.
Topic: Sum of the left diagonal of a 3 x 3 array
Answer
import java.util.Scanner;
class LeftDiagonal { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int m[][] = new int[3][3]; int sum = 0;
System.out.println("Enter 9 elements of the 3 x 3 array :"); for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) m[i][j] = sc.nextInt();
System.out.println("The array is :"); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) System.out.print(m[i][j] + "\t"); System.out.println(); }
for(int i = 0; i < 3; i++) sum = sum + m[i][i];
System.out.println("Sum of the left diagonal = " + sum); } }
The whole question rests on recognising the index pattern of the left (principal) diagonal: the row number equals the column number. So the elements are m[0][0], m[1][1], m[2][2] — written simply as m[i][i].
That means a SINGLE loop suffices for the summing, not a nested one. Using nested loops with an if(i == j) inside also works and is accepted, but it makes nine tests where three additions would do.
Worth knowing the companion pattern for the right (secondary) diagonal: row plus column equals n - 1, so the elements are m[i][n-1-i]. Questions often ask for both.
Displaying the array before the answer is not demanded but costs two lines and makes the output readable — examiners look kindly on it.
Check with 1 to 9 filled row by row: the diagonal is 1, 5, 9 and the sum is 15.
m[][] int[3][3] - stores the nine elements entered by the user sum int - running total of the left diagonal elements i, j int - loop variables for rows and columns sc Scanner - object used to read input