C Program to Multiply Two Numbers Without Using Arithmetic Operator
Multiplication is normally performed using the '*' operator in C. However, in some programming challenges and interviews, you may be asked to multiply two numbers without using the multiplication operator.
This can be achieved using repeated addition or bitwise operations. In this tutorial, we will explore different approaches with clear explanations and examples.
1. Understanding the Problem
We need to multiply two integers without using the '*' operator.
Example: Input: 4 and 3 Output: 12 Because 4 × 3 = 4 + 4 + 4 = 12
So multiplication can be treated as repeated addition.
2. Algorithm Using Repeated Addition
Step-by-step algorithm:
1. Read two numbers a and b.
2. Initialize result = 0.
3. Repeat addition of 'a' exactly 'b' times.
4. Store the final sum in result.
5. Print result.
3. C Program Using Repeated Addition
#include <stdio.h>
int main() {
int a, b, result = 0, i;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
for(i = 0; i < b; i++) {
result += a;
}
printf("Multiplication result = %d\n", result);
return 0;
}
Input: 4 3 Output: Multiplication result = 12
4. Handling Negative Numbers
If one of the numbers is negative, the result should also be negative.
We convert negative numbers to positive for calculation and adjust the sign at the end.
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, b, result = 0, i;
int negative = 0;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
if(a < 0) {
a = abs(a);
negative = !negative;
}
if(b < 0) {
b = abs(b);
negative = !negative;
}
for(i = 0; i < b; i++) {
result += a;
}
if(negative)
result = -result;
printf("Multiplication result = %d\n", result);
return 0;
}
5. Using Bitwise Operators (Efficient Method)
Another advanced method is using bitwise operators. This method is similar to the binary multiplication technique.
Algorithm:
1. Initialize result = 0.
2. While b > 0:
- If last bit of b is 1, add a to result.
- Left shift a (a <<= 1).
- Right shift b (b >>= 1).
#include <stdio.h>
int main() {
int a, b, result = 0;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
while(b > 0) {
if(b & 1)
result += a;
a <<= 1;
b >>= 1;
}
printf("Multiplication result = %d\n", result);
return 0;
}
6. Time Complexity
Repeated Addition Method → O(n)
Bitwise Method → O(log n)
The bitwise method is more efficient for large numbers.
7. Common Mistakes
1. Not handling negative numbers.
2. Infinite loop when b is negative.
3. Forgetting to initialize result = 0.
Conclusion
Multiplying two numbers without using the '*' operator can be done using repeated addition or bitwise operations. The repeated addition method is simple and easy to understand, while the bitwise method is more efficient.
Understanding these approaches strengthens your knowledge of loops, bitwise operators, and algorithm design in C programming.
Codecrown