malloz16
malloz16

Reputation: 79

Using Loops (in Java) to Multiply Numbers

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

Answers (4)

Rahul Srivastava
Rahul Srivastava

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

serhii
serhii

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

Moe
Moe

Reputation: 56

There are three issues

  1. Your looping over x while decreasing the value of a
  2. y = y + y; (First iteration, y=5, so it's 5+5, next iteration y=10, so it's 10+10).
  3. You need to add a return value to the end of the method

.

 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

m_callens
m_callens

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

Related Questions