469,602 Members | 1,709 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,602 developers. It's quick & easy.

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
news:8q*****************@newsread2.news.pas.earthl ink.net...
"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).

BTW please don't top post.

-Mike

Jul 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by 193.123.19.116 [Daz] | last post: by
2 posts views Thread by Stefan L | last post: by
6 posts views Thread by Patrick McGovern | last post: by
reply views Thread by devrayhaan | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.