# C# program to calculate the sum of two binary numbers

Here, we are going to learn how to calculate the sum of two binary numbers in C#?
Submitted by Nidhi, on October 03, 2020

Here we will calculate the sum of two given binary numbers. As we know that a binary number is represented using only two digits 0 and 1.

Program:

The source code to calculate the sum of two binary numbers is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

```//C# program to calculate the sum of binary numbers.

using System;
class BinarySum
{
static void CalculateBinarySum(int num1, int num2)
{
int i   = 0;
int rem = 0;
string str="";

while (num1 != 0 || num2 != 0)
{
str += (num1 % 10 + num2 % 10 + rem) % 2;
rem = (num1 % 10 + num2 % 10 + rem) / 2;

num1 = num1 / 10;
num2 = num2 / 10;
}

if (rem != 0)
str += rem;

Console.Write("Sum is : ");
for (i = str.Length - 1; i >= 0; i--)
{
Console.Write(str[i]);
}
Console.WriteLine();
}
public static void Main()
{
int num1=0;
int num2=0;

Console.Write("Enter 1st binary number: ");

Console.Write("Enter 2nd binary number: ");

CalculateBinarySum(num1, num2);
}
}
```

Output:

```Enter 1st binary number: 1010
Enter 2nd binary number: 1101
Sum is : 10111
Press any key to continue . . .
```

Explanation:

Here, we created a class BinarySum that contains two static methods CalculateBinarySum() and Main().

In the CalculateBinarySum() method we took num1 and num2 as an argument and then add each digit according to the rules of binary addition and then we concatenate the result into the string and we print the resulted string in the reverse direction to print actual output on the console screen.

The Main() method is the entry point for the program, here we read the value num1 and num2 from the user and passed the values to the CalculatBinarySum() method to calculate and print the binary addition on the console screen.