next up previous
Next: Example: power by means Up: Unit 06 Previous: Example of nested loop:

Example: power by means of a nested loop

public static int power(int base, int exponent) {
  int result = 1;
  int multiplicand, multiplicator, product;

  while (exponent > 0) {
    exponent--;

    // result = result * base
    multiplicand = result;
    multiplicator = base;
    product = 0;
    while (multiplicator > 0) {
      multiplicator--;
      product = product + multiplicand;
    }
    result = product;
  }
  return result;
}


next up previous
Next: Example: power by means Up: Unit 06 Previous: Example of nested loop: