C# | Print Binary of a 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 [Last updated : March 19, 2023]

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.

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

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.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.