i need to know how to use powers in c++. so if i enter to and then 3 for the power i get 8.

this is what i have so far

#include <iostream>
using namespace std;

double power(double,int);

int main()
{
    double n;
    int p;
    cout << "Enter a number ";
    cin >> n;
    cout << "Enter a power ";
    cin >>p;
    cout << power(n,p);
    return 0;   
}

double power(double n, int p)
{
 
 }

the function power is the part im having problems with i dont know what to put in it

thank you in advance

Recommended Answers

Have you tried multiplying p n times? Do you know about loops yet?

Jump to Post

It's called using a flow chart. Draw one for the code (presuming it works) and all should become clear.

Trace each step with your finger and write the results on paper.

Jump to Post

All 8 Replies

Have you tried multiplying p n times? Do you know about loops yet?

double power( double n, int p )       
{
double result = 1.0; 
for(int j=0; j<p; j++)
result *= n; 
return result;       
}

ok i got the loop i just dont understand it can some one explain it quick

It's called using a flow chart. Draw one for the code (presuming it works) and all should become clear.

Trace each step with your finger and write the results on paper.

>ok i got the loop i just dont understand it
Translation: I ganked this code, but I need to know how it works to get credit for my homework. ;)

>can some one explain it quick
What don't you understand? It's a simple loop that counts p times and continually updates the result by multiplying n into it.

You might, for the sake of clarity, want to chage

result *= n;   to  result = result * n;

>You might, for the sake of clarity, want to chage
>result *= n; to result = result * n;
Why? It's not like this is a huge stumbling point for beginners.

LOL not really ganked and its not for a class. but i did find the code in the back of the book.

well maybe ganked just a little =P

double power( double n, int p )       
{
double result = 1.0; 
for(int j=0; j<p; j++)
result *= n; 
return result;       
}

Suppose you send the value of n = 2 and power as 3 ie. p=3

Then the loop runs 3 times.
Each time it runs the result is multiplied by 2.

result = result * n;

This statement is executed p times multiplying the result with n.
This is how the power function works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.