Fibonacci Series Using While Loop

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones. It starts with 0 and 1, and the subsequent numbers are obtained by adding the previous two numbers. In this tutorial, we will explore how to generate the Fibonacci series using a while loop in Java.

Implementation in Java

To generate the Fibonacci series using a while loop in Java using BlueJ, we can follow the steps below:

  1. Create a class named FibonacciSeries.
  2. Inside the FibonacciSeries class, create a main method as the entry point of the program.
  3. Declare and initialize two variables, num1 and num2, with the initial values of the Fibonacci series (0 and 1).
  4. Print the initial two numbers of the series.
  5. Create a while loop with a condition to generate the series up to a certain limit or a specific number of terms.
  6. Inside the while loop, calculate the next number in the series by adding num1 and num2, and store it in a variable called nextNum.
  7. Print the nextNum.
  8. Update the values of num1 and num2 by shifting them to the right (num1 becomes num2, and nextNum becomes num2).
  9. Repeat steps 6-8 until the desired number of terms is generated.

Example Fibonacci series using a while loop in Java

public class FibonacciSeries {
public static void main(String[] args) {
int num1 = 0, num2 = 1;
System.out.print(“Fibonacci Series: ” + num1 + ” ” + num2);

int count = 10; // Number of terms to generate
int i = 2;
while (i < count) {
int nextNum = num1 + num2;
System.out.print(” ” + nextNum);
num1 = num2;
num2 = nextNum;
i++;
}
}

}

In the above code, we start with the initial two numbers of the Fibonacci series, 0 and 1. We print these numbers as the starting point of the series. Then, using a while loop, we calculate and print the next numbers in the series by adding the previous two numbers. The loop continues until we generate the desired number of terms (in this case, 10 terms).

When you run the above code, you will see the following output:

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Conclusion

In this blog post, we learned how to generate the Fibonacci series using a while loop in Java. By using a while loop, we can iteratively calculate the next numbers in the series and generate the desired number of terms. The Fibonacci series has applications in various fields, such as mathematics, computer science, and finance. It’s a fascinating sequence that exhibits interesting patterns and properties.

I hope this tutorial post has been helpful in understanding how to generate the Fibonacci series using a while loop in Java.

Happy coding!