# power function

• 11-05-2001
Unregistered
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
• 11-05-2001
kaviros
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;
}
• 11-05-2001
mix0matt
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...
• 11-06-2001
biterman
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.