ASP.NET MVC, MVC, C#, PYTHON, JQUERY

Wednesday, September 12, 2018

Factorial program using recursion in c#




We have come across the situations where a function calls another function but there is one more possibility that a function calls itself.
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.

  1. using System;    
  2.     
  3. namespace Recursion_Example   
  4. {    
  5.     class Program    
  6.     {    
  7.         static void Main(string[] args)    
  8.         {    
  9.            int n;
  10.             Console.WriteLine("Enter the Number");    
  11.     
  12.                
  13.              n =Convert.ToInt32(Console.ReadLine());     //read number from user
  14.     
  15.             double factorial = Factorial(n);    //invoke the static method    
  16.     
  17.             //print the factorial result    
  18.             Console.WriteLine("factorial of"+n+"="+factorial.ToString());    
  19.     
  20.         }    
  21.         public static double Factorial(int n)    
  22.         {    
  23.             if (n == 0)    
  24.                 return 1;    
  25.             return n * Factorial(n-1);//Recursive call    
  26.     
  27.         }    
  28.     }    
  29. }    
Share:

0 comments:

Post a Comment

SOCIAL PROFILES

Search This Blog

Powered by Blogger.

Fixed Menu (yes/no)

yes

Contact Form

Name

Email *

Message *

Tags

Ads Section

Tags

ASP.NET MVC (7) C# (11) jQuery (1)