Implement multiplication with addition

We learned loop by implementing an Exponent in the last week. To practice for loop, we can use the addition to implement a multiplication.

We define a method in the interface MathCalculation

public int myMultiply(int a, int b);

To implement this method in class Calculator

public int myMultiply(int a, int b) {

// TODO Auto-generated method stub

}

How should we use the addition operation to realize myMultiply? let’s make an example:

5 x 3 = 5 + 5 + 5, if we put an initial value for this addition:

5 x 3 = 0 + 5 + 5 + 5

Same operation (addition) is repeated for 3 times, therefore, we can use loop.

public int myMultiply(int a, int b) {

// TODO Auto-generated method stub

int result = 0;

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

result = result + a;

}

return result;

}

We use this method in class CalculationHandler

public static void main(String[] args) {

// TODO Auto-generated method stub

Calculator myCalculator = new Calculator();

int inputA = 5;

int inputB = 3;

System.out.println(“inputA = “ + inputA);

System.out.println(“inputB = “ + inputB);

System.out.println(“myMultiply: inputA * inputB = “ + myCalculator.myMultiply(inputA, inputB));

System.out.println(“Multiply: inputA * inputB = “ + myCalculator.multiply(inputA, inputB));

}

Listing myMultiply and multiply two methods to compare the results. If they are same, then it proves myMultiply is a correct answer. Checking the console display:

Console display:

inputA = 5
inputB = 3
myMultiply: inputA * inputB = 15
Multiply: inputA * inputB = 15

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s