Java classic algorithm _ 026: Calculate the sum of a 3*3 matrix diagonal element

Source: Internet
Author: User
Package WZS. arithmetics; // question: Calculate the sum of the diagonal elements of a 3*3 matrix. Public class test_wzs26 {public static void main (string [] ARGs) {int array [] [] = {1, 2, 3}, {4, 5, 6}, {7, 8, 9}; system. out. println ("print matrix:"); For (INT I = 0; I <3; I ++) {for (Int J = 0; j <3; j ++) {system. out. print (array [I] [J] + "\ t");} system. out. println ();} system. out. println ("print the right corner element and sum. "); int sum = 0; For (INT I = 0; I <3; I ++) {for (Int J = 0; j <3; j ++) {if (I = J) {sum + = array [I] [J]; system. out. print (array [I] [J] + "\ t") ;}} system. out. println ("Corner element and:" + sum); int sum2 = 0; For (INT I = 0; I <3; I ++) {for (Int J = 0; j <3; j ++) {if (I + J = 2) {sum2 + = array [I] [J]; system. out. print (array [I] [J] + "\ t") ;}} system. out. println ("Corner element and:" + sum2 );}}

Output result:

Print matrix: 123456789 print the corner element and sum. 159 corner elements and: 15357 corner elements and: 15

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.