|
From: Robert A. <ral...@gm...> - 2005-11-09 01:39:09
|
Recursion works by solving a simpler problem. In the case above you know
that if you raise any number to the 1st power then you get that number back=
,
Otherwise you can get the result by multipling the number by the number
raised to the initial power minus one.
So if I am going to raise 10 to the third power ie pow(10,3)
pow(10,3)=3D10*pow(10,2)
pow(10,2)=3D10*pow(10,1)
pow(10,1)=3D10
So... now backing up as each function returns you get
pow(10,3)=3D10*10*10
On 11/8/05, Richard Gelling <use...@ya...> wrote:
>
> Hi,
>
> I am working my way through Sams Teach yourself c++ in 21 days and am
> having a bit fof difficulty with recursion, could someone explain to me
> how the following oiece of code works:
>
> #ifdef HAVE_CONFIG_H
> #include <config.h>
> #endif
>
> #include <iostream>
> #include <cstdlib>
>
> using namespace std;
>
> int toPowerOf( int , int );
> int main(int argc, char *argv[])
> {
> int powerOf, number, result;
> cout << "\nEnter the number: ";
> cin >> number;
> cout << "\nEnter the exponential: ";
> cin >> powerOf;
>
> result =3D toPowerOf( number, powerOf );
>
> cout << "\nThe result of " << number << " to the power of " <<
> powerOf << " is " << result << endl;
>
> return 0;
> }
> int toPowerOf( int number, int powerOf )
> {
> if ( powerOf =3D=3D 1 )
> return number;
> else
> {
> cout << "number is: " << number << " and the power of is " <<
> powerOf << endl;
> return ( number * toPowerOf( number, powerOf - 1 ));
> }
> }
>
> If someone could explain how the recusion side workd I would be
> gratefull, as I don't seem to be getting anywhere.
>
> Thanks a lot
>
> Richard G.
>
>
>
>
> -------------------------------------------------------
> SF.Net email is sponsored by:
> Tame your development challenges with Apache's Geronimo App Server.
> Download
> it for free - -and be entered to win a 42" plasma tv or your very own
> Sony(tm)PSP. Click here to play: http://sourceforge.net/geronimo.php
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|