Q:

C# program to calculate the sum of two binary numbers

belongs to collection: C# Basic Programs | basics

0

C# program to calculate the sum of two binary numbers

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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: ");
        num1 = Convert.ToInt32(Console.ReadLine());
        
        Console.Write("Enter 2nd binary number: ");
        num2 = Convert.ToInt32(Console.ReadLine());

        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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to calculate the multiplication of two ... >>
<< C# program to print the Pascal Triangle...