Write a program to generate Fibonacci series of limit number of elements.





Following are the test cases

Test cases Result Status
generateFibSeries(5) {0,1,1,2,3} Ok
generateFibSeries(7) {0,1,1,2,3,5,8} Ok
generateFibSeries(10) {0,1,1,2,3,5,8,13,21,34} Ok

Java solution


public class Program11 {
	public static void main(String[] args) {
		Program11.generateFibSeries(5);
		Program11.generateFibSeries(7);
		Program11.generateFibSeries(10);
	}
	public static int[] generateFibSeries(int limit){
		int f = 0;
	    int g = 1;
	    int array[] = new int[limit];
	    for (int i = 0; i < limit; i++) {
	        array[i] = f;
	        f = f + g;
	        g = f - g;
	    } 
	    return array;
	}
}

Javascript solution


const generateFibSeries = (limit) => {
    let first = 0;
    let second = 1;
    let array = [];
    for (let index = 0; index < limit; index++) {
        array.push(first);
        first = first + second;
        second = first - second;
    }
    return array;
}

console.log(generateFibSeries(5)); //[0,1,1,2,3]
console.log(generateFibSeries(7)); //[0,1,1,2,3,5,8]
console.log(generateFibSeries(10)); //[0,1,1,2,3,5,8,13,21,34]




About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *