logo CodeStepByStep logo

printRange

Language/Type: C++ recursion
Author: Marty Stepp (on 2016/06/16)

Write a recursive function named printRange that accepts integer parameters x and y and prints the sequential integers between x and y inclusive in a particular format. The first half should be printed with the greater-than character (">") separating consecutive values. The second half should be printed with the less-than character ("<") separating consecutive values. When there are two values in the middle of the range, those two values should be separated by a pair of dashes ("--"), as shown in the second example output below. The following table shows several calls and their expected output:

Call Output
printRange(1, 9); 1 &gt; 2 &gt; 3 &gt; 4 &gt; 5 &lt; 6 &lt; 7 &lt; 8 &lt; 9
printRange(1, 10); 1 &gt; 2 &gt; 3 &gt; 4 &gt; 5 -- 6 &lt; 7 &lt; 8 &lt; 9 &lt; 10
printRange(23, 29); 23 &gt; 24 &gt; 25 &gt; 26 &lt; 27 &lt; 28 &lt; 29
printRange(13, 14); 13 -- 14
printRange(-8, -8); -8

Notice that in the first output, 5 is in the middle with the numbers before it separated by greater-than and the numbers after it separated by less-than. In the second output, 26 is in the middle with numbers before it separated by greater-than and numbers after it separated by less-than. The last output has no separators because that range includes one number.

Your function should throw an integer exception if x is greater than y.

Constraints: Do not declare any global variables. Also, do not use any loops; you must use recursion. You are allowed to define other "helper" functions if you like; they are subject to these same constraints.

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

Need help?

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.