w3resource

Kotlin Program: Generate a multiplication table of a number

Kotlin Control Flow: Exercise-8 with Solution

Write a Kotlin program to generate the multiplication table of a given number.

Sample Solution:

Kotlin Code:

fun main() {
    // Change this value to generate the multiplication
    //  table for a different number
    
    val number = 7

    println("Multiplication table of $number:")
    generateMultiplicationTable(number)
}

fun generateMultiplicationTable(number: Int) {
    for (i in 1..10) {
        val result = number * i
        println("$number * $i = $result")
    }
}

Sample Output:

Multiplication table of 7:
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

Explanation:

In the above exercise,

  • In the main() function the "number" variable represents the number for which we want to generate the multiplication table. You can modify this value to generate the table for a different number.
  • The "generateMultiplicationTable()" function takes the number as an argument and generates a multiplication table for that number.
  • Inside the "generateMultiplicationTable()" function, we use a for loop to iterate from 1 to 7.
  • For each iteration, we calculate the result of multiplying the number with the loop variable i and store it in the result variable.
  • Finally we print the multiplication expression and the corresponding result using the println() function.

Kotlin Editor:


Previous: Calculate the sum of numbers between a given range.
Next: Count even and odd elements in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.