编程知识 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 .

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={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、a、a
}
else if((i+j)==2)
{
sum=sum+a[i][j];// such as a、a
}

The final result and code are as follows ： Of course , You have to write the simplest ：int sum=a+a+a+a+a; 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 .

https://cdmana.com/2020/12/20201225085210300C.html

Scroll to Top