Как найти сумму чисел строки в матрице

Перейти к содержанию

Суммы строк и столбцов матрицы

Просмотров 10.7к. Обновлено 15 октября 2021

Посчитать суммы каждой строки и каждого столбца матрицы. Вывести суммы строк в конце каждой строки, а суммы столбцов под соответствующими столбцами.

Поскольку двумерный массив обычно перебирается построчно, то сумму строк считать проще. Можно, заполняя строку матрицы и выводя ее элементы на экран, накапливать в переменной сумму элементов строки и выводить ее в конце строки.

Для сумм столбцов можно предусмотреть отдельный массив, в ячейках которого накапливать сумму каждого столбца. При построчном проходе по матрице, каждый новый элемент следует суммировать с соответствующим ему элементом массива сумм столбцов. Индекс элемента в строке матрицы будет совпадать с индексом элемента в массиве сумм.

Выводить суммы столбцов следует в отдельном цикле.

Pascal


const
M = 10;
N = 5;
var
a: array[1..N,1..M] of integer;
i, j: byte;
s: integer;
sc: array[1..M] of integer;
begin
for i:= 1 to M do
sc[i] := 0;

for i:=1 to N do begin
s := 0;
for j:=1 to M do begin
a[i,j] := random(10);
write(a[i,j]:6);
s := s + a[i,j];
sc[j] := sc[j] + a[i,j]
end;
writeln (' |', s);
end;
for i:= 1 to M do
write('--':6);
writeln;
for i:= 1 to M do
write(sc[i]:6);
writeln;

end.



Пример выполнения программы:

5 5 7 8 6 8 5 8 4 6 |62
6 3 4 2 8 0 9 2 3 4 |41
7 8 5 4 5 3 9 8 0 3 |52
0 6 0 3 8 9 7 1 8 8 |50
9 4 7 8 4 5 7 6 1 7 |58
-- -- -- -- -- -- -- -- -- --
27 26 23 25 31 25 37 25 16 28

Язык Си

сумма элементов каждого столбца матрицы c++


#include < stdio.h>
#define M 10
#define N 5
main() {
int a[N][M];
int sc[M];
int s, i, j;
srand(time(NULL));
for (i=0; i< M; i++) sc[i] = 0;
for (i=0; i< N; i++) {
s = 0;
for (j=0; j< M; j++) {
a[i][j] = rand() % 10;
printf("%5d", a[i][j]);
s += a[i][j];
sc[j] += a[i][j];
}
printf(" |%dn", s);
}
for (i=0; i< M; i++)
printf("%5s", "--");
printf("n");
for (i=0; i< M; i++)
printf("%5d", sc[i]);
printf("n");
}

Python

сумма элементов строки матрицы python (питон)


from random import random
M = 10
N = 5
a = []
for i in range(N):
b = []
for j in range(M):
b.append(int(random()*11))
print("%3d" % b[j], end='')
a.append(b)
print(' |', sum(b))

for i in range(M):
print(" --", end='')
print()

for i in range(M):
s = 0
for j in range(N):
s += a[j][i]
print("%3d" % s, end='')
print()



Пример(ы) выполнения программы на языке Python:

6 7 3 10 10 10 4 2 6 5 | 63
2 8 0 9 0 4 9 3 6 3 | 44
5 3 1 10 5 6 5 2 0 9 | 46
10 9 10 8 7 8 5 2 10 9 | 78
3 3 6 0 4 1 6 10 10 3 | 46
-- -- -- -- -- -- -- -- -- --
26 30 20 37 26 29 29 19 32 29
В Python используется немного иной алгоритм решения задачи. Сначала создается пустой список - будущая матрица. Далее в цикле в нее добавляются вложенные списки.

Суммы строк матрицы вычисляются с помощью функции sum(), которой передается текущий список-строка цикла.

Суммы столбцов вычисляются путем прохода по каждому столбу матрицы. Обратите внимание, что здесь наоборот: внешний цикл - проход по столбцам, внутренний - по строкам.

КуМир


алг суммы строк столбцов
нач
цел M = 10, N = 5
цел таб a[1:N,1:M], sc[1:M]
цел i, j, s
нц для i от 1 до M
sc[i] := 0
кц

нц для i от 1 до N
s := 0
нц для j от 1 до M
a[i,j] := int(rand(0,10))
вывод a[i,j], " "
s := s + a[i,j]
sc[j] := sc[j] + a[i,j]
кц
вывод " |", s, нс
кц

нц для i от 1 до M
вывод "---"
кц
вывод нс
нц для i от 1 до M
вывод sc[i], " "
кц
кон

Basic-256


M = 10
N = 5
dim a(N,M)
dim sc(M)
for i = 0 to N-1
s = 0
for j=0 to M-1
a[i,j] = int(rand*10)
print a[i,j] + " ";
s = s + a[i,j]
sc[j] = sc[j] + a[i,j]
next j
print " |" + s
next i

for i=0 to M-1
print "-- ";
next i
print
for i=0 to M-1
print sc[i] + " ";
next i
print

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given a matrix of order m×n, the task is to find out the sum of each row and each column of a matrix.

    Examples: 

    Input: array[4][4] = { {1, 1, 1, 1}, 
                           {2, 2, 2, 2}, 
                           {3, 3, 3, 3}, 
                           {4, 4, 4, 4}};
    Output: Sum of the 0 row is = 4
            Sum of the 1 row is = 8
            Sum of the 2 row is = 12
            Sum of the 3 row is = 16
            Sum of the 0 column is = 10
            Sum of the 1 column is = 10
            Sum of the 2 column is = 10
            Sum of the 3 column is = 10

    Approach:  

    The sum of each row and each column can be calculated by traversing through the matrix and adding up the elements.

    Below is the implementation of the above approach:  

    C++

    #include <iostream>

    using namespace std;

    #define m 4

    #define n 4

    void row_sum(int arr[m][n])

    {

        int i,j,sum = 0;

        cout << "nFinding Sum of each row:nn";

        for (i = 0; i < m; ++i) {

            for (j = 0; j < n; ++j) {

                sum = sum + arr[i][j];

            }

            cout

                << "Sum of the row "

                << i << " = " << sum

                << endl;

            sum = 0;

        }

    }

    void column_sum(int arr[m][n])

    {

        int i,j,sum = 0;

        cout << "nFinding Sum of each column:nn";

        for (i = 0; i < m; ++i) {

            for (j = 0; j < n; ++j) {

                sum = sum + arr[j][i];

            }

            cout

                << "Sum of the column "

                << i << " = " << sum

                << endl;

            sum = 0;

        }

    }

    int main()

    {

        int i,j;

        int arr[m][n];

        int x = 1;

        for (i = 0; i < m; i++)

            for (j = 0; j < n; j++)

                arr[i][j] = x++;

        row_sum(arr);

        column_sum(arr);

        return 0;

    }

    Java

    import java.io.*;

    class GFG {

        static int m = 4;

        static int n = 4;

        static void row_sum(int arr[][])

        {

            int i, j, sum = 0;

            System.out.print("nFinding Sum of each row:nn");

            for (i = 0; i < m; ++i) {

                for (j = 0; j < n; ++j) {

                    sum = sum + arr[i][j];

                }

                System.out.println("Sum of the row " + i + " = "

                                   + sum);

                sum = 0;

            }

        }

        static void column_sum(int arr[][])

        {

            int i, j, sum = 0;

            System.out.print(

                "nFinding Sum of each column:nn");

            for (i = 0; i < m; ++i) {

                for (j = 0; j < n; ++j) {

                    sum = sum + arr[j][i];

                }

                System.out.println("Sum of the column " + i

                                   + " = " + sum);

                sum = 0;

            }

        }

        public static void main(String[] args)

        {

            int i, j;

            int[][] arr = new int[m][n];

            int x = 1;

            for (i = 0; i < m; i++)

                for (j = 0; j < n; j++)

                    arr[i][j] = x++;

            row_sum(arr);

            column_sum(arr);

        }

    }

    Python 3

    import numpy as np

    m , n = 4, 4       

    def row_sum(arr) :

        sum = 0

        print("nFinding Sum of each row:n")

        for i in range(m) :

            for j in range(n) :

                sum += arr[i][j]

            print("Sum of the row",i,"=",sum)

            sum = 0

    def column_sum(arr) :

        sum = 0

        print("nFinding Sum of each column:n")

        for i in range(m) :

            for j in range(n) :

                sum += arr[j][i]

            print("Sum of the column",i,"=",sum)

            sum = 0

    if __name__ == "__main__" :

        arr = np.zeros((4, 4))

        x = 1

        for i in range(m) :

            for j in range(n) :

                arr[i][j] = x

                x += 1

        row_sum(arr)

        column_sum(arr)

    C#

    using System;

    class GFG {

        static int m = 4;

        static int n = 4;

        static void row_sum(int[, ] arr)

        {

            int i, j, sum = 0;

            Console.Write("nFinding Sum of each row:nn");

            for (i = 0; i < m; ++i) {

                for (j = 0; j < n; ++j) {

                    sum = sum + arr[i, j];

                }

                Console.WriteLine("Sum of the row " + i + " = "

                                  + sum);

                sum = 0;

            }

        }

        static void column_sum(int[, ] arr)

        {

            int i, j, sum = 0;

            Console.Write("nFinding Sum of each"

                          + " column:nn");

            for (i = 0; i < m; ++i) {

                for (j = 0; j < n; ++j) {

                    sum = sum + arr[j, i];

                }

                Console.WriteLine("Sum of the column " + i

                                  + " = " + sum);

                sum = 0;

            }

        }

        public static void Main()

        {

            int i, j;

            int[, ] arr = new int[m, n];

            int x = 1;

            for (i = 0; i < m; i++)

                for (j = 0; j < n; j++)

                    arr[i, j] = x++;

            row_sum(arr);

            column_sum(arr);

        }

    }

    PHP

    <?php

    $m = 4;

    $n = 4;

    function row_sum(&$arr)

    {

        $sum = 0;

        echo "Finding Sum of each row:nn";

        for ($i = 0; $i < m; ++$i)

        {

            for ($j = 0; $j < n; ++$j)

            {

                $sum = $sum + $arr[$i][$j];

            }

            echo "Sum of the row " . $i .

                 " = " . $sum . "n";

            $sum = 0;

        }

    }

    function column_sum(&$arr)

    {

        $sum = 0;

        echo "nFinding Sum of each column:nn";

        for ($i = 0; $i < m; ++$i)

        {

            for ($j = 0; $j < n; ++$j)

            {

                $sum = $sum + $arr[$j][$i];

            }

            echo "Sum of the column " . $i .

                        " = " . $sum . "n";

            $sum = 0;

        }

    }

    $arr = array_fill(0, $m, array_fill(0, $n, NULL));

    $x = 1;

    for ($i = 0; $i < $m; $i++)

        for ($j = 0; $j < $n; $j++)

            $arr[$i][$j] = $x++;

    row_sum($arr);

    column_sum($arr);

    ?>

    Javascript

    <script>

    var m= 4;

    var n= 4;

    function row_sum( arr)

    {

        var i,j,sum = 0;

        document.write("<br>"+ "nFinding Sum of each row:"+"<br>");

        for (i = 0; i < m; ++i) {

            for (j = 0; j < n; ++j) {

                sum = sum + arr[i][j];

            }

            document.write( "Sum of the row "

                + i + " = " + sum

                +"<br>");

            sum = 0;

        }

    }

    function column_sum(arr)

    {

        var i,j,sum = 0;

        document.write( "<br>"+"Finding Sum of each column:"+"<br>");

        for (i = 0; i < m; ++i) {

            for (j = 0; j < n; ++j) {

                sum = sum + arr[j][i];

            }

            document.write( "Sum of the column "

                + i +" = " + sum

                +"<br>");

            sum = 0;

        }

    }

        var i,j;

        var arr=new Array(m).fill(0);

        for(var k=0;k<m;k++)

        {

            arr[k]=new Array(n).fill(0);

        }

        var x = 1;

        for (i = 0; i < m; i++)

            for (j = 0; j < n; j++)

                arr[i][j]=  x++;

        row_sum(arr);

        column_sum(arr);

    </script>

    Output

    Finding Sum of each row:
    
    Sum of the row 0 = 10
    Sum of the row 1 = 26
    Sum of the row 2 = 42
    Sum of the row 3 = 58
    
    Finding Sum of each column:
    
    Sum of the column 0 = 28
    Sum of the column 1 = 32
    Sum of the column 2 = 36
    Sum of the column 3 = 40
    

    Complexity Analysis:

    • Time Complexity: O(N*M), as we are using nested loops for traversing the matrix.
    • Auxiliary Space: O(1), as we are not using any extra space.

    Last Updated :
    06 Sep, 2022

    Like Article

    Save Article

    0 / 0 / 0

    Регистрация: 16.05.2011

    Сообщений: 22

    1

    Найти сумму элементов каждой строки (столбца) матрицы

    21.10.2011, 09:49. Показов 56372. Ответов 5


    Студворк — интернет-сервис помощи студентам

    Найти сумму элементов каждой строки (столбца) матрицы;



    0



    alex_bojik

    Заблокирован

    21.10.2011, 09:58

    2

    Лучший ответ Сообщение было отмечено Памирыч как решение

    Решение

    C#
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    int[,] a;
    int n=10;
    a = new int[n,n];
    int[] s=new int[n];
     
    //сумма по строке
    for (int i=0;i<n;i++)
        for(int j=0;j<n;j++)
                s[i]+=a[i,j];
                
    //сумма по столбцу
    for (int i=0;i<n;i++)
        for(int j=0;j<n;j++)
                s[i]+=a[j,i];



    0



    0 / 0 / 0

    Регистрация: 16.05.2011

    Сообщений: 22

    21.10.2011, 10:37

     [ТС]

    3

    А МОЖЕШЬ СДЕЛАТЬ ВЫВОДЫ



    0



    Эксперт .NET

    17203 / 12657 / 3321

    Регистрация: 17.09.2011

    Сообщений: 20,932

    21.10.2011, 12:10

    4

    Легко.
    Вывод: найти сумму по столбцам или строкам матрицы можно через вложенный цикл.



    3



    alex_bojik

    Заблокирован

    21.10.2011, 13:33

    5

    Лучший ответ Сообщение было отмечено Памирыч как решение

    Решение

    C#
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    int[,] a;
    int n=10;
    a = new int[n,n];
    int[] s=new int[n];
     
    //сумма по строке
    for (int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
            s[i]+=a[i,j];
        Console.Writeln(s[i]," ");
    }  
    //сумма по столбцу
    for (int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
            s[i]+=a[j,i];
        Console.Writeln(s[i]," ");
    }

    Добавлено через 1 минуту
    а.. нет… там или Write или Writeln но тогда без » »



    0



    ТимМерсер

    2 / 2 / 7

    Регистрация: 11.04.2017

    Сообщений: 19

    11.04.2017, 21:37

    6

    C#
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    
                int n, m, sum1=0, sum2=0;
                Console.WriteLine("Введите n-строк и m-столбцов!");
                Console.Write("n=");
                n = Convert.ToInt32(Console.ReadLine());
                Console.Write("m=");
                m = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine();
     
                int[,] k = new int[n, m];
                Random r = new Random();        //заполняем матрицу случайными числами 
     
                for (int i = 0; i < n; i++) 
                {
                    for (int j = 0; j < m; j++) 
                    {
                        k[i, j] = r.Next(-10, 10);    //каждый элемент принимает значение от -10 до +10
                        Console.Write("{0} ", k[i, j]);
                    }
                    Console.WriteLine();
                }
     
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < m; j++)
                    {
                        sum1 += k[i, j];       //находим сумму всех элементов строки
                    }
                    Console.WriteLine();
                    Console.WriteLine("Сумма " + (i+1) + " строки равна " + sum1);     //выводим сумму строки
                    sum1 = 0;    //обнуляем полученную сумму
                }
                Console.WriteLine();
     
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < m; j++)
                    {
                        sum2 += k[j, i];       //находим сумму всех элементов столбца
                    }
                    Console.WriteLine();
                    Console.WriteLine("Сумма " + (i + 1) + " столбца равна " + sum2);     //выводим сумму столбца
                    sum2 = 0;    //обнуляем полученную сумму
                }
     
                Console.ReadKey();



    2



    В общем есть программа. Ввожу количество строк и столбцов, рандомом заполняю таблицу(матрицу). Нажимаю «сумма», и в нулевых ячейках должна выводиться сумма каждой строки, но выходит ерунда…
    6290c68d7707460faeb4e18ceb8f3a55.png
    Подскажите в чем ошибка.
    Вот код процедуры:

    var
      i, j, countCols, countRows, result1: integer;
      result : array[1..100] of integer;
    begin
      countCols := StrToInt(Form1.Edit2.text);
      countRows := StrToInt(Form1.Edit1.text);
      Form1.Label3.Caption := IntToStr(countCols) + ' ' + IntToStr(countRows);
        for i := 1 to countRows do
        begin
          for j := 1 to countCols do
            begin
              result[i] := result[i] + StrToInt(StringGrid1.Cells[j, i]);
            end;
          StringGrid1.Cells[0, i] := IntToStr(result[i]);
        end;
    end;

    Решение:

    var
      i, j, countCols, countRows, sum: integer;
      sumArr: array[1..50] of integer;
    begin
    
      countCols := StrToInt(Form1.Edit2.text);
      countRows := StrToInt(Form1.Edit1.text);
      Form1.Label3.Caption := IntToStr(countCols) + ' ' + IntToStr(countRows);
        for i := 1 to countRows do
          begin
          sum := 0;
            for j := 1 to countCols do
              begin
                sum := sum + StrToInt(StringGrid1.Cells[j, i]);
              end;
            sumArr[i] := sum;
            StringGrid1.Cells[0, i] := IntToStr(sumArr[i]);
          end;
    
        for j := 1 to countCols do
          begin
          sum := 0;
            for i := 1 to countRows do
              begin
                sum := sum + StrToInt(StringGrid1.Cells[j, i]);
              end;
            sumArr[i] := sum;
            StringGrid1.Cells[j, 0] := IntToStr(sumArr[i]);
          end;
    end;

    Помогите пожалуйста, хоть с 0 написать, очень хочу чистого и простого логичного кода, отставьте комментарии по коду, буду очень благодарен !)

     Dim i, j
        Dim text, answer
        Dim m As Byte, n As Byte, sum As Integer
        Dim a() As Integer
        n = InputBox("N")
        m = InputBox("M")
        ReDim a(1 To n, 1 To m) As Integer
        For i = 1 To n
        sum = 0
        For j = 1 To m
        a(i, j) = Int((100) * Rnd - 50)
        sum = sum + a(i, j)
        text = text & a(i, j) & Space(3)
        Next j
        answer = answer & "Номер строки : " & i & "  Сумма:  " & sum & vbLf
        text = text & vbLf
        Next i
        MsgBox text
        MsgBox answer
    

    Понравилась статья? Поделить с друзьями:
  • Как найти местоположение по номеру программы
  • Как составить номер ту 2021 год
  • Порядковый номер 42 не найден в библиотеке dll c windows system32 xlive dll как исправить
  • Как найти наложение участков
  • Как составить заявление уполномоченному по правам человека