In this article, we will write a C program to subtract two numbers without using the subtraction operator. The program takes two numbers from the user as input, subtracts them and prints the result on the output window.
Sample Example:
Enter two numbers: 10 5
The result of (10 - 5) is 5
Enter two numbers: 1000 10
The result of (1000 - 10) is 990
To subtract two numbers without using the subtraction operator, we have to first understand how computers perform the subtraction.
Basically, to perform subtraction on two numbers, computers use the Two's complement
method.
Two’s complement of a number is achieved by inverting the bits of the number(which is also called one’s complement) and then adding 1 to it.
So whenever computers need to perform subtraction on two numbers, they actually add the two’s complement of the second number to the first number.
For example, let’s say we want to subtract 5 from 7 i.e. (7 – 5). To do that we have to first convert both decimal numbers into their binary equivalents and then add the 2’s complement of the number 5 to the binary equivalent of the number 7.
- The binary representation of 5 is (0101)2 and the binary representation of 7 is (0111)2.
- The 1’s complement of 5 can be achieved by inverting its bits i.e. replacing 0 with 1 and 1 with 0 which will give us (1010)2.
- Therefore, 2’s complement of 5 = (1’s complement of 5) + 1 = (1010 + 1)2 = (1011)2
- So, (7 – 5) = Binary eq. of 7 + 2’s complement of 5 = 0111 + 1011 = (1)0010
We can ignore the overflowing bit which is 1 in this case. So, if we take the remaining bits, we will get (0010)2, which is nothing but the binary equivalent of the decimal number 2 and it is the result of subtraction(7 – 5 = 2).
We can use the above approach in our C program to subtract two numbers without using the subtraction operator.
See implementation in the below program:
// C program to subtract two numbers // without using the subtraction operator #include <stdio.h> int main() { int num1, num2, res; printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); // Add 2's complement of num2 to num1 to // subtract num2 from num1 res = num1 + (~num2 + 1); printf("The result of (%d - %d) is %d", num1, num2, res); return 0; }
Output:
Enter two numbers: 7 5 The result of (7 - 5) is 2 Enter two numbers: 100 5 The result of (100 - 5) is 95
I hope you like this article. Thanks for reading!