Fibonacci Series Program In Java

Fibonacci Series In Java:

The fibonacci series is a series where the next number is the sum of previous two numbers.  
for examples:  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc

above you can see first two numbers of fibonacci series are 0 and 1.


  Java Program to print fibonacci series:



import java.util.Scanner;

public class Fibonacci {

	public static void main(String[] args) {

		int num1 = 0, num2 = 1, num3, i, input;
		Scanner sc = new Scanner(System.in);
        
		//Getting input limit from user
		System.out.print("Enter limit: ");
		input = sc.nextInt();
		
        //printing num1 means 0 and num2 means 1
		System.out.print(num1+" "+num2);
		
        /*for loop starts from 2 because first two values
        means 0 and 1 are already printed*/
		for(i=2;i<input; i++) {
			num3 = num1+num2;
			System.out.print(" "+num3);
			num1=num2;
			num2=num3;
		}
		
		
	}
}

Above Program will show the following Output:

Enter limit: 10
0 1 1 2 3 5 8 13 21 34



  Fibonacci Series Program using while loop:



import java.util.Scanner;

public class Fibonacci {

	public static void main(String[] args) {

		int num1 = 0, num2 = 1, num3, i, input;
		Scanner sc = new Scanner(System.in);
		
        //Getting input limit from user
		System.out.print("Enter limit: ");
		input = sc.nextInt();
		
        //printing num1 means 0 and num2 means 1
		System.out.print(num1+" "+num2);
        
	/*while loop starts from 2 because first two values
        means 0 and 1 are already printed*/
		i = 2;
		while(i<input) {
		        num3 = num1+num2;
			System.out.print(" "+num3);
			num1=num2;
			num2=num3;
			i++;
		}
		
		
	}
}

Output:

Enter limit: 10
0 1 1 2 3 5 8 13 21 34



  Above Same Program using do-while loop:



import java.util.Scanner;

public class Fibonacci {

	public static void main(String[] args) {

		int num1 = 0, num2 = 1, num3, i, input;
		Scanner sc = new Scanner(System.in);
		//Getting input limit from user
		System.out.print("Enter limit: ");
		input = sc.nextInt();
		
        //printing num1 means 0 and num2 means 1
		System.out.print(num1+" "+num2);
        
		//do while loop 
		i = 2;
		do{
		    num3 = num1+num2;
			System.out.print(" "+num3);
			num1=num2;
			num2=num3;
			i++;
		}while(i<input);
		
		
	}
}

Output:

Enter limit: 10
0 1 1 2 3 5 8 13 21 34


Learn more about do-while loop in our C programming tutorials...



    Related Posts:


No comments:

Post a Comment

If you have any doubts, please discuss here...👇