Assignment 13 24 - 11-23

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Blue Ridge Public School

Class X – Computer Applications

A.Y. 2023-24

ASSIGNMENT – 13

1. Write a program to input and store integer elements in a double


dimensional array of size 3 x 3 array and print the array. Also, find
the sum of the elements in the left diagonal as well as the right
diagonal and display the same.

import java.util.*;
public class ArrDiagonalSum
{
int [][] arr = new int[3][3];
public void input2DArray()
{
Scanner sc = new Scanner (System.in);
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print("Enter element " + i + ","
+ j + ": ");
arr[i][j] = sc.nextInt();
}
}
} //input method ends
public void print2DArray()
{
//print elements of the array in a matrix form
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}//end of for loop
} //print method ends

public void sumDiagonals()


{
int ldiagsum = 0, rdiagsum = 0;
for(int row = 0; row < 3; row++)
{
for(int col = 0; col < 3; col++)
{
//compute sum of left diagonal elements
if(row == col)
ldiagsum += arr[row][col];
//compute sum of right diagonal elements
if(row + col == 3-1)
rdiagsum += arr[row][col];
}
}
System.out.println("Sum of the left diagonal
elements is " + ldiagsum );
System.out.println("Sum of the right diagonal
elements is " + rdiagsum );

} //diagonal sum method ends

public static void main(String [] args)


{
ArrDiagonalSum obj = new ArrDiagonalSum();
obj.input2DArray();
obj.print2DArray();
obj.sumDiagonals();

} //main method ends


} //program ends

OUTPUT

Enter element 0,0:


1
Enter element 0,1:
3
Enter element 0,2:
5
Enter element 1,0:
4
Enter element 1,1:
6
Enter element 1,2:
8
Enter element 2,0:
9
Enter element 2,1:
2
Enter element 2,2:
4
1 3 5
4 6 8
9 2 4
Sum of the left diagonal elements is: 11
Sum of the right diagonal elements is: 20
Variable Name Data type Description

i, j, row, col, ldiagsum, int stores integer values


rdiagsum

arr int [] stores an integer array

You might also like