In: Computer Science
QUESTION 15
We need to write a function that calculates the power of x to n e.g. power(5,3)=125.
Which of the following is a right way to define power function?
______________________________________________________________
int power(int a, int b) { int i=0, p=1; for(i=b;i>=1;i--) p*=a; return p; } ______________________________________________________________ |
||
int power(int a, int b) { int i=0, p=0; for(i=1;i<=b;i--) p=p*a; return p; } ______________________________________________________________ |
||
int power(int a, int b) { int i=0, p=1; for(i=b;i>=1;i--) a*=p; return p; } ______________________________________________________________ |
||
int power(int a, int b) { int i=0, p=1; for(i=a;i>=1;i--) p=p*b; return p; } ______________________________________________________________ |
Answer:
The right function that calculates power is--(first function)
int power(int a,int b)
{
int i=0, p=1;
for(i=b;i>=1;i--)
p*=a;
return p;
}
Explanation: Firstly i is initialized to 0 and p to 1.In the for loop i reinitialized to b and until it greater than or equal to 1 and decreases one and The power value which is p=p*a is stored in p variable and finally it returns power value.
Example: power(5,3) Here a=5 and b=3
When the for loop i=3,p=p*a=1*5=5
i=2,p=p*a=5*5=25
i=1,p=p*a=25*5=125
And i=0 and loop exists and returns p which is 125.
The remaining three functions are wrong.
The second function which is--
int power(int a,int b)
{
int i=0, p=0;
for(i=1;i<=b;i--)
p=p*a;
return p;
}
It is wrong every time multiply p which is 0 with a always gives 0 and 0 is returned So,It is WRONG.
The third function which is--
int power(int a,int b)
{
int i=0, p=1;
for(i=b;i>=1;i--)
a*=p;
return p;
}
It is wrong because calculating power value into a variable and returning p variable.
The fourth function which is--
int power(int a,int b)
{
int i=0, p=1;
for(i=a;i>=1;i--)
p=p*b;
return p;
}
It is wrong because we are taking base value as b to calculate power but are taking a.
Hope you understand and like the answer..
Thank you..