logo CodeStepByStep logo

Sequence

Language/Type: VB recursion

Write a recursive subroutine named Sequence that accepts an integer k as its parameter and prints 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 ArgumentException.

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: Your solution must obey the following constraints:

  • Your solution must not use any loops; it must be recursive.
  • Do not construct any data structures (no list, dictionary, etc.), and do not declare any global variables. You are allowed to define other "helper" functions if you like.
Function: Write a VB 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.