Kotlin Program to Add Two Matrix Using Multi-dimensional Arrays

Example: Program to Add Two Matrices

fun main(args: Array<String>) {
    val rows = 2
    val columns = 3
    val firstMatrix = arrayOf(intArrayOf(2, 3, 4), intArrayOf(5, 2, 3))
    val secondMatrix = arrayOf(intArrayOf(-4, 5, 3), intArrayOf(5, 6, 3))

    // Adding Two matrices
    val sum = Array(rows) { IntArray(columns) }
    for (i in 0..rows - 1) {
        for (j in 0..columns - 1) {
            sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]
        }
    }

    // Displaying the result
    println("Sum of two matrices is: ")
    for (row in sum) {
        for (column in row) {
            print("$column    ")
        }
        println()
    }
}

When you run the program, the output will be:

Sum of two matrices is:
-2    8    7    
10    8    6    

In the above program, the two matrices are stored in 2d array, namely firstMatrix and secondMatrix. We've also defined the number of rows and columns and stored them in variables rows and columns respectively.

Then, we initialize a new array of the given rows and columns called sum. This matrix array stores the addition of the given matrices.

We loop through each index of both arrays to add and store the result.

Finally, we loop through each element in the sum array using a for (foreach variation) loop to print the elements.

Here's the equivalent Java code: Java program to add two matrices using arrays

Did you find this article helpful?