### Thread: Help me understand this code

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2013
Location
Posts
116
Rep Power
2

#### 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. 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.
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2013
Location
Posts
116
Rep Power
2
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! :)