Q:

Kotlin program to find factorial of a number

belongs to collection: Kotlin Basic Programs

0

Factorial of number is the product of all positive numbers less or equal to the number.

Factorial of number n is denoted by n! is calculated using the formula, n! = n*(n-1)*(n-2)*...*2*1.

To find the factorial of the entered number, we have used a for loop that runs from n to 1. At each iteration, i is multiplied with the factorial variable.

Example:

    Input: 
    n = 5

    Output:
    factorial = 120 [5x4x3x2x1 = 120]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find factorial of a number in Kotlin

package com.includehelp.basic

import java.util.*

// Main Method Entry Point of Program
fun main(args:Array<String>) {
    // InputStream to get Input
    var reader = Scanner(System.`in`)
    
    // Input Integer Value
    println("Enter Number : ")
    var number = reader.nextInt()
    
    var factorial: Long=1
    
    for(i in 1..number){
        // Calculate Factorial
        factorial*=i.toLong()
    }
    
    // printing
    println("Factorial of $number is $factorial ")
}

Output

Run1 :
Enter Number :
5
Factorial of 5 is 120
---
Run 2:
Enter Number :
12
Factorial of 12 is 479001600

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to display Fibonacci series... >>
<< Kotlin program to check if given number is perfect...