C# Sharp Exercises: Function : To find the factorial of a given number
C# Sharp Function: Exercise-11 with Solution
Write a program in C# Sharp to create a recursive function to find the factorial of a given number.
Pictorial Presentation:
Sample Solution:
C# Sharp Code:
using System;
class funcexer11
{
static void Main()
{
decimal f;
Console.Write("\n\nRecursive Function : To find the factorial of a given number :\n");
Console.Write("------------------------------------------------------------------\n");
Console.Write("Input a number : ");
int num= Convert.ToInt32(Console.ReadLine());
f = Factorial(num);
Console.WriteLine("The factorial of {0}! is {1}", num, f);
}
static decimal Factorial(int n1)
{
// The bottom of the recursion
if (n1 == 0)
{
return 1;
}
// Recursive call: the method calls itself
else
{
return n1 * Factorial(n1 - 1);
}
}
}
Sample Output:
Recursive Function : To find the factorial of a given number : ------------------------------------------------------------------ Input a number : 5 The factorial of 5! is 120
Flowchart :
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a program in C# Sharp to create a function to calculate the sum of the individual digits of a given number.
Next: Write a program in C# Sharp to create a recursive function to calculate the Fibonacci number of a specific term.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework