1. Introduction

A multiplication table is a fundamental mathematical tool that displays the product of two numbers in a structured tabular format. It’s a common educational aid and serves as a helpful reference for various calculations.

In this tutorial, we’ll explore how to generate a multiplication table with Kotlin. We’ll cover a few different approaches: using a for() loop, a while() loop, and a functional approach.

2. Using a for() Loop

The for() loop is particularly suitable when we know the range of numbers we want to iterate through.

Let’s write a function to generate the multiplication table using a for() loop:

private fun generateMultiplicationTableUsingForLoop(num: Int): String {
    val table = StringBuilder()
    for (i in 1..10) {
        val product = num * i
        table.append("$num * $i = $product\n")
    }
    return table.toString().trim()
}

We should also write unit tests to verify the correctness of our multiplication table generator:

@Test
fun `generate multiplication table using for loop`() {
    val num = 6
    val expectedTable = """
        6 * 1 = 6
        6 * 2 = 12
        6 * 3 = 18
        6 * 4 = 24
        6 * 5 = 30
        6 * 6 = 36
        6 * 7 = 42
        6 * 8 = 48
        6 * 9 = 54
        6 * 10 = 60
    """.trimIndent()

    val actualTable = generateMultiplicationTableUsingForLoop(num)

    assertEquals(expectedTable, actualTable)
}

In the test above, we have a function generateMultiplicationTableUsingForLoop() that generates a multiplication table using a for() loop and returns it as a String. We then compare the expected table with the actual one using JUnit’s assertEquals() method.

3. Using a while() Loop

A while() loop is a suitable choice when we need more granular control over iterations, such as when we want to perform additional conditional checks or update loop variables dynamically within the loop body.

Let’s write the multiplication table generation function using a while() loop:

private fun generateMultiplicationTableUsingWhileLoop(num: Int): String {
   val table = StringBuilder()
   var i = 1
   while (i <= 10) {
        val product = num * i
        table.append("$num * $i = $product\n")
        i++
    }
    return table.toString().trim()
}

Now, let’s write unit tests to verify the correctness of our multiplication table generator:

@Test
fun `generate multiplication table using while loop`() {
    val num = 10
    val expectedTable = """
        10 * 1 = 10
        10 * 2 = 20
        10 * 3 = 30
        10 * 4 = 40
        10 * 5 = 50
        10 * 6 = 60
        10 * 7 = 70
        10 * 8 = 80
        10 * 9 = 90
        10 * 10 = 100
    """.trimIndent()

    val actualTable = generateMultiplicationTableUsingWhileLoop(num)

    assertEquals(expectedTable, actualTable)
}

In this test, we have a function generateMultiplicationTableUsingWhileLoop() that generates a multiplication table using a while() loop and returns it as a String. Then, we compare the table against our expectations to ensure it was generated correctly.

4. Using a Functional Approach

The functional approach is advantageous if we prefer a concise and declarative way of generating the multiplication table. This leverages Kotlin’s functional programming features to streamline the code and improve code readability.

Let’s generate the multiplication table using a functional approach:

private fun generateMultiplicationTableFunctionally(num: Int): String {
    return (1..10).map { i ->
        val product = num * i
        "$num * $i = $product"
    }.joinToString("\n")
}

Next, let’s write unit tests to validate the correctness of our functional approach:

@Test
fun `generate multiplication table functionally`() {
    val num = 7
    val expectedTable = """
        7 * 1 = 7
        7 * 2 = 14
        7 * 3 = 21
        7 * 4 = 28
        7 * 5 = 35
        7 * 6 = 42
        7 * 7 = 49
        7 * 8 = 56
        7 * 9 = 63
        7 * 10 = 70
    """.trimIndent()

    val actualTable = generateMultiplicationTableFunctionally(num)

    assertEquals(expectedTable, actualTable)
}

In this test, we have a function generateMultiplicationTableFunctionally() that generates a multiplication table using a functional approach and returns it as a String. We compare the expected table with the actual one as before.

5. Conclusion

In this tutorial, we’ve explored three different approaches to generating a multiplication table in Kotlin and validating them with unit tests. Whether we choose to use a for() loop, while() loop, or functional approach depends on our specific requirements and coding style.

Writing unit tests ensures that our multiplication table generator functions correctly, allowing us to confidently apply these techniques to various mathematical and programming tasks in Kotlin. As always, the code used in this tutorial is available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.