Reputation: 79
I'm trying to multiply two numbers using loops. The methods should be adding the numbers and then looping, to equal the two inputs multiplied together. The first one has to use while loops and here's what I have:
public static int wloopmultiply(int x, int y) {
int a = x;
while (x > 0) {
y = y + y;
a--;
}
Not really sure what's going on here and why it doesn't work. Any help? Also, I need to do the same thing but use recursion instead of while loops, and then finally use a for loop. Any hints for those? Thanks.
Upvotes: 0
Views: 8408
Reputation: 160
Loops will be like this:
int multiply(int x, int y){
int result = 0;
while(x > 0){
result += y;
x--;
}
return result;
}
we can call multiply(int x, int y)
like e.g. System.out.println(multiply(3,5));
Output: 15
Upvotes: 0
Reputation: 1177
Loops are very simple:
int multiply(int x, int y){
int res = 0;
while(x > 0){
res += y;
x--;
}
return res;
}
int multiply(int x, int y){
int res = 0;
for(int i = 0; i < x; i++){
res += y;
}
return res;
}
Here we will add one more y
on each step of recursion:
int multiply(x, y){
if(x == 0)
return 0;
return multiply(x - 1, y) + y;
}
These examples will work for positive integers and may cause int overflow. Try to improve them yourself ;)
Upvotes: 0
Reputation: 56
There are three issues
x
while decreasing the value of a
y=5
, so it's 5+5, next iteration y=10
, so it's 10+10)..
public static int wloopmultiply(int x, int y) {
int a = x-1;
while (a > 0) {
y = y + x;
a--;
}
return y;
}
These three changes should make it all work
Upvotes: 2
Reputation: 6360
The condition for your while
loop is that x > 0
, however you're decrementing a
in the loop body and x
is remaining unchanged, therefore will lead to an infinite loop.
Upvotes: 2