Lets write a C program to perform subtraction of 2 numbers without using minus symbol or the subtraction operation(-).
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 = 15 and b = 5. To subtract 10 from 5 we use result = a – b. And the result will be 10. But in this C program we are not using minus(-) operation, but still we must get the same result 10(for above input).
If num = 10;
result = ~num; will give 1s complement of 10, that is -11.
result = ~num+1; will give 2s complement of 10, that is -10.
Now using this logic, we ask the user to enter 2 numbers. If user enters a = 10 and b = 5. We use the below logic to perform subtraction, but without using minus symbol:
a = 10, b = 5;
sub = a + ~b + 1;
sub = 10 + (-6) + 1;
sub = 10 – 6 + 1;
sub = 10 – 5;
sub = 5;
This would give proper required result.
#include < stdio.h > int main() { int a, b, sub; printf("Enter 2 numbers\n"); scanf("%d%d", &a, &b); sub = a+~b+1; printf("Subtraction of %d and %d is %d\n", a, b, sub); return 0; }
Output 1:
Enter 2 numbers
4
10
Subtraction of 4 and 10 is -6
Output 2:
Enter 2 numbers
5
10
Subtraction of 5 and 10 is -5
Output 3:
Enter 2 numbers
10
5
Subtraction of 10 and 5 is 5
Output 4:
Enter 2 numbers
5
5
Subtraction of 5 and 5 is 0
Output 5:
Enter 2 numbers
5
-5
Subtraction of 5 and -5 is 10
Video Tutorial: C Program To Subtract Two Numbers without using Minus 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