//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;

3 Years
Discussion Span
Last Post by cgeier

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.


5 / 2 = 2 remainder 1

so, 5 % 2 = 1

Edited by cgeier

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.