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
Program Logic:
- //Using For Loop
- public class FibonacciExample {
- public static void main(String[] args)
- {
- // Set it to the number of elements you want in the Fibonacci Series
- int maxNumber = 10;
- int previousNumber = 0;
- int nextNumber = 1;
- System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
- for (int i = 1; i <= maxNumber; ++i)
- {
- System.out.print(previousNumber+" ");
- /* On each iteration, we are assigning second number
- * to the first number and assigning the sum of last two
- * numbers to the second number
- */
- int sum = previousNumber + nextNumber;
- previousNumber = nextNumber;
- nextNumber = sum;
- }
- }
- }
- 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.
- //Using While Loop
- public class FibonacciWhileExample {
- public static void main(String[] args)
- {
- int maxNumber = 10, previousNumber = 0, nextNumber = 1;
- System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
- int i=1;
- while(i <= maxNumber)
- {
- System.out.print(previousNumber+" ");
- int sum = previousNumber + nextNumber;
- previousNumber = nextNumber;
- nextNumber = sum;
- i++;
- }
- }
- }
The only difference in the program logic is use of WHILE Loop
Fibonacci Series Based On The User Input
Program Logic:
- //fibonacci series based on the user input
- import java.util.Scanner;
- public class FibonacciExample {
- public static void main(String[] args)
- {
- int maxNumber = 0;
- int previousNumber = 0;
- int nextNumber = 1;
- System.out.println("How many numbers you want in Fibonacci:");
- Scanner scanner = new Scanner(System.in);
- maxNumber = scanner.nextInt();
- System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
- for (int i = 1; i <= maxNumber; ++i)
- {
- System.out.print(previousNumber+" ");
- /* On each iteration, we are assigning second number
- * to the first number and assigning the sum of last two
- * numbers to the second number
- */
- int sum = previousNumber + nextNumber;
- previousNumber = nextNumber;
- nextNumber = sum;
- }
- }
- }
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