Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Fibonacci {
- // method to find nth term of fibonacci series
- public static int getFibonacciTerm(int n) {
- int a = 0, b = 1, temp = 1;
- if (n > 0) {
- while (--n > 0) {
- temp = b;
- b = a + b;
- a = temp;
- }
- return a;
- }
- return -1;
- }
- // method to print fibonacci series upto n terms
- public static void printFibonacciTerms(int n) {
- int a = 0, b = 1, temp = 1;
- while (n-- > 0) {
- System.out.print(a + " ");
- temp = b;
- b = a + b;
- a = temp;
- }
- System.out.println();
- }
- public static void main(String[] args) {
- int n = 0;
- Scanner in = new Scanner(System.in);
- System.out.print("Enter the number of terms to print: ");
- // read the number of terms
- n = in.nextInt();
- System.out.println("Fibonacci series upto " + n + " terms: ");
- printFibonacciTerms(n);
- System.out.print("Enter which term to print: ");
- // read which term to find from the series
- n = in.nextInt();
- System.out.println( n + "th Fibonacci term is: " + getFibonacciTerm(n));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement