C# Program to Calculate Factorial Using Recursion

In this C# program, we will create a recursive function to calculate the factorial of a given number. The factorial of a number is calculated by multiplying the number by each integer below it until 1 is reached. For example, the factorial of 6 (6!) is 6 * 5 * 4 * 3 * 2 * 1 = 720. A recursive function works by calling itself with smaller inputs until it reaches a base case, in this case when the input number is 1. The result will then be returned as the factorial of the number.



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

 Copy 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

Share this C# Exercise

More C# Practice Exercises of Functions in C#

Explore our set of C# Practice Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.