# recursive function

• 05-05-2003
brianptodd
recursive function
I am writing a recursive function that seems to work, but I have to also include a while loop to ask the user for the depth of the recursion. This is resulting in an endless loop.

Here is the code:

Code:

```  void recurse(int count, int depth);        //        function prototype  int main()  {         int depth;         cout << "Please enter a number for recursion depth, or -1 to exit: " << endl;         cin >> depth;         while (depth != depth *2)         {                 for (int counter = depth -(depth * 2); counter <= depth; counter++)                   {                                 recurse(counter, depth);                 }         cout << "Please enter a number for recursion depth, or -1 to exit: " << endl; }         return 0;         } void recurse(int count, int depth) {         if (count < 0)                 cout << "This was written by call number " << (count * -1) << "." << endl;         else if (count > 0)                 cout << "This was ALSO written by call number " << count << "." << endl;         else if (count == depth)                 return; }```
Any ideas on how to break from this while loop?
• 05-05-2003
thefroggy
Code:

`while (depth != depth *2)`
I haven't looked at the rest, but that is the source of your infinite loop.
• 05-05-2003
Magos
If you're just interested in a recursive call x number of times, then a while loop is not needed. Just pass an argument that gets decremented by 1 in each recursion.
Code:

```void Recurse(int Count) {   if(Count > 0) Recurse(Count - 1); } void StartRecursion() {   cin >> NrOfTimes;   Recurse(NrOfTimes); }```
• 05-05-2003
brianptodd
My program needs to print out something similar to this:

Get input from user for incursion depth of x = 5, so:

This was written by call number x.
This was written by call number x-1.
This was written by call number x-2.
This was written by call number x-3.
This was written by call number x-.4
This was ALSO written by call number x-4.
This was ALSO written by call number x-3.
This was ALSO written by call number x-2.
This was ALSO written by call number x-1.

My question is how to construct my while loop to prompt the user for another incursion depth, or a sentinel to exit.
• 05-05-2003
Magos
I don't know what a sentinel is...
You could use 0 as an exit condition though:
Code:

```int InputDepth; while(true) {   cin >> InputDepth;   if(InputDepth == 0) break;   Recurse(InputDepth); }```
• 05-05-2003
brianptodd
perfect! thanks Magos