|
![]() |
Overclock.net - Overclocking.net > Software, Programming and Coding > Coding and Programming > Application Programming | |
A little recursion c++ app.
|
||
![]() |
|
|
LinkBack | Thread Tools |
|
|
#1 (permalink) | ||||||||||||
|
Overclocker in Training
|
I wrote a recursion program in c++. It's a basic program to show how recursion works, all thought it could be commented a little better.
It prints a number and its factorial and then all the numbers that add up to its factorial as well. Code:
//recursion
#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
void instruct(void); //instructions function
unsigned long factorial ( unsigned long number);
unsigned long f_out ( unsigned long numb);
int
main(void)
{
instruct();
for ( int lol = 0; lol <= 50; lol++){
cout << setw ( 2 ) << lol << "! = " << factorial ( lol ) << setw( 5 ) << " = ";
f_out(lol);
cout << "n";
}
return 0;
}
unsigned long factorial( unsigned long number)
{
if ( number <= 1) // base case
return 1;
else
return number * factorial( number - 1 );
}
unsigned long f_out( unsigned long numb ) {
if ( numb <= 1 ) {
cout << "1";
return 1;}
else {
cout << numb << " * ";
return ( numb * f_out( numb - 1));
}
}
void
instruct()
{
cout << "Modify a factorial function to print its local variable and recursive call parameter.nn";
}
Last edited by .dp-BarackObama : 02-28-08 at 11:14 PM. |
||||||||||||
|
|
|
|
|
#2 (permalink) | |||||||||||||
|
Miscelaneous
|
Very nice, any chance you would do a C# version?
__________________
|
|||||||||||||
|
|
|
|
#3 (permalink) | ||||||||||||
|
Overclocker in Training
|
yeah ill try to get it up tomorrow.
|
||||||||||||
|
|
|
|
|
#4 (permalink) | |||||||||||||
|
Every base is base 10
|
Did you do that for a class or just for you? Recursion is powerful, but a factorial calculation is much better implemented in loop form
Just out of curiosity, why?
|
|||||||||||||
|
|
|
|
#5 (permalink) | |||||||||||||
|
Miscelaneous
|
I can do C++ but its a chore. Saves time for me to have a code in native C#.
__________________
|
|||||||||||||
|
|
|
|
#6 (permalink) | ||||||||||||
|
Overclocker in Training
|
did it for a class a while ago. thought i'd post it so people who don't know recursion. maybe it will help them understand better
|
||||||||||||
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
|
|