Monday, November 24, 2014

Java: Fibonaci series

public class Solution {

     public static void main(String args[])
   {
      int x=0, y=1, z, n;
 
      Scanner in = new Scanner(System.in); //Scanner object to scan/read the input data from console
        n=in.nextInt(); /* For integer we use nextInt method of scanner class, for string we can use next() or nextLine() methods*/

        System.out.println(x); //Printing first number of fibonaci

        System.out.println(y); // printing second number of fibonaci

        for(int i=2;i<=n;i++) /* we can start the loop from 2 or terminate it at n-2 iteration i.e. for(int i=1;i<=n-2;i++) since we have already printed first 2 numbers of fibonaci*/

            {
            z=x+y;
            x=y;
            y=z;
            System.out.println(z);
        }
   }
}

Input# 0-
8

Output# 0-
0 1 1 2 3 5 8 13<br /><div style="color: black; font-family: 'Times New Roman'; font-size: medium; line-height: normal; white-space: normal;"> <b>Input# 1-</b></div> <div style="color: black; font-family: 'Times New Roman'; font-size: medium; line-height: normal; white-space: normal;"> 10</div> <div style="color: black; font-family: 'Times New Roman'; font-size: medium; line-height: normal; white-space: normal;"> <br /></div> <div style="color: black; font-family: 'Times New Roman'; font-size: medium; line-height: normal; white-space: normal;"> <b>Output# 1-</b></div> <xmp style="margin-bottom: 0px; margin-top: 0px;">0 1 1 2 3 5 8 13 21 34<br />

No comments:

Post a Comment