w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Find the factorial of a given number

Secondary Nav

C# Sharp Recursion : Exercise-9 with Solution

Write a program in C# Sharp to find the factorial of a given number using recursion.
Test Data :
Input any positive number : 5
Expected Output
:
The factorial of 5 is : 120

C# Sharp Code:

using System;

class RecExercise9
    {
        static void Main(string[] args)
        {
			Console.WriteLine("\n\n Recursion : Find the factorial of a given number :");
			Console.WriteLine("-------------------------------------------------------");
	
			Console.Write(" Input any positive number : ");
            int n1 = Convert.ToInt32(Console.ReadLine());
            long fact = FactorialCalcu(n1);
            Console.WriteLine(" The factorial of {0} is : {1} ", n1, fact);           
            Console.ReadKey();
        }
 
        private static long FactorialCalcu(int n1)
        {          
            if (n1 == 0)
            {
                return 1;
            }
            return n1 * FactorialCalcu(n1-1);
        }
    }

C# Sharp Practice online:


using System;

class RecExercise9
    {
        static void Main(string[] args)
        {
			Console.WriteLine("\n\n Recursion : Find the factorial of a given number :");
			Console.WriteLine("-------------------------------------------------------");
	
			Console.Write(" Input any positive number : ");
            int n1 = Convert.ToInt32(Console.ReadLine());
            long fact = FactorialCalcu(n1);
            Console.WriteLine(" The factorial of {0} is : {1} ", n1, fact);           
            Console.ReadKey();
        }
 
        private static long FactorialCalcu(int n1)
        {          
            if (n1 == 0)
            {
                return 1;
            }
            return n1 * FactorialCalcu(n1-1);
        }
    }

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program