Hello. There is such a problem:

Given a square matrix of order N. In the matrix, calculate the arithmetic average of positive elements on the main diagonal.

I thought about it, and decided to do so ... Set an array, then calculate the positive elements. Then move them to a new array and calculate the amount of gender. elements standing on the main diagonal ...

How can I transfer the positive elements to a new array? Need to create a new variable or is there another way?

Thank you in advance!

    3 answers 3

    It is not necessary to start a new array. You only need to know the number of positive elements and their sum.

    You can simply "run through" the diagonal of the matrix, adding the positive elements into one variable, and their number into another.


    Ie the solution of the problem in Russian can be written as:

    Для каждого элемента массива, стоящего на главное диагонали: Если элемент > 0, То: В сумму прибавить этот элемент, увеличить число положительных элементов на 1 Результат работы = Сумма / Количество 

    Now it remains only to arrange this all as a program.

    • Thanks for the advice. But somehow I don’t have much idea how to write it in C ("run" diagonally across the matrix). : (Ie, if I have 9 elements, then I need to have a variable, in general, something of this ?: a = i [1] + i [5] + i [9]; - Timi
    • @Tim Let i, j be horizontal and vertical indices. Then, if a 3x3 matrix is ​​written, for example, as an int matrix[3 * 3]; , then you can refer to its elements like this: matrix[j * 3 + i] . If we draw simple analogies, this means that we are a matrix (square) of size 3x3 = 9 , “straightened” into a line of 9 elements. - Costantino Rupert
    • @Tim Ie, roughly speaking, we have all the lines of the original matrix become one after another into one big line of length 9. Now it remains only how the indices of the elements of the main diagonal are arranged and use the formula matrix[j * 3 + i] . - Costantino Rupert
    • Thank you for your help, I will decide) - Timi

    Why a new array? Why all this?

     int a[N][N], b=0, c=0; for(int i=0; i<N; i++) { if(a[i][i]>=0) { b=a[i][i]+b; c++; } } cout<<b/c<<endl; 

      For a one-dimensional array like this:

       type array[N*N], sum=0; int count=0; for(int i=0; i<N*N; i+=N+1) { if(array[i]<=0) continue; sum+=array[i]; count++; } cout << sum/count << endl; 

      The intermediate array is not needed. Instead of type, type int, float or whatever type your matrix has.