next up previous
Next: Flow control statements Up: Unit 06 Previous: Example: power by means

Example: power by means of two methods

public static int multiplication(int multiplicand,
                                 int multiplicator) {
  int product = 0;
  while (multiplicator > 0) {
    multiplicator--;
    product = product + multiplicand;
  }
  return product;
}

public static int power(int base, int exponent) {
  int result = 1;
  while (exponent > 0) {
    exponent--;
    result = multiplication(result, base);
  }
  return result;
}

Note that in this case the internal loop is hidden inside the invocation of the multiplication() method.


next up previous
Next: Flow control statements Up: Unit 06 Previous: Example: power by means