logo CodeStepByStep logo

sumUpTo

Language/Type: JavaScript recursion

Write a recursive function named sumUpTo that accepts an integer parameter n, where sumUpTo(n) returns: 1 + 1/2 + 1/3 + 1/4 + ... + 1/n .

For example, the call of sumUpTo(2) should return 1.5. You should return 0.0 if n is 0, and you should throw an exception with the message, "n must be non-negative", if n is less than 0.

Note: Because JavaScript integers are number types, dividing two integers which do not divide evenly returns the decimal value of the result instead of an integer (for example, 1 / 2 results in 0.5, not 0). Use parseInt(a / b) to parse the result into an integer if needed to solve this problem.

Function: Write a JavaScript function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.