Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a number from Decimal to Binary using recursion in C#?
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
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("
Binary of {0} = ", dec);
d.displayBinary (dec);
Console.ReadLine();
Console.Write("
");
}
}
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
Advertisements