# Thread: power function

1. ## power function

ok so my Proffessor wants me to write a program that computers the power function using "for" to controll the calculations with out using the math.h library. and i have no idea how to start. any help would be appreciated.

thanks
jeff

2. ## Power using for

This code is not the faster but i think that it is very simple.

#include <stdio.h>

int main()
{
int pow,i;
double base,result;
result=1;
pow=GetInteger();
base=GetInteger();
for (i=1 ; i<=pow ; i++)
result=result * base;
printf("%g", result);
return 0;
}

3. here's the something that works, but realize that homework is there to help you learn. Giving up is never going to get you anywhere. You didn't show much effort. it's actually a policy of the board that homework should not be posted. enough lecture, but i think you could have solved this one.

Code:
```double power (double base, int pow)
{
if ( pow == 0 )
return 1;

double result = base;

for (int i = 1; i < pow; i++)
result *= base;

return result;
}```
i'll let you figure out negative exponents...

4. ## Here's another interesting little way to do it...

Code:
```float power(float m, float n)
{
if(n == 0)
return 1;
else
m *= power(m, (--n));
return m;
}```
It's so much more intricate, and yet it's not really complex. It's just recursive. This was actually of my first programs, i've always had the inexplicable tendency of making things more complex than they really are or should be, of doing things the harder way.

Oh well,
biterman.

Popular pages Recent additions