English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn how to add two matrices using multi-dimensional arrays in Kotlin.
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)) //Addition of 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] } } //Display the result println("The sum of two matrices is: ") for (row in sum) { for (column in row) { print("$column ") } println() } }
When running the program, the output is:
The sum of the two matrices is: -2 8 7 10 8 6
In the above program, two matrices are stored in a two-dimensional array, i.e., firstMatrix and secondMatrix. We also define the number of rows and columns, and store them in variables rows and columns, respectively.
Then, we initialize a new array named sum with a given number of rows and columns. This matrix array stores the addition of the given matrices.
We iterate over each index of the two arrays to add and store the result.
Finally, we use the for (foreach variable) loop to iterate over each element of the sum array to print the elements.
Here is the equivalent Java code:Java Program to Add Two Matrices Using Arrays