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

    Join Date
    Jun 2013
    Location
    Dhaka, Bangladesh
    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
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,379
    Rep Power
    1871
    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
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Location
    Dhaka, Bangladesh
    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! :)

IMN logo majestic logo threadwatch logo seochat tools logo