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

Java Experiment 1

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)
10 views2 pages

Java Experiment 1

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
You are on page 1/ 2

Piyush Kumar 231302160

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

Program-
import java.util.Scanner;
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(System.in)
System.out.print("Enter the number of terms for Fibonacci series: ");
int n = scanner.nextInt();
System.out.println("\nFibonacci series using recursion:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacciRecursive(i) + " ");
}
Piyush Kumar 231302160

System.out.println("\nFibonacci series using non-recursion:");


for (int i = 0; i < n; i++) {
System.out.print(fibonacciNonRecursive(i) + " ");
}

scanner.close();
}
}
Output-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy