daily pastebin goal
62%
SHARE
TWEET

Chapter - 15 - Methods (2) Recursion - Fibonacci

A4L Dec 7th, 2018 (edited) 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. /*Your mission, should you choose to accept it, is to create a method called Fibonacci, which takes in a
  7. number and returns that number of the Fibonacci sequence. So if someone calls Fibonacci(3), it
  8. would return the 3 rd number in the Fibonacci sequence, which is 2. If someone calls Fibonacci(8), it
  9. would return 21. In your Main method, write code to loop through the first 10 numbers of the Fibonacci sequence and
  10. print them out.*/
  11. namespace Chapter___15___Method_Recursion_Fibonacci
  12. {
  13.     class Program
  14.     {
  15.         static void Main(string[] args)
  16.         {
  17.             for (int index = 1; index <= 10; index++)
  18.             {
  19.                 Console.WriteLine(Fibonacci(index));
  20.             }
  21.  
  22.             Console.ReadKey();
  23.         }
  24.  
  25.         /*  0, 1, 1, 2, 3, 5, 8, 13, 21, 34
  26.          * 1
  27.          * 1
  28.          * 1+1=2
  29.          * 1+2=3
  30.          * 2+3=5
  31.          * 3+5=8
  32.          * 5+8=13
  33.          * 8+13=21
  34.          * 21+13=34
  35.          */
  36.  
  37.         static ulong Fibonacci(int number)
  38.         {
  39.             if (number == 1) { return 1; }
  40.             if (number == 2) { return 1; }
  41.  
  42.             return Fibonacci(number - 1) + Fibonacci(number - 2);
  43.         }
  44.  
  45.         static int Factorial(int n)
  46.         {
  47.             // We establish our "base case" here. When we get to this point, we're done.
  48.             if (n == 1)
  49.                 return 1;
  50.                 return n * Factorial(n - 1);
  51.         }
  52.     }
  53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top