Last active
October 10, 2019 16:26
-
-
Save peterthorsteinson/d4bb7f6c94219b4b6a7bd6b5cdd37cb4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Output: | |
// First 10 fibonacci numbers: | |
// 0 1 1 2 3 5 8 13 21 34 | |
class First10FibonacciNumbers | |
{ | |
static void Main() | |
{ | |
int previous = 0; | |
int current = 1; | |
System.Console.WriteLine("\nFirst 10 fibonacci numbers recursively:"); | |
DisplayFibonacciRecursive(previous, current, 10); | |
System.Console.WriteLine("\nFirst 10 fibonacci numbers iteratively:"); | |
DisplayFibonacciIterative(previous, current, 10); | |
System.Console.WriteLine(); | |
} | |
static void DisplayFibonacciRecursive(int previous, int current, int count) | |
{ | |
System.Console.Write(previous + " "); | |
int next = current + previous; | |
previous = current; | |
count--; | |
if (count == 0) return; | |
DisplayFibonacciRecursive(current, next, count); | |
} | |
static void DisplayFibonacciIterative(int previous, int current, int count) | |
{ | |
System.Console.Write(previous + " "); | |
System.Console.Write(current + " "); | |
int next; | |
for (int i = 2; i < count; i++) | |
{ | |
next = previous + current; | |
System.Console.Write(next + " "); | |
previous = current; | |
current = next; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment