
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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
- Related Articles
- How to Convert Decimal to Binary Using Recursion in Python?
- Haskell Program to convert the decimal number to binary using recursion
- Swift program to convert the decimal number to binary using recursion
- C++ program to Convert a Decimal Number to Binary Number using Stacks
- How to convert Decimal to Binary using C#?
- C++ Program to convert the Binary number to Gray code using recursion
- Convert decimal fraction to binary number in C++
- C++ Program To Convert Decimal Number to Binary
- Decimal to binary conversion using recursion in JavaScript
- Haskell Program to convert the Binary number to Gray code using recursion
- Java Program to convert binary number to decimal number
- Convert decimal to binary number in Python program
- Python program to convert decimal to binary number
- How to Convert Binary to Decimal?
- How to Convert Decimal to Binary?

Advertisements