logo CodeStepByStep logo

sequence

Language/Type: JavaScript recursion

Write a recursive function named sequence that accepts an integer k as a parameter and outputs out the numbers 1 through k inclusive in a particular pattern separated by plus signs and wrapped in parentheses. The order of the numbers should begin with all of the evens in downward order, followed by all of the odds upward from 1. Each time a number is added to the pattern, a new set of parentheses and a plus sign are added to the pattern. If the value for k is 0 or negative, throw an exception with the message, "k must be greater than 0".

Call Output
sequence(1) 1
sequence(2) (2 + 1)
sequence(3) ((2 + 1) + 3)
sequence(4) (4 + ((2 + 1) + 3))
sequence(5) ((4 + ((2 + 1) + 3)) + 5)
sequence(6) (6 + ((4 + ((2 + 1) + 3)) + 5))
sequence(7) ((6 + ((4 + ((2 + 1) + 3)) + 5)) + 7)
sequence(8) (8 + ((6 + ((4 + ((2 + 1) + 3)) + 5)) + 7))
sequence(9) ((8 + ((6 + ((4 + ((2 + 1) + 3)) + 5)) + 7)) + 9)
sequence(10) (10 + ((8 + ((6 + ((4 + ((2 + 1) + 3)) + 5)) + 7)) + 9))

Constraints:

  • Do not declare any global variables.
  • Do not use any arrays to solve this problem.
  • Do not use any loops; you must use recursion.
  • Use console.log() to output your final sequence result (note that only one line is output).

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.