Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Fibonacci {
  4. // method to find nth term of fibonacci series
  5. public static int getFibonacciTerm(int n) {
  6. int a = 0, b = 1, temp = 1;
  7. if (n > 0) {
  8. while (--n > 0) {
  9. temp = b;
  10. b = a + b;
  11. a = temp;
  12. }
  13. return a;
  14. }
  15. return -1;
  16. }
  17. // method to print fibonacci series upto n terms
  18. public static void printFibonacciTerms(int n) {
  19. int a = 0, b = 1, temp = 1;
  20. while (n-- > 0) {
  21. System.out.print(a + " ");
  22. temp = b;
  23. b = a + b;
  24. a = temp;
  25. }
  26. System.out.println();
  27. }
  28. public static void main(String[] args) {
  29. int n = 0;
  30. Scanner in = new Scanner(System.in);
  31.  
  32. System.out.print("Enter the number of terms to print: ");
  33. // read the number of terms
  34. n = in.nextInt();
  35. System.out.println("Fibonacci series upto " + n + " terms: ");
  36. printFibonacciTerms(n);
  37.  
  38. System.out.print("Enter which term to print: ");
  39. // read which term to find from the series
  40. n = in.nextInt();
  41. System.out.println( n + "th Fibonacci term is: " + getFibonacciTerm(n));
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement