
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Fibonacci Series Using While Loop in Java
In this article, we'll generate the Fibonacci series using a while loop in Java. The Fibonacci series is a sequence where each number is the sum of the two previous numbers, starting with two initial numbers, usually either (0, 1) or (1, 1). Here, we start with (1, 1) and use a while loop to print the next numbers in the sequence until a specified limit.
Steps to print the Fibonacci series using while loop
Following are the steps to print the Fibonacci series using the while loop ?
- Define a class and initialize three variables: a and b for the first two numbers in the series, and c for the next number.
- Set the number of Fibonacci numbers to be printed (n).
- Print the first two numbers of the Fibonacci series.
- Enter a while loop to keep generating and printing the next Fibonacci number by adding the last two numbers (a and b).
- In each iteration of the loop: Calculate the next number c as the sum of a and b and print c.
- Update a and b to hold the two most recent numbers.
- Increment the loop counter until the desired number of Fibonacci numbers is printed.
Java program to print the Fibonacci series using while loop
Below is the Java program to print the Fibonacci series of a given number using while loop ?
public class FibonacciSeriesWithWhileLoop { public static void main(String args[]) { int a, b, c, i = 1, n; n = 10; a = b = 1; System.out.print(a+" "+b); while(i< n) { c = a + b; System.out.print(" "); System.out.print(c); a = b; b = c; i++; } } }
Output
1 1 2 3 5 8 13 21 34 55 89
Code explanation
In the above code, we start by declaring the variables a, b, c, and i. We initialize both a and b to 1, representing the first two Fibonacci numbers, and set i to 1, which will help us control the loop. The variable n is set to 10, which specifies how many Fibonacci numbers to print.
Inside the while loop, we calculate the next number c by adding a and b. Then we print c, update a and b to hold the two latest numbers, and increment i. The loop continues until we have printed n Fibonacci numbers. The output shows the Fibonacci series starting from 1, 1, followed by the subsequent numbers like 2, 3, 5, and so on.