Home  >  Article  >  Java  >  How to find the sum of the diagonal elements of a 3*3 matrix in Java

How to find the sum of the diagonal elements of a 3*3 matrix in Java

WBOY
WBOYforward
2023-05-05 10:10:062716browse

Find the sum of the diagonal elements of a 3*3 matrix

This is a matrix programming implementation question. Matrices in Java are generally implemented through two-dimensional arrays.

The specific code is as follows:

import java.util.Random;

/**
 * 求一个3*3矩阵对角线元素之和
 *
 * @author ChenZX
 *
 */
public class Test04 {

    public static void main(String[] args) {
        int sum = 0; //和
        int[][] arr = new int[3][3];
        Random r = new Random();
        for(int i=0;i<3;i++){    //随机生成矩阵
            for(int j=0;j<3;j++){
                arr[i][j] = r.nextInt(10);  //0到9
            }
        }
        for(int i=0;i<3;i++){      //遍历矩阵
            for(int j=0;j<3;j++){
                System.out.print(arr[i][j]+" ");   //打印矩阵元素
                if(i==j){   //如果为对角线元素
                    sum += arr[i][j];  //求和
                }
            }
            System.out.println(); //每输出3个元素换行
        }
        System.out.println("此矩阵对角线的和为:"+sum);
    }
}

The above is the detailed content of How to find the sum of the diagonal elements of a 3*3 matrix in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete