Factorial of a number in C#(CSharp)


The following is an example of the factorial number. It is also recursive method. Have a look:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public int factorial(int n)
        {
            int result;
            if (n == 1)
                return 1;
            else
            {
                result = factorial(n - 1) * n;
                return result;
            }
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            Console.WriteLine("Factorial of 3 is " + obj.factorial(3));
            Console.WriteLine("Factorial of 4 is " + obj.factorial(4));
            Console.WriteLine("Factorial of 5 is " + obj.factorial(5));

            Console.ReadLine();
        }
    }
}

Output:

Factorial

No comments:

Post a Comment

Recent Posts