Skip to content

Instantly share code, notes, and snippets.

@sbsatter
Created August 18, 2016 21:17
Show Gist options
  • Save sbsatter/d67e92173da0c05d364c42bb2507b821 to your computer and use it in GitHub Desktop.
Save sbsatter/d67e92173da0c05d364c42bb2507b821 to your computer and use it in GitHub Desktop.
nth Fibonacci term and the sum till that term
import java.util.Scanner;
class Fibonacci{
public static void main(String ... args){
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number of terms you are interested in");
int n=sc.nextInt();
do{
System.out.println(n+"th term is "+fib(n));
System.out.println("And the sum is "+sum(n));
n=sc.nextInt();
}while(n!=-1);
}
static int fib(int n){
int fib=(n==0)?0:(n==1)?1:fib(n-2)+fib(n-1);
return fib;
}
static int sum(int n){
if(n==0){
return 0;
} if(n==1){
return 1;
}
return sum(n-1)+fib(n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment