Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
June 15th, 2013, 04:10 AM
 arman.khandaker
Contributing User

Join Date: Jun 2013
Posts: 116
Time spent in forums: 16 h 51 m 33 sec
Reputation Power: 1
Help me understand this code

Here's the piece of code I am failing to grasp:
Code:
```int power(int base, int n)
{
int i, p;
p = 1;
for (i = 1; i <= n; ++i)
p = p * base;
return p;
}```

It's being used as a function for power. But I am not getting how this can raise the base to nth power. Please help me understand this code. Thanks

#2
June 15th, 2013, 05:09 AM
 salem
Contributed User

Join Date: Jun 2005
Posts: 4,260
Time spent in forums: 2 Months 4 Weeks 1 Day 15 h 3 m 57 sec
Reputation Power: 1827
2^1 = 2 = 2
2^2 = 4 = 2 * 2
2^3 = 8 = 2 * 2 * 2
2^4 = 16 = 2 * 2 * 2 * 2

Raising to the power of is just repeated multiplication.

Hence a for loop inside the code to do something n times.
__________________
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper

#3
June 17th, 2013, 11:18 AM
 arman.khandaker
Contributing User

Join Date: Jun 2013
Posts: 116
Time spent in forums: 16 h 51 m 33 sec
Reputation Power: 1
Quote:
 Originally Posted by salem 2^1 = 2 = 2 2^2 = 4 = 2 * 2 2^3 = 8 = 2 * 2 * 2 2^4 = 16 = 2 * 2 * 2 * 2 Raising to the power of is just repeated multiplication. Hence a for loop inside the code to do something n times.

Thanks a lot!

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Help me understand this code