2

how can I populate an array with results from multiple operations like a harmonic sum: Harmonic= 1+1/2+1/3+1/4.......+1/n My incomplete version looks like this:

public static void main(String[] args) {
        int x=1, harmonic=0, y=2;
        int[] n;
        n = new int[];

       // for populating the array ?!?!?!
       do {n = {x/y}} 
       y++;
       while (y<=500);

       //for the sum for loop will do...
        for (int z=0; z<=n.length; z++){
             harmonic += n[z];
            }
        System.out.println("Harmonic sum is: " + harmonic);
    }
0

1 Answer 1

2

2 things... you should use a double data type since you dont wan t/need truncated values, and you should use for that collections instead of arrays.

public static void main(String[] args) {

    double x = 1, harmonic = 0, y = 2;
    List<Double> arc = new ArrayList<>();

    do {
        arc.add(x / y);
        y++;
    } while (y <= 500);

    for (Double double1 : arc) {
        harmonic += double1;
    }
    System.out.println("Harmonic sum is: " + harmonic);
}

the output will look like:

Harmonic sum is: 5.792823429990519

edit:

using streams:

double streamedHarmonic = arc.stream().mapToDouble(Double::doubleValue).sum();
Sign up to request clarification or add additional context in comments.

1 Comment

I am at the begining and still learning the basics, that's why I was trying to do it with arrays. I will study your solution. Thx a lot !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.