Write a class FibonacciExample to accept a number and find its Fibonacci series value using do .. while

0

Assignment: Module 03- Part 01

Write a class FibonacciExample to accept a number and find its Fibonacci series value using do .. while
Assignment: Module 03- Part 01

10. Write a class FibonacciExample to accept a number and find its Fibonacci series value using do .. while

Input: 

Enter the no n 4

Output :

0

1

1

2

3

class FibonacciExample {
    void fibonacci(int n) {
        int a = 0, b = 1, c = 0;
        System.out.print(a + " " + b);
        do {
            c = a + b;
            System.out.print(" " + c);
            a = b;
            b = c;
            n--;
        } while (n > 0);
    }
}

public class Main {
    public static void main(String[] args) {
        FibonacciExample obj = new FibonacciExample();
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the no n: ");
        int n = sc.nextInt();
        obj.fibonacci(n);
    }
} 

In the above code, we create a class 'FibonacciExample' with a method 'fibonacci' which accepts an integer and prints the Fibonacci series of the number passed. In the main method, we create an object of the 'FibonacciExample' class, take input from the user for the number, then call the fibonacci method with the number passed as an argument. 

The output of the above code when the input is 4 is "0 1 1 2 3"

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.

In this example, I used a do-while loop to generate the Fibonacci sequence. The do-while loop runs at least once and then checks the condition, which means that it will always execute the loop body at least once.


👉Write a class CallByObject to accept two integer variable values and swap it👈

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
✨ Updates