The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs

In my college days my programming friend makes a rigorous challenge with me. He asked me to subtract two numbers without using minus operator, it's sounds poor right. Subtraction without using minus operator is it possible for you?

You being a programmer, Impossible is nothing more than having two cups of coffee instead of a coffee, lets code a C program to **subtract two numbers without using minus operator.**

c-without-subtraction-operator.c

#include <stdio.h> int subtract(int, int); int main() { int num1, num2; printf("\nEnter any two integers : "); scanf("%d%d", &num1, &num2); printf("Result is %d ", subtract(num1, num2)); return 0; } int subtract(int num1, int num2) { int borrow; while (num2 != 0) { borrow = (~num1) & num2; num1 = num1 ^ num2; num2 = borrow << 1; } return num1; }

Enter any two integers : 6 4 Result is : 2

The above program is crystal clear, we used function to subtract two numbers without using minus operator. We got two numbers from our user in a variable **num1** and **num2**. Firstly, we check whether **num2** is **0**. If it's zero, just return a value in **num1**. If it's a non-zero number, then execute the statement following else.

Lets look closely in while-loop

- borrow = (~6) & 4;
- borrow = (1001) & 0100 (in binary representation)
- borrow = 0

- num1 = 6 ^ 4;
- num1 = 0110 ^ 0100 (in binary representation)
- num1 = 0010
- num1 = 2

- num2 = borrow << 1;
- num2 = 0 << 1 (in binary representation)
- num2 = 0

In the first iteration itself num2 becomes 0. Thus value stored in num1 i.e) **2** is outputted.

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report

We to update you

© Copyright 2018