What is wrong with the following function?
void power (int x, int y, int result)
{
result = 1;
while (y > 0)
{
result = result * x;
y --;
}
}
I believe it's because the while loop is not with the void power (int x, int y, int result). Doesn't the while loop have to be with that in order for the loop to work? Any help or input would be appreciated.
looks to me like its trying to be a tail recurive function. My teacher didnt go over them closely. But the idea was the answer was passed down through each step. but i think you would need something like this.
void power (int x, int y, int& result)
so pass in result by reference. it would still be a void function though
If you put a & in there, it means that the argument and parameter are the same. With int& result, when you modify result, you're modifying the variable that was actually passed to the function, whereas without that you're modifying copies, which the function caller will never see.
In other words:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void power (int x, int y, int result)
{
result = 1;
while (y > 0)
{
result = result * x;
y --;
}
}
int main()
{
int result;
power (2, 2, result);
cout << result;
return 0;
}
Will do nothing, because the 'result' variable in main() is never modified by power() (it just made it's own copy and modified that) while:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void power (int x, int y, int& result)
{
result = 1;
while (y > 0)
{
result = result * x;
y --;
}
}
int main()
{
int result;
power (2, 2, result);
cout << result;
return 0;
}
Will return 4, because the 'result' variable in power() is actually the same thing as the one in main(), not a copy.
Generally though, we wouldn't use references like this. It's much easier and expected to do it with return values:
1 2 3 4 5 6 7 8 9 10 11
int power (int x, int y)
{
result = 1;
while (y > 0)
{
result = result * x;
y --;
}
return result;
}
This way we can use the main() function like this: