编程知识 cdmana.com

Exercise 3 in Chapter 6 of C language programming: the sum of diagonal elements

subject :

Ask for one 3x3 The sum of diagonal elements of the shaping matrix .

answer :

Let's take a look first 3x3 What are the characteristics of the index of the diagonal of the matrix elements of .

The diagonal to :

then , We set i and j As rows and columns :

We take all the elements of this two-dimensional array as two loops , The outer layer is i, The inner layer is j:

// First, define some variables , such as sum Used to accumulate sums 
int sum=0;
// Let me define one more 3x3 The shape array of 
int a[3][3]={1,2,3,4,5,6,7,8,9};

for(int i=0;i<3;i++)

{

    for(int j=0;j<3;j++)

        {

            // Summation code 

        }

}

And then according to the logic in the figure above , The sum code is :

if(i==j)
{
  sum=sum+a[i][j];// such as a[0][0]、a[1][1]、a[2][2]
}
else if((i+j)==2)
{
  sum=sum+a[i][j];// such as a[0][2]、a[2][0]
}

The final result and code are as follows :

Of course , You have to write the simplest :int sum=a[0][0]+a[0][2]+a[1][1]+a[2][0]+a[2][2]; It can be , But in this way, if the matrix is added, it will be very difficult to deal with . It can't reflect the ability of personal thinking .

版权声明
本文为[Liu Rihui]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225085210300C.html

Scroll to Top