Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Fibonacci Sequence Printing to infinity

1. ## Fibonacci Sequence Printing to infinity

I'm experiencing a problem with my code or rather, I'm unsure as to how to go about doing something.

I made a script that prints out the fibonacci sequence:

Code:
```public class Fibonacci {
public static int fib(int n) {
if (n == 1)
return 1;
if (n == 0)
return 0;
return fib(n - 1) + fib(n - 2);

}

public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
System.out.println(fib(i));
}
}
}```
However, I have to specify how far it'll go before it stops printing the sequence. I want it to print the numbers forever until either the program crashes, or I close it. I was hoping some of you could help me do that.

2. ## Im new to Java

I was looking at the code and, tell me if I'm wrong, wouldn't a do()....while() loop be the kind you would need for something like this? I'm not sure how to get it to work(I'm trying right now) but wouldn't that be the way to do it?

3. here it is in C#... A clever individual would be able to convert this rather easily or find it's Java equiv somewhere on google :|
Code:
```class playGround
{

public playGround()
{
int i = 0;
while (true)
{
Console.WriteLine(fib(i));
i++;
}
}

private int fib(int a)
{
switch (a)
{
case 0:
return 0;
case 1:
return 1;
default:
return fib(a - 1) + fib(a - 2);
}
}
}```

4. Code:
```public class Fibonacci {
public static int fib(int n) {
if (n == 1)
return 1;
if (n == 0)
return 0;
return fib(n - 1) + fib(n - 2);

}

public static void main(String[] args) {
int i= 0;
while(true) {
System.out.println(fib(i));
i++;
}
}
}```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•