Scala - Calculating factorials of numbers from 1 to 1 using recursion Code Example

The code for Calculating factorials of numbers from 1 to 1 using recursion

// Recursive function
def factorial(i: BigInt): BigInt = i match {
 case _ if i == 1 => i
 case _ => i * factorial(i - 1)
}

// Printing factorials of numbers 
// from 1 to 1 using recursion
// and, printing them
var formatted_string = ""
for (i <- 1 to 10)
 printf("Factorial of %2d is %8d\n",i,factorial(i))

/*
Output:
Factorial of  1 is        1
Factorial of  2 is        2
Factorial of  3 is        6
Factorial of  4 is       24
Factorial of  5 is      120
Factorial of  6 is      720
Factorial of  7 is     5040
Factorial of  8 is    40320
Factorial of  9 is   362880
Factorial of 10 is  3628800
*/
Code by IncludeHelp, on August 8, 2022 02:42

Comments and Discussions!

Load comments ↻






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