Social Icons

Monday, 24 March 2014

C# Program to Subtract two numbers without using subtract (-) operator

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b;
            Console.Write("\n Enter first number : ");
            a = int.Parse(Console.ReadLine());
            Console.Write("\n Enter first number : ");
            b = int.Parse(Console.ReadLine());

            int c = a + ~b + 1;
          
            Console.WriteLine("\n\t The Difference of a and b is : " + c);
            Console.ReadKey();
        }
    }
}

                                                       OUTPUT




NOTE:- The way you get this is by taking the binary representation of a number, taking it's complement (inverting all the bits) and adding one. Two starts as 0000 0010, and by inverting the bits we get 1111 1101. Adding one gets us the result above. The first bit is the sign bit, implying a negative.

So let's take a look at how we get ~2 = -3:

Here's two again:

0000 0010

Simply flip all the bits and we get:

1111 1101

Well, what's -3 look like in two's complement? Start with positive 3: 0000 0011, flip all the bits to 1111 1100, and add one, 1111 1101.

So if you simply invert the bits in 2, you get the two's complement representation of -3.

No comments:

Post a Comment