Saturday, June 8, 2024

Write a Java program to generate the first n Fibonacci numbers

The Fibonacci series is a sequence of numbers in which each number (after the first two) is the sum of the two preceding ones. The sequence typically starts with 0 and 1, although some variations start with 1 and 1. The mathematical definition of the Fibonacci sequence is:

F(n)=F(n1)+F(n2)F(n) = F(n-1) + F(n-2)

With the initial conditions:

F(0)=0F(0) = 0 F(1)=1F(1) = 1

This means that:

F(2)=F(1)+F(0)=1+0=1F(2) = F(1) + F(0) = 1 + 0 = 1 F(3)=F(2)+F(1)=1+1=2F(3) = F(2) + F(1) = 1 + 1 = 2 F(4)=F(3)+F(2)=2+1=3F(4) = F(3) + F(2) = 2 + 1 = 3 F(5)=F(4)+F(3)=3+2=5F(5) = F(4) + F(3) = 3 + 2 = 5 \ldots

So, the beginning of the Fibonacci series looks like this:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The Fibonacci sequence has many interesting properties and appears in various areas of mathematics and nature, such as in the branching of trees, the arrangement of leaves on a stem, the fruit sprouts of a pineapple, the flowering of an artichoke, and the arrangement of a pine cone.

java program sample code: 

import java.util.Scanner;


public class Fibonacci {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of terms: ");

        int n = scanner.nextInt();

        scanner.close();

        

        int a = 0, b = 1, c;

        System.out.print("Fibonacci Series: " + a + " " + b);

        

        for (int i = 2; i < n; i++) {

            c = a + b;

            System.out.print(" " + c);

            a = b;

            b = c;

        }

    }

}


No comments:

Post a Comment