In: Computer Science
Write a method sumTo 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 print an error message and return -1 if passed a value less than 0.
Include a loop.
Please help for Java programming.
If you have any queries please comment in the comments section I will surely help you out and if you found this solution to be helpful kindly upvote.
Solution :
Code:
import java.util.*;
public class HelloWorld
{
// function sumTo
public static float sumTo(int n)
{
// initialize sum as 0
float sum=0;
// if n is less than 0 then return -1
if (n<0)
{
return -1;
}
// otherwise run a loop from 1 to n
else
{
for(int i=1;i<=n;i++)
{
// add 1/i in each iteration
sum = sum + (1/(float)i);
}
// return the sum
return sum;
}
}
//main function
public static void main(String []args)
{
// make an object of Scanner class
Scanner sc = new Scanner(System.in);
// input an integer
int n = sc.nextInt();
// call the function
float res = sumTo(n);
// if the res is -1 then print error
if (res==-1)
{
System.out.println("Error");
}
// otherwise print the value of res
else
{
System.out.println(res);
}
}
}
Output :