# recursion

• 03-03-2004
student2005
recursion
Can someone please explain recursive to me?! I know that recursion is a function calling itself, but when it says
n = 4
Code:

```int funt1 (int n) { if (n == 0) { return 1; } else { Return 2* funt1 (n-1); }```
I think thats right. Im doing it by memory.
I am trying to write a program that takes a user input number and change the number into binary, octal, and the other one...lol. Its gotta have a class, a stack, and recursion.
• 03-03-2004
Salem
> I think thats right. Im doing it by memory.
Well post what you actually tried then.
• 03-03-2004
Ephraim
first call:
Code:

`funt1(4)`
Inside there:
Code:

`funt1(4) calls -> funt1(4-1) calls -> funt1(3-1) calls -> funt1(2-1) calls -> funt1(1-1)`
now we are at the special point with n == 0 (remember your if(n == 0) )
so the function returns a 1.
and every time it returns it will be multiplied by 2.
Code:

```funt1(4) -> funt1(4-1) -> funt1(3-1) -> funt1(2-1) -> funt1(1-1) 16 <- 2*      <- 2*        <- 2*        <- 2*        <- 1```
so you will get 2^4 which is16.

Hope it helped you :)

Ciao Ephraim
• 03-03-2004
major_small
ooh yay... another excuse to write a recursive function:
Code:

```double power(int num,int exp); ... double power(int num, int exp) {   if(exp==0)       return 1;   else if(exp>1)       return (num*power(num,exp-1));   else       return num; }```
it goes all the way in, and when exp becomes 1, it returns num, which is multiplied by num and returned to the parent, which is multiplied by num and returned to the parent, which is...
• 03-03-2004
Ephraim
Quote:

Code:

```double power(int num, int exp) {   if(exp==0)       return 1;   else if(exp>1)       return (num*power(num,exp-1));   else       return num; }```

Tricky :) but for what reason do you have the
if(exp == 0) there. You will never go into this section ;)
If Exp == 1 it not calls again the power but returns num.
and so the exp isn't subtracted by -1, so never come into
exp==0 section ;)

just kidding :)
I like this way of programming, so the brain can get really f***** :)

Ciao Ephraim
• 03-03-2004
major_small
there's no trick there... what is X^0?

this doesn' handle negative exponents well though...
• 03-03-2004
Ephraim
jep you are right :)
Forgotten this point. :(
and with the negative thing ...
I think you can just use an unsigned int as exp isn't it?!

Ciao Ephraim
• 03-04-2004
major_small
you could cast the exponent to an unsigned int, but what if they want to find out what x^-y is? they couldn't use this function (without modification) for it...