
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 (n1);
}
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.

> I think thats right. Im doing it by memory.
Well post what you actually tried then.

first call:
Inside there:
Code:
funt1(4) calls > funt1(41) calls > funt1(31) calls > funt1(21) calls > funt1(11)
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(41) > funt1(31) > funt1(21) > funt1(11)
16 < 2* < 2* < 2* < 2* < 1
so you will get 2^4 which is16.
Hope it helped you :)
Ciao Ephraim

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,exp1));
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...

Quote:
Code:
double power(int num, int exp)
{
if(exp==0)
return 1;
else if(exp>1)
return (num*power(num,exp1));
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

there's no trick there... what is X^0?
this doesn' handle negative exponents well though...

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

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...