Fibonacci Series in Java
Generate Fibonacci terms in Java by updating two integers in a for loop after Scanner input. Seven terms end at 8; large terms can overflow int.
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter number of terms: ");7 int n = sc.nextInt();89 int a = 0, b = 1;10 for (int i = 1; i <= n; i++) {11 System.out.print(a + " ");12 int c = a + b;13 a = b;14 b = c;15 }16 sc.close();17 }18}
Sample Output
Enter number of terms: 7 0 1 1 2 3 5 8
The printed a values are 0,1,1,2,3,5,8. At each step the pair shifts to the next two terms.
In this one
- Keep two consecutive sequence terms
- Save a sum before updating
- Distinguish term count from value limit
How it works
- 1
Read the number of terms n.
- 2
Start a = 0 and b = 1.
- 3
Print a and calculate c = a + b.
- 4
Move a to b and b to c for the next pass.
Edge cases
One term
Enter 1
Only 0 prints because that is the chosen first term.
No terms
Enter 0
The loop does not run. Negative counts are also not useful input for a sequence.
What's going on
Print a chosen number of Fibonacci terms. This sequence starts with 0 and 1, and every later term is the sum of the two before it. It is a useful exercise in updating related values without losing a value too early.
Scanner is the keyboard reader. a and b hold two consecutive terms. Each pass prints a, calculates c = a + b, then moves a to b and b to c. Saving c before changing a preserves both old terms needed for the addition. n is the number of terms, not the largest allowed value.
For n = 7, the output is 0, 1, 1, 2, 3, 5, 8. There are two ones because the rule produces them. Use a small positive n with this int version; large terms can overflow, which means they exceed the number type and give an incorrect stored value. Zero or negative n causes this loop to print no terms.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What follows 3 and 5?
Pick an answer to check it.
Question 2
What is the first printed term?
Pick an answer to check it.
Questions people ask
Why are there two ones?
The first 1 is given, and the next is 0 + 1.
Does n = 7 mean stop at value 7?
No. It means print seven terms, so 8 can appear.
Why calculate c before assigning a = b?
The addition needs the old a and old b. Updating too soon loses one of them.