could anyone make me go through this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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; }

3rd Dec 2019, 5:18 AM
Dipanjan Basu
Dipanjan Basu - avatar
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.
3rd Dec 2019, 5:30 AM
A͢J
A͢J - avatar
+ 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.
3rd Dec 2019, 5:55 AM
Avinesh
Avinesh - avatar
0
Bro I am learning C++ I am not getting how the loop is working here for the result hence the question
3rd Dec 2019, 5:32 AM
Dipanjan Basu
Dipanjan Basu - avatar
0
Thanks bro, what about the for loop?
3rd Dec 2019, 5:58 AM
Dipanjan Basu
Dipanjan Basu - avatar
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.
3rd Dec 2019, 6:05 AM
Avinesh
Avinesh - avatar
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; }
5th Dec 2019, 1:14 AM
Claide Alexis Tendido
Claide Alexis Tendido - avatar