Group
Functions in C#
Objective
1. Define a recursive function named "Factorial" that takes an integer parameter.
2. In the base case, if the number is 1, return 1.
3. In the recursive case, multiply the number by the result of calling "Factorial" with the number decreased by 1.
4. Return the result of the factorial calculation.
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.
Example usage:
Console.Write(Factorial(6));
Output: 720
Example C# Exercise
Show C# Code
using System;
class Program
{
// Recursive function to calculate the factorial of a number
public static int Factorial(int n)
{
// Base case: if n is 1, return 1 (end of recursion)
if (n == 1)
{
return 1;
}
else
{
// Recursive case: n * Factorial(n-1)
return n * Factorial(n - 1);
}
}
// Main method to run the program
public static void Main()
{
// Call the Factorial function with the number 6 and display the result
Console.WriteLine(Factorial(6)); // Output will be 720
}
}
Output
720