Q:

Kotlin program to find the sum of each row and each column of a matrix

belongs to collection: Kotlin Array Programs

0

Given a matrix, we have to find the sum of each row and each column.

Example:

    Input:
    matrix:
    [3, 4, 5]
    [6, 3, 3]
    [2, 1, 2]
    [3, 4, 3]

    Output:
    [3, 4, 5]  : SumOfRow-> 12
    [6, 3, 3]  : SumOfRow-> 12
    [2, 1, 2]  : SumOfRow-> 5
    [3, 4, 3]  : SumOfRow-> 10
    Sum of 1 column : 14
    Sum of 2 column : 12
    Sum of 3 column : 13

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find the sum of each row and each column of a matrix in Kotlin

package com.includehelp

import java.util.*

// Main function, Entry Point of Program
fun main(args: Array<String>) {

    //variable of rows and col
    val rows: Int
    val column: Int

    //Input Stream
    val scanner = Scanner(System.`in`)

    //Input no of rows and column
    print("Enter the number of rows and columns of matrix : ")
    rows   = scanner.nextInt()
    column = scanner.nextInt()

    //Create Array
    val matrixA     = Array(rows) { IntArray(column) }

    //Input Matrix
    println("Enter the Elements of First Matrix ($rows X $column} ): ")
    for(i in matrixA.indices){
        for(j in matrixA[i].indices){
            print("matrixA[$i][$j]: ")
            matrixA[i][j]=scanner.nextInt()
        }
    }

    //print Matrix A and Sum of Row
    println("Matrix A : ")
    for(i in matrixA.indices){
        println("${matrixA[i].contentToString()}  : SumOfRow-> ${matrixA[i].sum()} ")
    }


    //Sum of Column
    for(i in 0 until column){
        var sumOfCol=0
        for(j in 0 until rows){
            sumOfCol+=matrixA[j][i]
        }
        println("Sum of ${i+1} column : "+sumOfCol)
    }
}

Output

Run 1:
Enter the number of rows and columns of matrix : 3
2
Enter the Elements of First Matrix (3 X 2} ):
matrixA[0][0]: 3
matrixA[0][1]: 4
matrixA[1][0]: 5
matrixA[1][1]: 2
matrixA[2][0]: 1
matrixA[2][1]: 2
Matrix A :
[3, 4]  : SumOfRow-> 7
[5, 2]  : SumOfRow-> 7
[1, 2]  : SumOfRow-> 3
Sum of 1 column : 9
Sum of 2 column : 8
-----------
Run 2:
Enter the number of rows and columns of matrix : 4
3
Enter the Elements of First Matrix (4 X 3} ):
matrixA[0][0]: 3
matrixA[0][1]: 4
matrixA[0][2]: 5
matrixA[1][0]: 6
matrixA[1][1]: 3
matrixA[1][2]: 3
matrixA[2][0]: 2
matrixA[2][1]: 1
matrixA[2][2]: 2
matrixA[3][0]: 3
matrixA[3][1]: 4
matrixA[3][2]: 3
Matrix A :
[3, 4, 5]  : SumOfRow-> 12
[6, 3, 3]  : SumOfRow-> 12
[2, 1, 2]  : SumOfRow-> 5
[3, 4, 3]  : SumOfRow-> 10
Sum of 1 column : 14
Sum of 2 column : 12
Sum of 3 column : 13

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program to find transpose of a matrix... >>
<< Kotlin program to check sparse matrix...