469,602 Members | 1,709 Online

# Calculating exponents without library functions

How can you write a program in C++ by using loop to control the calculation
without the use of library function pwr .For example 3 to the power of 4 (ie
3x3x3x3). Any help will be appreciated

Jul 22 '05 #1
3 6879
"David" <d_***@shaw.ca> wrote in message
news:7Ujec.78302\$Pk3.72421@pd7tw1no...
How can you write a program in C++ by using loop to control the calculation without the use of library function pwr .For example 3 to the power of 4 (ie 3x3x3x3). Any help will be appreciated

#include <iostream>

unsigned int pwr(unsigned int base, unsigned int exp)
{
unsigned int result = 1;

while(exp--)
result *= base;

return result;
}

int main()
{
std::cout << pwr(3, 4) << '\n';
return 0;
}
-Mike
Jul 22 '05 #2
Thanks a lot Mike for the solution

I am trying to do the the calculation without the use of built in pwr
function.I have to use the for or while loop with probably the counter

Thanks once again

David

"Mike Wahler" <mk******@mkwahler.net> wrote in message
"David" <d_***@shaw.ca> wrote in message
news:7Ujec.78302\$Pk3.72421@pd7tw1no...
How can you write a program in C++ by using loop to control the

calculation
without the use of library function pwr .For example 3 to the power of 4

(ie
3x3x3x3). Any help will be appreciated

#include <iostream>

unsigned int pwr(unsigned int base, unsigned int exp)
{
unsigned int result = 1;

while(exp--)
result *= base;

return result;
}

int main()
{
std::cout << pwr(3, 4) << '\n';
return 0;
}
-Mike

Jul 22 '05 #3
"David" <d_***@shaw.ca> wrote in message
news:X1nec.83152\$Ig.68204@pd7tw2no...
Thanks a lot Mike for the solution

I am trying to do the the calculation without the use of built in pwr
function.
There is no built-in function called 'pwr()' (however there
is one called 'pow()' declared by <cmath>

'pwr()' is the name of the function I wrote in my post.

I have to use the for or while loop with probably the counter

The function I posted uses a while loop with a counter.
(the 'counter' is the exponent parameter).

-Mike

Jul 22 '05 #4

### This discussion thread is closed

Replies have been disabled for this discussion.