Skip to content

Commit f20d6e0

Browse files
Fibonacci series using recursion (solution)
1 parent d1d31bd commit f20d6e0

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Recursion/FibonacciSeries.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.Scanner;
2+
3+
public class FibonacciSeries {
4+
5+
static int number1 = 0; // Declaring and initializing the variables
6+
static int number2 = 1, number3 = 0;
7+
8+
// Main method
9+
public static void main(String[] args) { // Question: Display the fibonacci numbers from 1 to n, where n is
10+
// limit of the fibonacci series, provided by the user as input
11+
// Using recursion.
12+
System.out.println("Enter the limit of fibonacci number"); // Telling the user to enter the limit.
13+
14+
Scanner input = new Scanner(System.in);
15+
int n = input.nextInt(); // Taking the input from user
16+
17+
System.out.print(0 + " "); // Printing the first number
18+
System.out.print(1 + ""); // printing second number
19+
fibonacciNumber(n); // Function call to print the fibonacci series
20+
}
21+
22+
// Method to print fibonacci series (Recursion)
23+
public static void fibonacciNumber(int n) {
24+
25+
if(n > 0) {
26+
27+
number3 = number1 + number2;
28+
number1 = number2;
29+
number2 = number3;
30+
31+
System.out.print(" " + number3); // Printing the number of fibonacci series one by one.
32+
33+
fibonacciNumber(n - 1); // Function call (Recursive call)
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)