15,908,768 members
See more:
Here I got a java solution from Scaler for printing the Fibonacci series. But still doubtful.

What I have tried:

```<pre lang="Java">import java.io.*;

import java.util.*;

public class Main

{

//Recursive function to print the fibonacci series

static int fib(int n)

{

int res;

if(n <= 1)

return n;

else

{

res=fib(n - 1) + fib(n - 2);

}

return res;

}

public static void main(String[] args)

{

System.out.println("\nFIBONACCI SERIES USING RECURSION\n--------------------------------\n");

Scanner sc = new Scanner(System.in);

int n,i = 0;

System.out.println("Enter the number:");

n= sc.nextInt();

System.out.println("\nOutput\n-------")

while(i++ < n)

{

System.out.println(fib(i) + "");

}

}

}```
Posted
Updated 20-Jun-22 2:33am
v2
Richard Deeming 20-Jun-22 8:08am
My "valuable thoughts" are:

a) I don't. Since I'm not taking an "introduction to programming" course, I have no need of such code.

b) You haven't actually asked a question, nor explained what doubts you have.

c) If I really needed to calculate the Fibonacci sequence, I would avoid recursion, since that quickly leads to stack overflow errors.

d) If you submit a solution that you've taken from somewhere else as your own work, you will likely get kicked off your course for plagiarism.
OriginalGriff 20-Jun-22 8:40am
To be honest Richard, you'd need to use BigInteger values or similar to get the stack to blow. Even with long values you'll overflow before you reach 100 values in the sequence! :laugh:

## Solution 1

Use a loop: it's pretty simple to generate Fibonacci numbers, all you need are the previous two elements.

1) Create two variables N1 and N2
2) Set N1 to 0
3) Set N2 to 1
4) Loop:
4.1) Print N2
4.2) Add N1 and N2, store it in N
4.3) Set N1 to N2
4.4) Set N2 to N
4.5) If you have not printed enough values, loop back to 4
5) Done

This isn't a complex bit of code, so give it a try.
If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]

CPallini 20-Jun-22 9:03am
5.

## Solution 2

Quote:
Here I got a java solution from Scaler for printing the Fibonacci series. But still doubtful.

The fact that you get correct answer is a good indication that the code is correct.
Quote:

The 0 is missing at first place in answer.
Java
```System.out.println("\nOutput\n-------")
// a semicolon is missing here          ^```

CPallini 20-Jun-22 9:04am
5.
Patrice T 20-Jun-22 9:06am
Thank you.