|
|
 |
|
|
Pages: 1
Tips on recursive functions.
(Click here to view the original thread with full colors/images)
Posted by: Freak
Is there a way out of this hell?
I get questions like "Calculate the output of these Recursive functions"
And I have to repeat function like 20 times and THEN I have to add it all up !
WTF!
Ok so now I have to write my own recursive function involving some ridiculous sum...Use recursive functions to calculate the sum of the elements in this array m[40] when elements progress in a linear fashion (eg. 2,4,6,8,10)
AHHHHHHHH!
Ok...so my question is, is there a way to think up recursive functions without getting my brain tied in loops over and over again?
Posted by: Outlaw
WTF are you talking about? 
Is there a program you have to use or something?
Posted by: Freak
Oops sorry. I am talking about writing a simple newbie program in C++
I'm such a newb, I can't even imagine what kind of stuff real programmers do.
Posted by: Kdr Kane
You could always put an output statement in your recursive function to show you what's going on.
For example:
Code:
// factorial.cpp
//
#include <iostream>
using namespace std;
double factor(double n);
int usage(void);
int main(int argc, char *argv[])
{
double n;
if(argc !=2)
return usage();
(double) n = atof(argv[1]);
if((n > 30) || (n < 1))
return usage();
cout << n << " factorial = " << factor(n);
return 0;
}
int usage(void)
{
cout << "Usage: factor number\n";
cout << "\'number\' must be greater than zero and no more than 30.\n\n";
return 1;
}
double factor(double n) // RECURSIVE FUNCTION
{
double ans;
if (n == 1)
return 1;
ans = factor(n - 1) * n;
cout << ans << '\n'; // ADD THIS TO SEE THE OUTPUT **
return ans;
}
That is...
unless your teacher wants you to do it by hand. They don't, do they??
Posted by: Freak
Hmm.. thanks.
That was a good example on how to write a recursive function...subbing an A for the function (n-1) * n.
|
|
|
|
|