Home > OS >  Need help making a function to take in an int N and make an array with N elements. Each element shou
Need help making a function to take in an int N and make an array with N elements. Each element shou

Time:05-06

Problem: Write a function that takes in an int n and returns a double[] of length n where the starting element (value) is 1.0 and the other elements are the previous divided by 2. For example, halves(4) should return a double[] with numbers {1.0, 0.5, 0.25, 0.125}. (JAVASCRIPT)

Stuck on where to continue, currently just have setting the array to length. Couldn't find any questions that already answered this.

void halves(int n){
    arrhalves[] n;
}

CodePudding user response:

If you are writing in JavaScript, define an array with only first element [1.0]. Then, define for-loop and loop over the array n times. Starting index should be 1 (because we already have one element in the array) and on each iteration push (arr[i - 1]) / 2 to the array.

  • Related