Write a method sum To that accepts an integer parameter n an

Write a method sum To that accepts an integer parameter n and returns the sum of the first n reciprocals. In other words: sumTo(n) returns: 1 + 1/2 + 1/3 + 1/4 +...+ 1/n For example, the call of sumTo(2) should return 1.5. The method should return 0.0 if passed the value 0 and should throw an IllegalArgument Exception if passed a value less than 0. This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

Solution

Here is code:

public static double sumTo(int n ){
// if n is less then 0
if(n<0){
throw new IllegalArgumentException();
}
else if (n==0){ // if n is equal 0
return 0.0;
}
else{ // return sum of reciprocals
double sum = 0;
for(int i=1;i<=n;i++)
{
sum += (double)1/i;
}
return (sum);
}

 Write a method sum To that accepts an integer parameter n and returns the sum of the first n reciprocals. In other words: sumTo(n) returns: 1 + 1/2 + 1/3 + 1/4

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site