Search code examples
javasimulate

How to simulate multiplication by addition java


I need to simulate multiplication by addition by not using the operator of multiplication such as asterisk This is my code trial code but seems not working :(

while (sum < a + b) { 
sum += a; 
} 

System.out.println (a+" x "+b+" is "+sum); 
} 
}

Solution

  • The code you have:

    sum = 0;
    while (sum < a + b) { 
        sum += a; 
    }
    

    will only add a to the sum until the sum becomes a + b. You would need to use a * b in the while loop in that case but, as stated, you're not allowed to.


    Since multiplication is just repeated addition, you can do it with the following (pseudo-) code:

    a = 5; b = 4
    
    product = 0
    acopy = a
    while acopy > 0:
        product = product + b
        acopy = acopy - 1
    

    That's the basic idea though it has a rather nasty bug for negative numbers.

    If you want to handle that as well, you'd need something like:

    product = 0
    acopy = a
    while acopy < 0:
        product = product - b
        acopy = acopy + 1
    while acopy > 0:
        product = product + b
        acopy = acopy - 1
    

    Only one of those while loops will run, depending on whether a is negative or positive (if it's zero, neither will run).