How to convert a number from Decimal to Binary using recursion in C#?

CsharpProgrammingServer Side Programming

To get the binary of Decimal, using recursion, firstly set the decimal number −

int dec = 30;

Now pass the value to a function −

public int displayBinary(int dec) {
}

Now, check the condition until the decimal value is 0 and using recursion get the mod 2 of the decimal num as shown below. The recursive call will call the function again with the dec/2 value −

public int displayBinary(int dec) {
   int res;
   if (dec != 0) {
      res = (dec % 2) + 10 * displayBinary(dec / 2);
      Console.Write(res);
      return 0;
   } else {
      return 0;
   }
}

The following is the complete code −

Example

 Live Demo

using System;

public class Program {
   public static void Main(string[] args) {
      int dec;
      Demo d = new Demo();
      dec = 30;
      Console.Write("Decimal = "+dec);
      Console.Write("\nBinary of {0} = ", dec);
      d.displayBinary (dec);
      Console.ReadLine();
      Console.Write("\n");
   }
}
public class Demo {
   public int displayBinary(int dec){
      int res;
      if (dec != 0) {
         res = (dec % 2) + 10 * displayBinary(dec / 2);
         Console.Write(res);
         return 0;
      } else {
         return 0;
      }
   }
}

Output

Decimal = 30
Binary of 30 = 11110
raja
Published on 31-Aug-2018 12:27:48
Advertisements