With Recursion
package com.physicsinfo;
import java.util.Scanner;
public class FibonacciCode{
static int n1=0, n2=1, n3=0;
static void fibonacci(int count){
if(count>0){
n3 = n1+n2;
System.out.print(n3+" ");
n1=n2;n2=n3;
count--;
fibonacci(count);
}
}
public static void main(String args[]){
System.out.print("Enter hwo many terms you want to see in the fibonacci series: ");
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
System.out.println("Here are the first "+count+" terms of the Fibonacci series:");
System.out.print(n1+" "+n2+" ");
fibonacci(count-2);
}
}
Without Recursion & using for loop
package com.physicsinfo;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
int n1=0, n2=1, n3, count;
System.out.print("Enter hwo many terms you want to see in the fibonacci series: ");
Scanner sc = new Scanner(System.in);
count = sc.nextInt();
System.out.println("Here are the first "+count+" terms of the Fibonacci series:");
System.out.print(n1+" "+n2+" ");
for(int i=2;i<count;i++){ //loop starts from 2 because 0 and 1 are already printed.
n3=n1+n2;
System.out.print(n3+" ");
n1=n2;n2=n3;
}
}
}
Related