The Fibonacci numbers are a sequence of integers in which the first two elements are 1, and each following element is the sum of the two preceding elements. The first 12 Fibonacci numbers are: 1 1 2 3 5 8 13 21 34 55 89 144 Write a piece of code that uses a for loop to compute and print the first 12 Fibonacci numbers. (You may include other code, such as declaring variables before the loop, if you like.)

Respuesta :

Answer:

// program in java to print 12 fibonacci terms

// package

import java.util.*;

// class definition

class Main

{

   // main method of the class

public static void main (String[] args) throws java.lang.Exception

{

   try{

     

      // variables

      int no_of_term=12, f_term = 1, s_term = 1, n_term = 0;

      System.out.print("First 12 term of Fibonacci Series:");

      // print 12 terms of the Series

       for (int x = 1; x<= no_of_term; x++)

           {

       // Prints the first two terms.

            if(x <=2 )

            System.out.print(1+" ");

            else

            {

               // find the next term

                n_term = f_term + s_term;

                // update the last two terms

                f_term = s_term;

                s_term = n_term;

                // print the next term

              System.out.print(n_term+" ");

            }

           }

     

     

   }catch(Exception ex){

       return;}

}

}

Explanation:

Declare and initialize no_of_term=12,f_term=1,s_term=1 and n_term=0.Run a loop  for 12 times, for first term print 1 and then next term will be calculated as  sum of previous two term of Series.Then update previous two term.This will  continue for 12 time and print the terms of Fibonacci Series.

Output:

First 12 term of Fibonacci Series:1 1 2 3 5 8 13 21 34 55 89 144

ACCESS MORE