C# program to print the binary equivalent of an integer number using recursion

Here, we are going to learn how to print the binary equivalent of an integer number using recursion in C#?
Submitted by Nidhi, on September 03, 2020

Here we will read an integer number from the keyboard and then print the binary equivalent of the number using the recursive method on the console screen.

Program:

The source code to print the binary equivalent of an integer number using recursion is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to print the binary equivalent 
//of an integer number using recursion.

using System;

class Sample
{
    public static int PrintBinary(int number)
    {
        if (number == 0)
        {
            return 0;
        }
        else
        {
            int bit = 0;

            bit = (number % 2) + 10 * PrintBinary(number / 2);
            Console.Write(bit);

            return 0;
        }
    }

    public static void Main()
    {
        int num = 0;
        
        Console.Write("Enter the number: ");
        num = int.Parse(Console.ReadLine());

        PrintBinary(num);
        Console.WriteLine();
    }
}

Output:

Enter the number: 9
1001
Press any key to continue . . .

Explanation:

In the above program, we created a Sample class that contains two static methods PrintBinary() and Main() method. In the Main() method, we declared an integer variable num and read the value of variable num, and then print the binary equivalent number on the console screen.

As we know that the base of the binary number is 2 while the base of the decimal number is 10. In the PrintBinary() method, we calculated the remainder of a number by 2 and add the resultant value to the 10, and multiply the resultant value to the recursive method call, it will print one bit in every recursive call on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.