Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

recursive factorial function that prints to console on it's own (C#)

This one is just to scratch an itch, and probably not even a problem worth solving on it’s own.

I’d like to write a recursive factorial function to print to the console in C#. The thing is, just out curiosity, I tried to get it to do this by only passing the function and argument. As in, I’d like to avoid having to type Console.WriteLine(Factorial(5));

It’s harder that I’d thought to just type this and get a result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> Factorial(5);

here is the function I’ve been playing with:

int Factorial(int number)
{
    Console.Write(number != 1 ? $"{number} x " : $"{number} = \n");
    if (number <= 1) return 1; // end of the line
    number *= Factorial(number - 1); // recursive function
    Console.WriteLine(number);
    return number; // this could have been combined with line above, but more clear this way
}

the results come out like this, where instead of seeing the 2, 6 and 24. I’d just like to see the 120:

5 x 4 x 3 x 2 x 1 =
2
6
24
120

>Solution :

You could use a local function as the actual recursive part, using the outer Factorial function as a wrapper which just calls it!

int Factorial(int number)
{
    static int DoFactorial(int number) => number <= 1
        ? 1
        : number *= DoFactorial(number - 1);
        
    var answer = DoFactorial(number);
    Console.WriteLine(answer);
    
    return answer;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading