//Hi all ,can you explain why does this functon has two returns?
//How to read them? Is it like if/else?
int _tmain(int argc, _TCHAR* argv[])
{
    int x, n;
    int res;
    int power(int, int);
    cout << "Enter a number:";
    cin >> x;
    cout << "Enter a power:";
    cin >> n;
    res = power(x, n);
    cout << "X^N is:" << res << endl;


    return 0;
}


  int power(int x, int n)
{

     if (n == 0)
         return 1;

     if (n % 2 == 0)
     return power(x*x, n / 2);
     return power(x*x, n / 2)*x;

}

Recommended Answers

All 2 Replies

The power function has three returns. The first is inside the first if, the second (which is wrongly indented) is inside the second if and the third is outside of any if. The third will only execute if none of the previous ifs were executed (just like the second will only execute if the first did not execute (and the if condition is true, of course)), so you can think of it as being inside an implicit else, yes.

Also n % 2 is modulus division. Here, it only = 0 for mulitiples of 2.

Ex: 2, 4, 6, 8, 10, etc...

Modulus division is the remainder part of dividing two numbers.

ex:

5 / 2 = 2 remainder 1

so, 5 % 2 = 1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.