Hello,
John Turnur wrote:
You need to run
val = x;
for(i =0; i < y ; i++) { val = x * val}
your answer is val
The initialisation for val should be val = 1;
For this simple method, y must be an integer value, and with this implementation, the value of y must be positive and non-zero. To handle y = 0, use a "while" loop, rather than a "for" loop.
val = 1;
while (y) { val *= x; y--; }
If x is an integer value, overflow can easily occur, so checking for this condition might be desireable. Overflow would be less of a problem if x is a floating point value. It should also be possible to accurately handle negative values of y.
val = 1.0;
if (y >= 0) {
while (y) { val *= x; y--; }
}
else {
while (y) { val /= x; y++; }
}
Regards,
Mac