When a function calls itself it is known as recursion. It is usually used where we have to repeat a process again and again.
The following program for finding factorial using recursion is an example of recursive function and its implementation.
- using System;
- namespace Recursion_Example
- {
- class Program
- {
- static void Main(string[] args)
- {
- int n;
- Console.WriteLine("Enter the Number");
- n =Convert.ToInt32(Console.ReadLine()); //read number from user
- double factorial = Factorial(n); //invoke the static method
- //print the factorial result
- Console.WriteLine("factorial of"+n+"="+factorial.ToString());
- }
- public static double Factorial(int n)
- {
- if (n == 0)
- return 1;
- return n * Factorial(n-1);//Recursive call
- }
- }
- }







0 comments:
Post a Comment