Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a string of fibonacci recursively in C#

Can that be done with no while loops?

static void Main(string[] args)
{
    Console.WriteLine("Please enter a number");
    int number = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine(" #" + Fibonacci(number));
}

public static int Fibonacci(int number)
{
    if (number <= 1)
    {
        return 1;
    }
    else
    {
        return Fibonacci(number - 2) + Fibonacci(number - 1);
    }
}

I can't even add a Console.WriteLine in the body of base case since it gets executed [number] number of times; Not sure how to do this without loops...

like image 926
Marin Avatar asked Mar 22 '12 18:03

Marin


People also ask

What is the recursive formula for Fibonacci series in C?

Fibonacci Series Using Recursion in C refers to a number series. The Fibonacci series is created by adding the preceding two numbers ahead in the series. Zero and one are the first two numbers in a Fibonacci series. We generate the rest of the numbers by adding both the previous numbers in the series.

How do you print a Fibonacci sequence?

Enter a positive integer: 100 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, In this program, we have used a while loop to print all the Fibonacci numbers up to n . If n is not part of the Fibonacci sequence, we print the sequence up to the number that is closest to (and lesser than) n . Suppose n = 100 .

Is Fibonacci recursive?

In mathematics, things are often defined recursively. For example, the Fibonacci numbers are often defined recursively. The Fibonacci numbers are defined as the sequence beginning with two 1's, and where each succeeding number in the sequence is the sum of the two preceeding numbers.


2 Answers

static void Main(string[] args)
{
    Console.WriteLine("Please enter a number");
    int number = Convert.ToInt32(Console.ReadLine());
    Fibonacci(0, 1, 1, number);
}   

public static void Fibonacci(int a, int b, int counter, int number)
{
    Console.WriteLine(a);
    if (counter < number) Fibonacci(b, a+b, counter+1, number);
}
like image 66
Gus Avatar answered Oct 06 '22 04:10

Gus


public static int Fibonatchi(int position) {

    if(position == 0) {
        return 1;
    }
    if(position == 1) {
        return 1;
    } else {
        return Fibonatchi(position - 2) + Fibonatchi(position - 1);
    }
}
like image 32
igal sidoy Avatar answered Oct 06 '22 03:10

igal sidoy