Sum of Elements of Lower Triangular Matrix
Sum of Elements of Lower Triangular Matrix:
Program:
import java.util.Scanner;
public class LowerTriangularElementsSum {
public static void main(String[] args) {
int r, c;
Scanner s = new Scanner(System.in);
r = s.nextInt();
c = s.nextInt();
if(r!=c) {
System.exit(0);
}
int[][] matrix = new int[r][c];
for(int i = 0; i<r; i++) {
for(int j = 0; j<c;j++) {
matrix[i][j] = s.nextInt();
}
}
int sum = 0;
for(int i = 0; i<r; i++) {
for(int j = 0;j<c; j++) {
if(i>=j) {
System.out.print(matrix[i][j]);
System.out.print(" ");
sum+=matrix[i][j];
}
}
}
System.out.println("\nThe sum of Lower triangular elements of a matrix is: " + sum);
}
}
/* In other words, a square matrix is lower triangular if all its entries above the main diagonal are zero.
* Example of a 3 × 3 lower triangular matrix: Diagonal matrices are both upper
*and lower triangular since they have zeroes above and below the main diagonal
*/
Output:
3 3
1 2 3 4 5 6 7 8 9
1 4 5 7 8 9
The sum of Lower triangular elements of a matrix is: 34
Happy Coding 💻:-)
Comments
Post a Comment