Problem:
Fibonacci series are a type of series such that the value of an element is the sum of the 2 previous values for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,… it should always start with a 0 and 2 as the first 2 elements. Write a program that takes from the user a value N then display the elements of the series up to the nth element and print them.
Fibonacci: f(n) = f(n-1) + f(n-2)
Fibonacci: f(n) = f(n-1) + f(n-2)
Output:
Not needed.
Solution:
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many fib terms would you like to display? ");
int length = sc.nextInt();
int[] p = new int[length]; //set new array p equal the defined user length
printTerms( p, length ); //method to print terms
}
//method to populate and calculate array and fib sequence
public static int getNTerms( int[] p, int length ) {
//print first two terms
p[1] = 0;
p[2] = 1;
int newTerm = 0; //new value to calculate new terms on the sequence other that the first two
if ( length == 1 )
System.out.println(p[1]);
else if ( length == 2 )
System.out.println( p[1] + " " + p[2]);
else { //print rest of terms
System.out.print( p[1] + " " + p[2] + " ");
//for loop to calculate the rest of the terms
for ( int index = 3; index <= length; index++) {
newTerm = p[1] + p[2];
System.out.print( newTerm + " ");
p[1] = p[2];
p[2] = newTerm;
}
}
return newTerm;
}
public static void printTerms ( int[] p, int lenght ) {
System.out.print(getNTerms ( p, lenght ));
}
}
i was having problems solving the equation. and since this was a home assessment i could not take help from anywhere. but this post helps a great and thank you for updating
ReplyDelete