Write a C program to multiply two numbers using bitwise operator.
#include <stdio.h>
/* bitwiseAdd of two numbers without using addition operator */
int bitwiseAdd(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 val1, val2, output = 0, i;
/* get the input from the user */
printf ("Enter your first input:");
scanf("%d", &val1);
printf("Enter your second input:");
scanf("%d", &val2);
/*
* Adding val1 for val2 times gives the product
* value. Product of two numbers without using
* arithmetic operator.
*/
for (i = 0; i < val2; i++) {
output = bitwiseAdd(output, val1);
}
printf("product of %d and %d is %d\n", val1, val2, output);
return 0;
}
Please check the below link to get better understanding on this program.
/* bitwiseAdd of two numbers without using addition operator */
int bitwiseAdd(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 val1, val2, output = 0, i;
/* get the input from the user */
printf ("Enter your first input:");
scanf("%d", &val1);
printf("Enter your second input:");
scanf("%d", &val2);
/*
* Adding val1 for val2 times gives the product
* value. Product of two numbers without using
* arithmetic operator.
*/
for (i = 0; i < val2; i++) {
output = bitwiseAdd(output, val1);
}
printf("product of %d and %d is %d\n", val1, val2, output);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:55
Enter your second input:11
product of 55 and 11 is 605
Enter your first input:55
Enter your second input:11
product of 55 and 11 is 605
No comments:
Post a Comment