Here is a C program to multiply two numbers using bitwise operators. Given two numbers as input from user, we have to multiply them without using arithmetic operators like * and +. In this program we will multiply two numbers by repetitive addition.
In other words, A X B is same as A + A + A... (B times).
For Example
5 X 4 = 5 + 5 + 5 + 5 = 20To add two numbers we are calling a user defined function 'add' that takes two number as input and add them using bitwise operators and returns the sum. To add to number(lets say A and B), we will keep on adding value of A to a sum variable using 'add' function till B times.
C program to multiply two numbers without using arithmetic operators
#include<stdio.h> int add(int num1, int num2); int main() { int num1, num2, product = 0, i; printf ("Enter first number\n"); scanf("%d", &num1); printf("Enter second number\n"); scanf("%d", &num2); /* Add num1 to itself, num2 times */ for (i = 0; i < num2; i++) { product = add(product, num1); } printf("Product of %d and %d is %d\n", num1, num2, product); return 0; } int add(int num1, int num2) { int carry; while (num2 != 0) { carry = (num1 & num2) << 1; /* calculating the sum */ num1 = num1 ^ num2; num2 = carry; } return num1; }Output
Enter first number 3 Enter second number 7 Product of 3 and 7 is 21
Related Topics