Tuesday, May 31, 2016

C# Recursive Method Call Example

Problem to solve. We need to calculate:
4! = 4*3*2*1 = 24
This can be done with a reverse for loop like this:

 public double calcfactor(int number)  
     {  
       if (number == 0) return 1;  
       double factorial = 1;  
       for(int i = number; i>=1; i--)  
       {  
         Console.WriteLine(factorial = factorial*i);  
       }  
       return factorial;  
     }  

But it can also be solved like this with a recursive method call:

4! = 4* (4-1) *(4-2)*(4-3) = 24

But be careful to break out of the loop with some condition.

 public double calcfactor(int number)  
     {  
       if (number == 0) return 1;  
       return number * calcfactor(number - 1);  
     }  

No comments:

Post a Comment