How to multiply two numbers without using Arithmetic(multiplication) operator?
Consider x and y are two integers whose values are 10 and 3 correspondingly. Adding x for y times gives the product of x and y.
Example: x = 10, y = 3
Adding x for y times => 10 + 10 + 10 = 30 is the product of 10 and 3.
Please check the below link to know about how to add two numbers without using addition operator.
Write a C program to multiply two numbers without using arithmetic operator.
/* addition of two numbers without using addition operator */
int addition(int a, int b) {
int carry;
while (b != 0) {
/* calculating the carry and do a left shift*/
carry = (a & b) << 1;
/* calculating the sum */
a = a ^ b;
b = carry;
}
return a;
}
int main () {
int num1, num2, res = 0, i;
/* get the input from the user */
printf ("Enter your first input:");
scanf("%d", &num1);
printf("Enter your second input:");
scanf("%d", &num2);
/*
* Adding num1 for num2 times gives the product
* value. Product of two numbers without using
* arithmetic operator.
*/
for (i = 0; i < num2; i++) {
res = addition(res, num1);
}
printf("product of %d and %d is %d\n", num1, num2, res);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:100
Enter your second input:35
product of 100 and 35 is 3500
Enter your first input:100
Enter your second input:35
product of 100 and 35 is 3500
For negative no. It work
ReplyDeleteIt won't work
DeleteIt won't work
Delete