Exercise
Function Factorial
Objective
The factorial of a number is expressed as follows:
n! = n · (n-1) · (n-2) · (n-3) · ... · 3 · 2 · 1
For example,
6! = 6·5·4·3·2·1
Create a recursive function to calculate the factorial of the number specified as parameter:
Console.Write ( Factorial (6) );
would display 720
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Main method where the program starts
public static void Main()
{
// Calling the Factorial function with the number 6 and printing the result
Console.WriteLine(Factorial(6)); // The factorial of 6 is 720, which will be printed
}
// Recursive function to calculate the factorial of a number
public static int Factorial(int n)
{
// Base case: if n is 1 or less, return 1 (because 1! = 1 or 0! = 1)
if (n <= 1)
{
return 1; // Factorial of 1 or less is 1
}
// Recursive case: n * factorial of (n-1)
return n * Factorial(n - 1); // Multiply n by the factorial of (n-1)
}
}