Fibonacci Series
This program prints Fibonacci series using while loop.
Problem Statement
Write a Java program that prints first 7 terms of Fibonacci series using while loop.
Source Code
| 1 | public class FibonacciWhile { |
| 2 | public static void main(String[] args) { |
| 3 | int n = 7, a = 0, b = 1, count = 2; |
| 4 | System.out.println(a + " - Eduinq"); |
| 5 | System.out.println(b + " - Eduinq"); |
| 6 | while(count < n) { |
| 7 | int c = a + b; |
| 8 | System.out.println(c + " - Eduinq"); |
| 9 | a = b; |
| 10 | b = c; |
| 11 | count++; |
| 12 | } |
| 13 | } |
| 14 | } |
Program Output
0 - Eduinq 1 - Eduinq 1 - Eduinq 2 - Eduinq 3 - Eduinq 5 - Eduinq 8 - Eduinq
Explanation
The program initializes first two terms of Fibonacci series as 0 and 1. It prints them, then uses a while loop to calculate next terms by adding previous two numbers. The loop continues until 7 terms are printed. This demonstrates how while loops can generate mathematical sequences. Shows how while loop can generate Fibonacci series.