Scala - Nesting Method Definitions (Calculate Factorials) Code Example

The code for Nesting Method Definitions (Calculate Factorials)

def CalculateFactorial(i: Int): Int = {
 def fact(i: Int, accumulator: Int): Int = {
 if (i <= 1)
 accumulator
 else
 fact(i - 1, i * accumulator)
 }
 fact(i, 1)
}
println( CalculateFactorial(2) )
println( CalculateFactorial(4) )
println( CalculateFactorial(6) )
println( CalculateFactorial(8) )
println( CalculateFactorial(10) )
println( CalculateFactorial(12) )

/*
Output:
2
24
720
40320
3628800
479001600
*/
Code by IncludeHelp, on August 7, 2022 17:28

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.