Exercise Fibonacci (Loop) ~ Programming is Fun
 Programming is Fun!

www.anandsingh.net
Subscribe For Free Updates!

We'll not spam mate! We promise.

Saturday, September 6, 2014

Exercise Fibonacci (Loop)

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
Hints:
public class Fibonacci {
   public static void main (String args[]) {
      int n = 3;          // the index n for F(n), starting from n=3
      int fn;             // F(n) to be computed
      int fnMinus1 = 1;   // F(n-1), init to F(2)
      int fnMinus2 = 1;   // F(n-2), init to F(1)
      int nMax = 20;      // maximum n, inclusive
      int sum = fnMinus1 + fnMinus2;
      double average;
 
      System.out.println("The first " + nMax + " Fibonacci numbers are:");
      ......
 
      while (n <= nMax) {
         // Compute F(n), print it and add to sum
         ......
         // Adjust the index n and shift the numbers
         ......
      }
 
      // Compute and display the average (=sum/nMax)
      ......
   }
}
Tribonacci numbers are a sequence of numbers T(n) similar to Fibonacci numbers, except that a number is formed by adding the three previous numbers, i.e., T(n)=T(n-1)+T(n-2)+T(n-3)T(1)=T(2)=1, and T(3)=2. Write a program called Tribonacci to produce the first twenty Tribonacci numbers.


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

0 comments:

Post a Comment