We learned implementing basic math calculation such as addition/subtraction/multiplication/division in the last week. Exponents is a little bit hard, but we can use Loop operation to implement an Exponent.

First of all, let’s figure out what the exponent is:

The **exponent** of a number says **how many times **to use the number in a multiplication.

5 powered by 3 = 5*5*5

we can see that there are 3 times exactly action of multiplication used in the calculation. This is a perfect requirement for loop.

Still look at the example 5 powered by 3 = 5*5*5, and we choose to use **for loop.** We can decide the maximum time as 3, which means we make the multiplication for 3 times. Every time, we do a simply 5*5. To initial the multiplication, we put an initial number as 1, the multiplication result is what we have to output:

pre-step: result = 1;

step 1: result = result in pre-step * 5 = 1 * 5;

step 2: result = result in step 1 * 5 = 5 * 5 = 25;

step 3: result = result in step 2 * 5 = 25 * 5 = 125;

** i **is the cursor to go up by 1 every time to point the step.

To make the display friendly, I insert some sytem.out.print to make you easily understand how loop works.

1) We still use the interface **MathCalculation** to declare the method **power:**

//integer exponents

public int power(int a, int b);

2) The implementation part is in * Calculator* class:

public int power(int a, int b) {

// TODO Auto-generated method stub

int result = 1;

System.out.println(“How do we calculate “+ a + ” powered by ” + b + “:”);

for(int i=0; i<b; i++){

System.out.print(“Step ” +i +”: “);

System.out.print(i+”<” + b +”? ” + (i<b) +” // “);

result = result*a;

System.out.print(” result = ” + result);

System.out.println();

}

return result;

}

3) We use **CalculatorHandler** to display the result:

//power

System.out.println(“intA powered by intB = ” + myCal.power(intA, intB));

4) The display is in the console:

intA = 5

intB = 3

How do we calculate 5 powered by 3:

Step 0: 0<3? true // result = 5

Step 1: 1<3? true // result = 25

Step 2: 2<3? true // result = 125

intA powered by intB = 125

5) You can try to give a different input for intA and intB to watch if the result is same as what you expected, and also what the action is in each step

Homework:

- do you wanna try to use loop to realize a multiplication