You can multiply two numbers without using the multiplication operator by using a simple loop to repeatedly add one of the numbers to a running total. Here's a Java program to achieve this:
java program to multiply given 2 numbers without multiplication operatorpublic class MultiplyWithoutOperator {
public static int multiply(int num1, int num2) {
int result = 0;
// Determine the sign of the result
int sign = (num1 < 0 ^ num2 < 0) ? -1 : 1;
// Make both numbers positive for simplicity
num1 = Math.abs(num1);
num2 = Math.abs(num2);
for (int i = 0; i < num2; i++) {
result += num1;
}
return sign * result;
}
public static void main(String[] args) {
int num1 = 5;
int num2 = 3;
int product = multiply(num1, num2);
System.out.println("Product: " + product);
}
}
In this program:
- We initialize a variable
result
to store the product. - We determine the sign of the result based on the signs of the input numbers using the XOR (
^
) operator. - We make both numbers positive by taking their absolute values to simplify the multiplication process.
- We use a loop to add
num1
toresult
num2
times. - Finally, we return the product with the appropriate sign.
Keep in mind that this approach is not the most efficient way to multiply numbers, especially for large numbers, but it demonstrates how multiplication can be achieved without using the multiplication operator.
Comments
Post a Comment