I had to design a ruler using only recursion (no loops). The user puts in the ruler length and the depth(height) of the tick marks. I managed to build this just fine using simple for and while loops, but when I tried to translate it into recursion, I am having some trouble. I get a stack overflow and first chance exception at the end of running the file, BUT, just before the error kills it, I get the correct output. I’ve been using the test cases length: 4 and depth: 5, and length: 12 and depth: 3.
If anyone has an idea of how much I screwed up my recursive effort, I’m all ears.
#include <iostream>
#include <string>
using namespace std;
void solve (int, int, int, string, int);
int main()
{
int depth, length;
cout << "Enter a ruler length: ";
cin >> length;
cout << endl << "Enter a marking depth: ";
cin >> depth;
int i = 0;
string ruler = "";
int size = length * pow(2, (depth-1));
solve(length, depth, i, ruler, size);
int x;
cin >> x;
return 0;
}
void solve (int length, int depth, int i, string ruler, int size)
{
if (depth > 0)
{
int inc = pow(2, depth-1);
if (i <= (size))
{
if (i % inc == 0) {
cout << "|";
}
if (i % inc != 0) {
cout << " ";
}
solve (length, depth, ++i, ruler, size);
}
cout << "\n";
}
solve (length, depth-1, 0, ruler, size);
}
You need a return point from
solverecursion function, like: