Open In App

Program to find the Sum of each Row and each Column of a Matrix

Last Updated : 06 Sep, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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++




// C++ program to find the sum
// of each row and column of a matrix
 
#include <iostream>
using namespace std;
 
// Get the size m and n
#define m 4
#define n 4
 
// Function to calculate sum of each row
void row_sum(int arr[m][n])
{
 
    int i,j,sum = 0;
 
    cout << "\nFinding Sum of each row:\n\n";
 
    // finding the row sum
    for (i = 0; i < m; ++i) {
        for (j = 0; j < n; ++j) {
 
            // Add the element
            sum = sum + arr[i][j];
        }
 
        // Print the row sum
        cout
            << "Sum of the row "
            << i << " = " << sum
            << endl;
 
        // Reset the sum
        sum = 0;
    }
}
 
// Function to calculate sum of each column
void column_sum(int arr[m][n])
{
 
    int i,j,sum = 0;
 
    cout << "\nFinding Sum of each column:\n\n";
 
    // finding the column sum
    for (i = 0; i < m; ++i) {
        for (j = 0; j < n; ++j) {
 
            // Add the element
            sum = sum + arr[j][i];
        }
 
        // Print the column sum
        cout
            << "Sum of the column "
            << i << " = " << sum
            << endl;
 
        // Reset the sum
        sum = 0;
    }
}
 
// Driver code
int main()
{
 
    int i,j;
    int arr[m][n];
 
    // Get the matrix elements
    int x = 1;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            arr[i][j] = x++;
 
    // Get each row sum
    row_sum(arr);
 
    // Get each column sum
    column_sum(arr);
 
    return 0;
}


Java




// Java program to find the sum
// of each row and column of a matrix
 
import java.io.*;
 
class GFG {
 
    // Get the size m and n
    static int m = 4;
    static int n = 4;
 
    // Function to calculate sum of each row
    static void row_sum(int arr[][])
    {
 
        int i, j, sum = 0;
 
        System.out.print("\nFinding Sum of each row:\n\n");
 
        // finding the row sum
        for (i = 0; i < m; ++i) {
            for (j = 0; j < n; ++j) {
 
                // Add the element
                sum = sum + arr[i][j];
            }
 
            // Print the row sum
            System.out.println("Sum of the row " + i + " = "
                               + sum);
 
            // Reset the sum
            sum = 0;
        }
    }
 
    // Function to calculate sum of each column
    static void column_sum(int arr[][])
    {
 
        int i, j, sum = 0;
 
        System.out.print(
            "\nFinding Sum of each column:\n\n");
 
        // finding the column sum
        for (i = 0; i < m; ++i) {
            for (j = 0; j < n; ++j) {
 
                // Add the element
                sum = sum + arr[j][i];
            }
 
            // Print the column sum
            System.out.println("Sum of the column " + i
                               + " = " + sum);
 
            // Reset the sum
            sum = 0;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int i, j;
        int[][] arr = new int[m][n];
 
        // Get the matrix elements
        int x = 1;
        for (i = 0; i < m; i++)
            for (j = 0; j < n; j++)
                arr[i][j] = x++;
 
        // Get each row sum
        row_sum(arr);
 
        // Get each column sum
        column_sum(arr);
    }
}
// This code is contributed by inder_verma..


Python 3




# Python3 program to find the sum
# of each row and column of a matrix
 
# import numpy library as np alias
import numpy as np
 
# Get the size m and n
m , n = 4, 4       
 
# Function to calculate sum of each row
def row_sum(arr) :
 
    sum = 0
 
    print("\nFinding Sum of each row:\n")
 
    # finding the row sum
    for i in range(m) :
        for j in range(n) :
 
            # Add the element
            sum += arr[i][j]
 
        # Print the row sum
        print("Sum of the row",i,"=",sum)
 
        # Reset the sum
        sum = 0
 
 
# Function to calculate sum of each column
def column_sum(arr) :
 
    sum = 0
 
    print("\nFinding Sum of each column:\n")
 
    # finding the column sum
    for i in range(m) :
        for j in range(n) :
 
            # Add the element
            sum += arr[j][i]
 
        # Print the column sum
        print("Sum of the column",i,"=",sum)
 
        # Reset the sum
        sum = 0
 
         
 
# Driver code    
if __name__ == "__main__" :
 
    arr = np.zeros((4, 4))
 
    # Get the matrix elements
    x = 1
     
    for i in range(m) :
        for j in range(n) :
            arr[i][j] = x
 
            x += 1
                 
    # Get each row sum
    row_sum(arr)
 
    # Get each column sum
    column_sum(arr)
 
# This code is contributed by
# ANKITRAI1


C#




// C# program to find the sum
// of each row and column of a matrix
using System;
 
class GFG {
 
    // Get the size m and n
    static int m = 4;
    static int n = 4;
 
    // Function to calculate sum of each row
    static void row_sum(int[, ] arr)
    {
 
        int i, j, sum = 0;
 
        Console.Write("\nFinding Sum of each row:\n\n");
 
        // finding the row sum
        for (i = 0; i < m; ++i) {
            for (j = 0; j < n; ++j) {
 
                // Add the element
                sum = sum + arr[i, j];
            }
 
            // Print the row sum
            Console.WriteLine("Sum of the row " + i + " = "
                              + sum);
 
            // Reset the sum
            sum = 0;
        }
    }
 
    // Function to calculate sum
    // of each column
    static void column_sum(int[, ] arr)
    {
 
        int i, j, sum = 0;
 
        Console.Write("\nFinding Sum of each"
                      + " column:\n\n");
 
        // finding the column sum
        for (i = 0; i < m; ++i) {
            for (j = 0; j < n; ++j) {
 
                // Add the element
                sum = sum + arr[j, i];
            }
 
            // Print the column sum
            Console.WriteLine("Sum of the column " + i
                              + " = " + sum);
 
            // Reset the sum
            sum = 0;
        }
    }
 
    // Driver code
    public static void Main()
    {
        int i, j;
        int[, ] arr = new int[m, n];
 
        // Get the matrix elements
        int x = 1;
        for (i = 0; i < m; i++)
            for (j = 0; j < n; j++)
                arr[i, j] = x++;
 
        // Get each row sum
        row_sum(arr);
 
        // Get each column sum
        column_sum(arr);
    }
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


PHP




<?php
// PHP program to find the sum
// of each row and column of a matrix
 
// Get the size m and n
$m = 4;
$n = 4;
 
// Function to calculate sum of each row
function row_sum(&$arr)
{
    $sum = 0;
 
    echo "Finding Sum of each row:\n\n";
 
    // finding the row sum
    for ($i = 0; $i < m; ++$i)
    {
        for ($j = 0; $j < n; ++$j)
        {
 
            // Add the element
            $sum = $sum + $arr[$i][$j];
        }
 
        // Print the row sum
        echo "Sum of the row " . $i .
             " = " . $sum . "\n";
             
        // Reset the sum
        $sum = 0;
    }
}
 
// Function to calculate sum of each column
function column_sum(&$arr)
{
    $sum = 0;
 
    echo "\nFinding Sum of each column:\n\n";
 
    // finding the column sum
    for ($i = 0; $i < m; ++$i)
    {
        for ($j = 0; $j < n; ++$j)
        {
 
            // Add the element
            $sum = $sum + $arr[$j][$i];
        }
 
        // Print the column sum
        echo "Sum of the column " . $i .
                    " = " . $sum . "\n";
         
        // Reset the sum
        $sum = 0;
    }
}
 
// Driver code
$arr = array_fill(0, $m, array_fill(0, $n, NULL));
 
// Get the matrix elements
$x = 1;
for ($i = 0; $i < $m; $i++)
    for ($j = 0; $j < $n; $j++)
        $arr[$i][$j] = $x++;
 
// Get each row sum
row_sum($arr);
 
// Get each column sum
column_sum($arr);
 
// This code is contributed by ita_c
?>


Javascript




<script>
// Get the size m and n
var m= 4;
var n= 4;
 
// Function to calculate sum of each row
function row_sum( arr)
{
 
    var i,j,sum = 0;
 
    document.write("<br>"+ "\nFinding Sum of each row:"+"<br>");
 
    // finding the row sum
    for (i = 0; i < m; ++i) {
        for (j = 0; j < n; ++j) {
 
            // Add the element
            sum = sum + arr[i][j];
        }
 
        // Print the row sum
        document.write( "Sum of the row "
            + i + " = " + sum
            +"<br>");
 
        // Reset the sum
        sum = 0;
    }
}
 
// Function to calculate sum of each column
function column_sum(arr)
{
 
    var i,j,sum = 0;
 
    document.write( "<br>"+"Finding Sum of each column:"+"<br>");
 
    // finding the column sum
    for (i = 0; i < m; ++i) {
        for (j = 0; j < n; ++j) {
 
            // Add the element
            sum = sum + arr[j][i];
        }
 
        // Print the column sum
        document.write( "Sum of the column "
            + i +" = " + sum
            +"<br>");
 
        // Reset the sum
        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);
    }
 
    // Get the matrix elements
    var x = 1;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            arr[i][j]=  x++;
 
    // Get each row sum
    row_sum(arr);
//document.write(arr[0][0]);
    // Get each column sum
    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.


Next Article
Generate a matrix with each row and column of given sum

Similar Reads

Find row and column pair in given Matrix with equal row and column sum
Given a matrix Mat of size N x M, the task is to find all the pairs of rows and columns where the sum of elements in the row is equal to the sum of elements in the columns. Examples: Input: M = {{1, 2, 2}, {1, 5, 6}, {3, 8, 9}}Output: {{1, 1}}Explanation: The sum of elements of rows and columns of matrix M are: C = 1C = 2C = 3Sum of RowsR = 11225R
8 min read
Sum of Matrix where each element is sum of row and column number
Given two numbers M and N denoting the number of rows and columns of a matrix A[] where A[i][j] is the sum of i and j (indices follow 1 based indexing), the task is to find the sum of elements of the matrix. Examples: Input: M = 3, N = 3Output: 36Explanation: A[]: {{2, 3, 4}, {3, 4, 5}, {4, 5, 6}}. Sum of matrix: 36. Input: M = 3, N = 4Output: 54Ex
14 min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Minimum element of each row and each column in a matrix
Given a matrix, the task is to find the minimum element of each row and each column. Examples: Input: [1, 2, 3] [1, 4, 9] [76, 34, 21] Output: Minimum element of each row is {1, 1, 21} Minimum element of each column is {1, 2, 3} Input: [1, 2, 3, 21] [12, 1, 65, 9] [11, 56, 34, 2] Output: Minimum element of each row is {1, 1, 2} Minimum element of e
11 min read
Maximum sum of a Matrix where each value is from a unique row and column
Given a matrix of size N X N, the task is to find maximum sum of this Matrix where each value picked is from a unique column for every row.Examples: Input: matrix = [[3, 4, 4, 4], [1, 3, 4, 4], [3, 2, 3, 4], [4, 4, 4, 4]] Output: 16 Explanation: Selecting (0, 1) from row 1 = 4 Selecting (1, 2) from row 2 = 4 Selecting (2, 3) from row 3 = 4 Selectin
8 min read
Construct a Binary Matrix whose sum of each row and column is a Prime Number
Given an integer N, the task is to construct a binary matrix of size N * N such that the sum of each row and each column of the matrix is a prime number. Examples: Input: N = 2 Output: 1 1 1 1 Explanation: Sum of 0th row = 1 + 1 = 2 (Prime number) Sum of 1st row = 1 + 1 = 2 (Prime number) Sum of 0th column = 1 + 1 = 2 (Prime number) Sum of 1st colu
6 min read
Generate a matrix with each row and column of given sum
Given two arrays row[] and col[] of size N and M respectively, the task is to construct a matrix of dimensions N 脳 M such that the sum of matrix elements in every ith row is row[i] and the sum of matrix elements in every jth column is col[j]. Examples: Input: row[] = {5, 7, 10}, col[] = {8, 6, 8}Output: {{0, 5, 0}, {6, 1, 0}, {2, 0, 8}}Explanation:
7 min read
Sum of matrix in which each element is absolute difference of its row and column numbers
Given a positive integer n. Consider a matrix of n rows and n columns, in which each element contain absolute difference of its row number and numbers. The task is to calculate sum of each element of the matrix. Examples : Input : n = 2 Output : 2 Matrix formed with n = 2 with given constraint: 0 1 1 0 Sum of matrix = 2. Input : n = 3 Output : 8 Ma
13 min read
Sum of matrix element where each elements is integer division of row and column
Consider a N X N matrix where each element is divided by a column number (integer division), i.e. mat[i][j] = floor((i+1)/(j+1)) where 0 &lt;= i &lt; n and 0 &lt;= j &lt; n. The task is to find the sum of all matrix elements. Examples : Input : N = 2 Output : 4 2 X 2 matrix with given constraint: 1 0 2 1 Sum of matrix element: 4 Input : N = 3 Outpu
9 min read
Construct a square matrix such that the sum of each row and column is odd
Given an integer N. Then your task is to output a square matrix of length N using the numbers from the range [1, N2] such that the sum of each row and column is odd. Note: If there are multiple solution, then print any of them. Examples: Input: N = 2 Output: {{1, 2}, {4, 3}} Explanation: Let us calculate the sum of each row and col: First row: R1 i
12 min read
Article Tags :
  • DSA
  • Matrix
  • School Programming
Practice Tags :
  • Matrix
three90RightbarBannerImg

PHP网站源码石岩SEO按效果付费西乡网站设计东莞阿里店铺运营坂田推广网站坂田网站推广系统石岩网站搭建丹竹头设计网站坪山百度seo大浪网站设计福永网站排名优化宝安模板网站建设东莞设计网站南联网站关键词优化布吉标王坪地外贸网站设计木棉湾网站推广系统宝安百度关键词包年推广深圳网站制作设计民治网站改版宝安外贸网站建设吉祥关键词排名包年推广松岗百搜词包观澜网络广告推广平湖推广网站永湖企业网站改版丹竹头网站关键词优化观澜网站建设设计大运设计网站荷坳网站推广平湖设计公司网站歼20紧急升空逼退外机英媒称团队夜以继日筹划王妃复出草木蔓发 春山在望成都发生巨响 当地回应60岁老人炒菠菜未焯水致肾病恶化男子涉嫌走私被判11年却一天牢没坐劳斯莱斯右转逼停直行车网传落水者说“没让你救”系谣言广东通报13岁男孩性侵女童不予立案贵州小伙回应在美国卖三蹦子火了淀粉肠小王子日销售额涨超10倍有个姐真把千机伞做出来了近3万元金手镯仅含足金十克呼北高速交通事故已致14人死亡杨洋拄拐现身医院国产伟哥去年销售近13亿男子给前妻转账 现任妻子起诉要回新基金只募集到26元还是员工自购男孩疑遭霸凌 家长讨说法被踢出群充个话费竟沦为间接洗钱工具新的一天从800个哈欠开始单亲妈妈陷入热恋 14岁儿子报警#春分立蛋大挑战#中国投资客涌入日本东京买房两大学生合买彩票中奖一人不认账新加坡主帅:唯一目标击败中国队月嫂回应掌掴婴儿是在赶虫子19岁小伙救下5人后溺亡 多方发声清明节放假3天调休1天张家界的山上“长”满了韩国人?开封王婆为何火了主播靠辱骂母亲走红被批捕封号代拍被何赛飞拿着魔杖追着打阿根廷将发行1万与2万面值的纸币库克现身上海为江西彩礼“减负”的“试婚人”因自嘲式简历走红的教授更新简介殡仪馆花卉高于市场价3倍还重复用网友称在豆瓣酱里吃出老鼠头315晚会后胖东来又人满为患了网友建议重庆地铁不准乘客携带菜筐特朗普谈“凯特王妃P图照”罗斯否认插足凯特王妃婚姻青海通报栏杆断裂小学生跌落住进ICU恒大被罚41.75亿到底怎么缴湖南一县政协主席疑涉刑案被控制茶百道就改标签日期致歉王树国3次鞠躬告别西交大师生张立群任西安交通大学校长杨倩无缘巴黎奥运

PHP网站源码 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化