0% found this document useful (0 votes)
4 views2 pages

Java Fibonacci Series: Recursive & Iterative

Uploaded by

Piyush singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Java Fibonacci Series: Recursive & Iterative

Uploaded by

Piyush singh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Piyush Kumar 231302160

Program 1
Aim- Write a Java program to find the Fibonacci series using recursive and non-
recursive functions.

Program-
import [Link];
public class Fibonacci {

// Recursive function to calculate the Fibonacci number at position n


public static int fibonacciRecursive(int n) {
// Base case: Fibonacci(0) = 0, Fibonacci(1) = 1
if (n <= 1) {
return n;
} else {
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
}

// Non-recursive (iterative) function to calculate the Fibonacci number at position n


public static int fibonacciNonRecursive(int n) {
if (n <= 1) {
return n;
}
int first = 0, second = 1, next;
for (int i = 2; i <= n; i++) {
next = first + second;
first = second;
second = next;
}
return second;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link])
[Link]("Enter the number of terms for Fibonacci series: ");
int n = [Link]();
[Link]("\nFibonacci series using recursion:");
for (int i = 0; i < n; i++) {
[Link](fibonacciRecursive(i) + " ");
}
Piyush Kumar 231302160

[Link]("\nFibonacci series using non-recursion:");


for (int i = 0; i < n; i++) {
[Link](fibonacciNonRecursive(i) + " ");
}

[Link]();
}
}
Output-

You might also like