logo CodeStepByStep logo

numberSequence

Language/Type: C++ recursion
Author: Marty Stepp (on 2016/07/03)

Write a recursive function named numberSequence that accepts an integer n as a parameter and prints a sequence of n integers, descending from n to 1 and then ascending back from 1 to n as in the table below:

Call Output
numberSequence(1); 1
numberSequence(2); 1 1
numberSequence(3); 2 1 2
numberSequence(4); 2 1 1 2
numberSequence(5); 3 2 1 2 3
numberSequence(6); 3 2 1 1 2 3
numberSequence(7); 4 3 2 1 2 3 4
numberSequence(8); 4 3 2 1 1 2 3 4
numberSequence(9); 5 4 3 2 1 2 3 4 5
numberSequence(10); 5 4 3 2 1 1 2 3 4 5

Notice that for odd numbers the sequence has a single 1 in the middle while for even values it has two 1s in the middle.

Your function should throw an int exception if passed a value less than 1.

Type your C++ solution code here:


This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.