-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathFibonacci.java
More file actions
54 lines (47 loc) · 1.48 KB
/
Fibonacci.java
File metadata and controls
54 lines (47 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Write a program called Fibonacci to display the first 20 Fibonacci numbers F(n),
* where F(n) = F(n–1) + F(n–2) and F(1) = F(2) =1. Also compute their average.
*
* The output shall look like:
*
* The first 20 Fibonacci numbers are:
* 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
* The average is 885.5
*/
package javaexercises.flowcontrol;
/**
*
* @author User
*/
public class Fibonacci {
public static void main(String[] args) {
Fibonacci aFibonacci = new Fibonacci();
aFibonacci.printFiboacciAndAverage(20);
}
private void printFiboacciAndAverage(int n) {
long fb1 = 1;
long fb2 = 1;
long fbn = 0;
long sum = 0;
if (n <= 0) {
System.out.println("Please correct number of items and try again.");
return;
}
System.out.println("The first " + n + " Fibonacci numbers are:");
for(int i = 1; i <= n; i++) {
switch (i) {
case 1: fbn = fb1; break;
case 2: fbn = fb2; break;
default:
fbn = fb1 + fb2;
fb1 = fb2;
fb2 = fbn;
}
sum += fbn;
System.out.print(fbn + " ");
}
System.out.println();
System.out.printf("The sum is %1$d \n", sum);
System.out.printf("The average is %.4f \n", (double)sum / n);
}
}