Kotlin Program to find factorial of a number using class


In this program, You will learn how to find factorial of a number using class in Kotlin.


3! => 1 * 2 * 3 = 6

4! => 1 * 2 * 3 * 4 = 24

Example: How to find factorial of a number using class in Kotlin.

import java.util.Scanner

class Test {

    fun add(n: Int): Int {
        var f = 1
        for (i in 1..n) {
            f *= i
        }
        return f
    }
}

fun main(args: Array<String>) {

    var n: Int
    var f: Int
    val sc = Scanner(System.`in`)

    print("Enter a number:")
    n = sc.nextInt()

    var obj = Test()
    f = obj.add(n)

    println("The factorial is:$f")
}

Output:

Enter a number:4
The factorial is:24