Home > Java > javaTutorial > 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
Release: 2023-05-05 10:10:06
forward
2760 people have browsed it

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);
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template