Scala control flow Program: Find a factorial with a while loop
Write a Scala program to find the factorial of a given number using a while loop.
Sample Solution:
Scala Code:
object FactorialCalculator {
def main(args: Array[String]): Unit = {
val number: Int = 4 // Number for which you want to find the factorial
var factorial: Long = 1 // Initialize the factorial variable as 1
var i: Int = number
while (i > 0) {
factorial *= i
i -= 1
}
println(s"The factorial of $number is: $factorial")
}
}
Sample Output:
The factorial of 4 is: 24
Explanation:
In the above exercise -
- First we define a variable "number" and assign it a value (5 in this case) for which we want to find the factorial. We initialize a variable factorial as 1 since the factorial of 0 is defined as 1. We also initialize a variable i with the value of "number".
- Inside the while loop, we multiply the current factorial value with i and store the result back in factorial. Then, we decrement the value of i by 1.
- The loop continues until i becomes 0. When the loop finishes, we print the result using println, which displays the factorial.
Scala Code Editor :
Previous: Scala control flow program to check even or odd number.
Next: Print Fibonacci series with while loop.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics