Find the Sum of two Binary Numbers without using a method in C#?

CsharpProgrammingServer Side Programming

First, declare and initialize two variables with the binary numbers.

val1 = 11010;
val2 = 10100;

Console.WriteLine("Binary one: " + val1);
Console.WriteLine("Binary two: " + val2);

To get the sum, loop until both the value are 0.

while (val1 != 0 || val2 != 0) {
   sum[i++] = (val1 % 10 + val2 % 10 + rem) % 2;
   rem = (val1 % 10 + val2 % 10 + rem) / 2;
   val1 = val1 / 10;
   val2 = val2 / 10;
}

Now, let us see the complete code to find the sum of two binary numbers.

Example

 Live Demo

using System;
class Demo {
   public static void Main(string[] args) {
      long val1, val2;
      long i = 0, rem = 0;
      long[] sum = new long[30];
   
      val1 = 11010;
      val2 = 10100;

      Console.WriteLine("Binary one: " + val1);
      Console.WriteLine("Binary two: " + val2);

      while (val1 != 0 || val2 != 0) {
         sum[i++] = (val1 % 10 + val2 % 10 + rem) % 2;
         rem = (val1 % 10 + val2 % 10 + rem) / 2;
         val1 = val1 / 10;
         val2 = val2 / 10;
      }

      if (rem != 0)
      sum[i++] = rem;
      i = i - 1;
      Console.Write("Sum = ");

      while (i >= 0)
      Console.Write(sum[i--]);
   }
}

Output

Binary one: 11010
Binary two: 10100
Sum = 101110
raja
Published on 21-Aug-2018 09:07:36
Advertisements