Fibonacci Series Program in Java using Loops

What is Fibonacci Series?

In Fibonacci series, next number is the sum of previous two numbers. The first two numbers of Fibonacci series are 0 and 1.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Using For Loop

  1. //Using For Loop
  2. public class FibonacciExample {
  3. public static void main(String[] args)
  4. {
  5. // Set it to the number of elements you want in the Fibonacci Series
  6. int maxNumber = 10;
  7. int previousNumber = 0;
  8. int nextNumber = 1;
  9. System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
  10. for (int i = 1; i <= maxNumber; ++i)
  11. {
  12. System.out.print(previousNumber+" ");
  13. /* On each iteration, we are assigning second number
  14. * to the first number and assigning the sum of last two
  15. * numbers to the second number
  16. */
  17. int sum = previousNumber + nextNumber;
  18. previousNumber = nextNumber;
  19. nextNumber = sum;
  20. }
  21. }
  22. }
Program Logic:
  • previousNumber is initialized to 0 and nextNumber is initialized to 1
  • For Loop iterates through maxNumber
    • displays the previousNumber
    • calculates sum of previousNumber and nextNumber
    • updates new values of previousNumber and nextNumber

Using While Loop

You can also generate Fibonacci Series using a While loop in Java.
  1. //Using While Loop
  2. public class FibonacciWhileExample {
  3. public static void main(String[] args)
  4. {
  5. int maxNumber = 10, previousNumber = 0, nextNumber = 1;
  6. System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
  7. int i=1;
  8. while(i <= maxNumber)
  9. {
  10. System.out.print(previousNumber+" ");
  11. int sum = previousNumber + nextNumber;
  12. previousNumber = nextNumber;
  13. nextNumber = sum;
  14. i++;
  15. }
  16. }
  17. }
The only difference in the program logic is use of WHILE Loop

Fibonacci Series Based On The User Input

  1. //fibonacci series based on the user input
  2. import java.util.Scanner;
  3. public class FibonacciExample {
  4. public static void main(String[] args)
  5. {
  6. int maxNumber = 0;
  7. int previousNumber = 0;
  8. int nextNumber = 1;
  9. System.out.println("How many numbers you want in Fibonacci:");
  10. Scanner scanner = new Scanner(System.in);
  11. maxNumber = scanner.nextInt();
  12. System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
  13. for (int i = 1; i <= maxNumber; ++i)
  14. {
  15. System.out.print(previousNumber+" ");
  16. /* On each iteration, we are assigning second number
  17. * to the first number and assigning the sum of last two
  18. * numbers to the second number
  19. */
  20. int sum = previousNumber + nextNumber;
  21. previousNumber = nextNumber;
  22. nextNumber = sum;
  23. }
  24. }
  25. }
Program Logic:
The logic is same as earlier. Instead of hardcoding the number of elements to show in Fibonacci Series, user is asked for the same

No comments:

Post a Comment