0
could anyone make me go through this code?
double power (double n, int p =2) { double res = 1; int i; if (n==0) res = 0; else if (p==0) res = 1; else for (int i=1; i<=p; i++) res = res*n return res; }
6 Answers
+ 1
First complete your course then you can get what is going on here. You have just finished Html and SQL and this problem doesn't belong them.
+ 1
This function is finding the square of the number passed as "n".
If n=0 --> returned value res is 0
If n=some positive integer, then the function returns pow(n,2).
Notice: p==0 condition will never match since p=2 is initialized in the function argument.
0
Bro I am learning C++ I am not getting how the loop is working here for the result hence the question
0
Thanks bro, what about the for loop?
0
That for loop is only finding the square of the number "n" pasand in the argument.
See for example if your n=2.
And your p=2 always.
So i=1 and i<=p is true so res=1*2=2. Here "res" becomes 2 now.
Now after i++ now i=2 and i<=p is true so res=2*2=4.
So you can see you passed 2 and 2's square is 4.
0
could anyone make me go through this code?
double power (double n, int p =2)
{
double res = 1; int i;
if (n==0) res = 0;
else if (p==0) res = 1;
else
for (int i=1; i<=p; i++)
res = res*n
return res;
}