Kotlin Program to Generate and Print Multiplication Table

In this post, we will go through Kotlin program to generate and print multiplication table of given number.

We will learn to generate multiplication table using

  1. for Loop
  2. while Loop

1. Multiplication Table Using for Loop

In this section, we will learn to generate table using for loop in kotlin. We will also see how to use ranges to iterate using for loop.

Sourcecode –

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter Number:")
    val number = read.nextInt()

    println("Multiplication Table: \n")
    for (index in 1..10) {
        val product = number * index
        println("$number * $index = $product")
    }

    println("\nThe End")
}

When you run the program, output will be

Enter Number:
12
Multiplication Table:

12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120

The End

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.

Input read by scanner is then stored in variable number

When you run the program, you are asked to enter one number. Based on that number, multiplication table is generated.

2. Generate Multiplication Table Using while Loop

In previous section, we used for loop and ranges to generate multiplication table in Kotlin. In this section, we will use while loop to generate table.

Sourcecode –

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter Number:")
    val number = read.nextInt()

    println("Multiplication Table: \n")

    var index = 1
    while(index <= 10) {
        val product = number * index
        println("$number * $index = $product")
        index++
    }

    println("\nThe End")
}

When you run the program, output will be

 Enter Number:
 15
 Multiplication Table:

 15 * 1 = 15
 15 * 2 = 30
 15 * 3 = 45
 15 * 4 = 60
 15 * 5 = 75
 15 * 6 = 90
 15 * 7 = 105
 15 * 8 = 120
 15 * 9 = 135
 15 * 10 = 150

 The End

Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.

read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.

Input read by scanner is then stored in variable year

We have used while loop to generate multiplication table in kotlin. Notice that we are increasing value of index by 1 using ++ operator. So, while loop will run from 1 to 10 only.

Finally, we print result value using println() method.

Thus, we went through Kotlin program to generate and print multiplication table of given number.

Leave a Reply