Reputation:
I am trying to understand what my instructor wants me to do. In his description " Design, implement and test a Java program Multiplication.java which includes an iterative method multIterative and a recursive method multRecursive. Both methods take the same parameters, the two positive integer numbers that will be multiplied and return the multiplication result. For both methods, use the technique of repetitive additions for achieving the multiplication of the two numbers. As an example, 4 multiplied by 6 should be calculated as 6 + 6 + 6 + 6 (i.e. four times six)."
I can understand the multiplication for recursion but not the iterative. Does he want me to make factorials? or what? I need help understanding. Examples would help!
Upvotes: 0
Views: 2358
Reputation:
Alright then in recursion for my multRecursion() I did
public static int multRecursive(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
return multRecursive(a, b - 1) + a;
}
Upvotes: 0
Reputation:
Thanks, but I came up with something like this too. can this work for an Iterative as well?
public static int multIterative(int a, int b) {
if (b == 0) {
return 1;
} else if (b < 0) {
return 0;
}
return a * multIterative(a, b - 1);
}
Upvotes: 0
Reputation: 348
A while loop should do the trick
public int multiIterative(int firstNum, int secondNum){
int result;
while(secondNum > 0){
result += firstNum;
secondNum--;
}
return result;
}
Upvotes: 1