Lets write a C program to perform addition of 2 numbers without using plus symbol or the addition operator(+).
In this video tutorial we are using ~(tilde symbol) bitwise complement operator to perform the operation to get to the anticipated result.
Example: If user enters 2 numbers. a = 8 and b = 7. To add 8 and 7 we use result = a + b. And the result will be 15. But in this C program we are not using plus(+) operation, but still we must get the same result 15(for above input).
If num = 7;
result = ~num; will give 1s complement of 7, that is -8.
result = -(~num); will give 8.
result = -(~num)-1; will give 7.
Now using this logic, we ask the user to enter 2 numbers. If user enters a = 8 and b = 7. We use the below logic to perform addition, without using plus symbol:
a = 8, b = 7;
add = a – ~b – 1;
add = 8 – (-8) – 1;
add = 8 + 8 – 1;
add = 8 + 7;
add = 15;
This would give proper required result.
#include < stdio.h > int main() { int a, b, add; printf("Enter 2 numbers for addition\n"); scanf("%d%d", &a, &b); add = a-~b-1; printf("Addition of %d and %d is %d\n", a, b, add); return 0; }
Output 1:
Enter 2 numbers for addition
1
2
Addition of 1 and 2 is 3
Output 2:
Enter 2 numbers for addition
-1
2
Addition of -1 and 2 is 1
Output 3:
Enter 2 numbers for addition
-1
-2
Addition of -1 and -2 is -3
Output 4:
Enter 2 numbers for addition
-5
5
Addition of -5 and 5 is 0
Output 5:
Enter 2 numbers for addition
5
-10
Addition of 5 and -10 is -5
Video Tutorial: C Program To Add Two Numbers without using Plus Operator
Note: These kind of tricky C programming questions can be asked in your viva or company interviews or competitive exams or even in your academic exams. So be prepared.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert