Question How do you write a program to print the Fibonacci series 0, 1,1,2,3,5,8…n?

Status
Not open for further replies.
Jun 20, 2022
1
0
10
Here is a java solution that I got from Scaler for printing the Fibonacci series. But still doubtful.

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) + "");

}

}

}

Please put your valuable insights and help me correct it.
 

Ralston18

Titan
Moderator
Seconding the previous posts.

You provided some code that apparently does not work.

Explain why you are doubtful.

Show the output of your work compared to the Fibonacci sequence. Just a comparison of the respective results may prove revealing.

Objective is to do your own work and know what each line of code does.

Plus, as noted by @hotaru.hino , some thought as to how the sequence is generated. Work through the process manually to improve your understanding of what all needs to be done and in what order. Including loops.
 
Status
Not open for further replies.