Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I add two numbers without using ++ or + or any other arithmetic operator in C/C++?
In this article we will see how to add two numbers without using arithmetic operators like +, ++, -, or --. This technique uses bitwise operations to simulate binary addition.
To solve this problem, we can use binary adder logic. In digital circuits, we design half adder and full adder circuits that can add one-bit binary numbers. By cascading multiple adders, we can create circuits to add bigger numbers.
In binary addition, we perform XOR operation for the sum bits, and AND operation for the carry bits. These principles are implemented here to add two numbers using only bitwise operators.
Syntax
int add(int a, int b) {
while (b != 0) {
int carry = a & b; // Find carry
a = a ^ b; // XOR for sum
b = carry << 1; // Shift carry left
}
return a;
}
How It Works
The algorithm works by simulating binary addition −
- XOR (^): Gives sum without carry (1+0=1, 0+1=1, 0+0=0, 1+1=0)
- AND (&): Finds positions where carry is generated (1+1=carry)
- Left Shift ( Moves carry to the next bit position
- Loop: Continues until no carry is left
Example
Here's a complete C program that adds two numbers without arithmetic operators −
#include <stdio.h>
int add(int a, int b) {
while (b != 0) { // Until there is no carry, iterate
int carry = a & b; // Find carry by ANDing a and b
a = a ^ b; // Perform XOR on a and b, store in a
b = carry << 1; // Shift carry one bit left, store in b
}
return a;
}
int main() {
int num1 = 15;
int num2 = 27;
printf("First number: %d\n", num1);
printf("Second number: %d\n", num2);
printf("Sum without + operator: %d\n", add(num1, num2));
return 0;
}
First number: 15 Second number: 27 Sum without + operator: 42
Step-by-Step Trace
Let's trace how add(15, 27) works −
| Step | a (binary) | b (binary) | carry | a ^ b |
|---|---|---|---|---|
| Initial | 01111 (15) | 11011 (27) | 01011 (11) | 10100 (20) |
| Step 1 | 10100 (20) | 10110 (22) | 10100 (20) | 00010 (2) |
| Step 2 | 00010 (2) | 101000 (40) | 00000 (0) | 101010 (42) |
| Final | 101010 (42) | 00000 (0) | Loop ends | |
Key Points
- This method works for both positive and negative numbers (two's complement)
- Time complexity is O(log n) where n is the larger number
- Space complexity is O(1)
- The algorithm mimics how processors perform addition at the hardware level
Conclusion
Adding numbers without arithmetic operators demonstrates fundamental binary addition using XOR for sum bits and AND with left shift for carry propagation. This technique forms the basis of how computers perform addition at the hardware level.
