Programming in C# myFib Write a C# function using recursion to compute the Fibon
ID: 3709767 • Letter: P
Question
Programming in C#
myFib
Write a C# function using recursion to compute the Fibonacci number of n (where n is a positive integer). Your function should output the calculated result for the n given. You also need to type check to make sure the value being given is an integer.
Fib(n) = 1 for n = 0 or n = 1
Fib(n) = Fib(n-1) + Fib(n-2) for n > 1
Output sample:
myFib(5);
8
myFib(10);
89
myFib(8);
34
myFib(“Thirtyfive”);
Not an integer value!
myFib(3.5);
Not an integer value!
Explanation / Answer
using System.IO;
using System;
class Program
{
static void Main()
{
Console.WriteLine(myFib(5));
}
static int myFib(int n) {
if(n==0 || n==1) return 1;
else if (n == 2)
return n;
return myFib(n-1) + myFib(n-2);
}
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.