Having problems with completing this code to a working program and running it. What is the final value of sum? What is the value of i when the loop terminates?

public class SumLargestToSmallest {
    int n = 2147483647;
    float old_sum = (float) 0.0;
    float sum = (float) 1.0; // already added 1.0/i for i = 1
    int i = 1;
    while (i <= n && sum != old_sum) {
        i = i+1;
        old_sum = sum;
        sum = sum + (float) (1.0 / i);
    }
    println(i);
    println(sum);
}

Recommended Answers

All 4 Replies

int n = 2147483647;

i think this extends the range of integer data type

Exactly what problems are you having in running this? All you need is a one-line main method. What did you try?
ps 2147483647 is the largest valid value for an int.

It cannot print the line. Invalid method declaration.

Found the error. It was meant to be System.out.println(i); hehe =]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.