# Generate Fibonacci Series Using Recursion

Page 1 of 1

## 4 Replies - 61167 Views - Last Post: 11 May 2008 - 09:33 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=51604&amp;s=4a4443b0c51e7eec8e6c82a62b67e068&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 crafty

Reputation: 1
• Posts: 24
• Joined: 10-May 08

# Generate Fibonacci Series Using Recursion

Posted 10 May 2008 - 03:48 AM

```namespace fabi
{
class fab
{
public static int fibonacci(int n)
{
int previous = -1;
int next = 1;
for (int i = 0; i < n; i++)
{
int sum = next + previous;
previous = next;
next = sum;
Console.WriteLine(next);
}
return next;
}

static void Main(string[] a)
{
int num;
Console.WriteLine("Enter a number:");
Console.WriteLine("\n");
Console.WriteLine("The first " + num + " number(s) in the fibonacci series are: ");
fibonacci(num);

}
}
}

```

Is This A Good Question/Topic? 0

## Replies To: Generate Fibonacci Series Using Recursion

### #2 baavgai

• Dreaming Coder

Reputation: 7164
• Posts: 14,932
• Joined: 16-October 07

## Re: Generate Fibonacci Series Using Recursion

Posted 10 May 2008 - 07:58 AM

To show you would probably be to do it.

So, here's a hint. The following two methods give identical output.

```// non recursion
void ShowNumsLoopy(int n) {
for (int i = 0; i < n; i++) {
Console.WriteLine(i);
}
}

// recursion
// in recursion, there's usually some kind of setup before the thing gets started.
void ShowNumsRecusion(int n) {
ShowNumsRecusion(n, 0);
}
// the work is here
void ShowNumsRecusion(int n, int i) {
if (i < n) {
Console.WriteLine(i);
ShowNumsRecusion(n, i - 1);
}
}

```

Hope this helps.

### #3 crafty

Reputation: 1
• Posts: 24
• Joined: 10-May 08

## Re: Generate Fibonacci Series Using Recursion

Posted 10 May 2008 - 09:57 PM

Hey thanks. I finished my program.

But I hv a doubt :
```ShowNumsRecusion(n, i - 1);
```

It went into infinite loop when I used it, instead I used :
```ShowNumsRecusion(n, i + 1);
```

### #4 baavgai

• Dreaming Coder

Reputation: 7164
• Posts: 14,932
• Joined: 16-October 07

## Re: Generate Fibonacci Series Using Recursion

Posted 11 May 2008 - 08:36 AM

Oops. Yeah, that way.

```void ShowNumsRecusion(int n) {
if (n<0) { return: }
ShowNumsRecusion(n-1);
Console.WriteLine(n);
}

```

But it contains n inclusive, which isn't exactly the same, so I rewrote it. Bugs are funny that way. Sorry.

### #5 crafty

Reputation: 1
• Posts: 24
• Joined: 10-May 08

## Re: Generate Fibonacci Series Using Recursion

Posted 11 May 2008 - 09:33 AM

This is very elegant and simple. Thanks again.

This post has been edited by crafty: 11 May 2008 - 09:33 AM