recursion why does it not work?

Apr 19, 2016 at 6:54pm
// Example program
#include <iostream>
#include <string>

using namespace std;

void rec(int);
int main()
{
int number;

cout << "enter the starting number to continue with" << endl;
cin >> number;

rec(number); // sends the number to the function



system("pause");
return 0;
}


int rec(number)
{

if (number > 0)
{
for (int i=0; i < number; i++)
{
cout << rec(number -1) << endl; // recursion occurs and sub from 1
}
return number;
}

else
cout << "countdown is done" << endl;
}
Last edited on Apr 19, 2016 at 7:05pm
Apr 19, 2016 at 6:55pm
why doesnt this not work, very confused by this?
Apr 19, 2016 at 8:30pm
why doesnt this not work, very confused by this?

If you want help when you receive an error message when trying to compile or link it is customary to let your potential helpers know the type of error you're dealing with (as opposed to the generic proclamation "it doesn't work") and also supply them with the exact text of the error which generally includes things like line numbers, function names and other helpful information like a brief description of what the compiler expected to be there.

You have some pretty basic syntax errors that I'm sure you could remedy yourself if you re-read whatever material you're learning from. Also, the definintion of rec doesn't match the forward declaration of rec, and there should be no loop in rec.

Apr 21, 2016 at 2:44am
#include <iostream>
#include <string>

using namespace std;

void rec(int);
int main()
{
int number;

cout << "enter the starting number to continue with" << endl;
cin >> number;

rec(number); // sends the number to the function

system("pause");
return 0;
}


void rec(int number)
{
cout << "Before" << number << endl;
if (number > 1)
rec(number -1) ; // recursion occurs and sub from 1
cout << "After" << number << endl;

}

///// Have fun buddy
Apr 21, 2016 at 8:41pm
thank you wolfycplusplus, found out the silly mistakes i made.
Topic archived. No new replies allowed.