NewUser101
NewUser101

Reputation: 151

recursive functions c++

I am writing a recursive function that has two functions, one to add numbers from 0 to 10 and then the other to retrieve the first function return value and subtract it until it reaches 0. Although, my code only adds them up 10 for the calls. Can someone shed some light. thanks.

#include <iostream>
#include <fstream>
using namespace std;

static int recurse(int count)
{

   cout << count << "\n";

   if (count < 10)
   {
      recurse(count + 1);
   }

   int aRet = count;
   return count;
}

static int minusRecusive(int minus)
{

   recurse(1);
   cout << "\n\t" << minus;
   int a =0;
   minus = recurse(a);

   if (minus < 1)
   {
      recurse(minus - 1);
   }

   return minus;
}


int main()
{
   minusRecusive(1);
   cin.get();
}

Upvotes: 0

Views: 243

Answers (1)

The Real Baumann
The Real Baumann

Reputation: 1961

Your recurse functions doesn't actually return the sum. If you call recurse(0) it will recurse into it 10x, but your return value would still be 0. Also, you're creating aRet but it's never used. Try the following...

if (count < 10) return count + recurse(count + 1);
return count;

Your minusRecursive function should be similar.

Upvotes: 1

Related Questions