Monday, March 28, 2016

factorial number

  1st method:-

int i, number, fact;
            Console.WriteLine("Enter the Number");
            number = int.Parse(Console.ReadLine());
            fact = number;
            for (i = number - 1; i >= 1; i--)
            {
                fact = fact * i;
            }
            Console.WriteLine("\nFactorial of Given Number is: " + fact);

2nd method:-
class Program
        {

            static int Fact(int n)
            {
                if (n <= 1)
                    return 1;
                return n * Fact(n - 1);
            }

            static int Factorial(int n)
            {
                if (n <= 1)
                    return 1;
                int result = 1;
                for (int i = 2; i <= n; i++)
                {
                    result = result * i;
                }
                return result;
            }


            static void Main(string[] args)
            {
                Console.Write("Enter a Number to find factorial: ");
                int n = Convert.ToInt32(Console.ReadLine());
                int r = Fact(n);
                Console.WriteLine(n.ToString() + "! = " + r.ToString());

                Console.Write("Enter a Number to find factorial: ");
                n = Convert.ToInt32(Console.ReadLine());
                r = Factorial(n);
                Console.WriteLine(n.ToString() + "! = " + r.ToString());
            }
        }

3rd Method:-
  class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Enter a number");
                int number = Convert.ToInt32(Console.ReadLine());
                long fact = GetFactorial(number);
                Console.WriteLine(fact);
                Console.ReadKey();
            }
            private static long GetFactorial(int no)
            {
                if (no == 0)
                {
                    return 1;
                }
                else
                {
                    return no * GetFactorial(no - 1);
                }
            }

        }

No comments:

Post a Comment

Find the value from array when age is more than 30

 const data = [   { id: 1, name: 'Alice', age: 25 },   { id: 2, name: 'Bob', age: 30 },   { id: 3, name: 'Charlie', ...