C# program to convert a number from Decimal to Binary using recursion
Here's a C# program that converts a number from decimal to binary using recursion:
using System;
class Program
{
static void Main()
{
int decimalNumber = 10;
Console.WriteLine("Binary representation of " + decimalNumber + " is: " + DecimalToBinary(decimalNumber));
}
static string DecimalToBinary(int decimalNumber)
{
// Base case: if the decimal number is 0, return "0" as the binary representation
if (decimalNumber == 0)
{
return "0";
}
else
{
// Recursive case: divide the decimal number by 2 and convert the quotient to binary,
// then append the remainder (decimal number % 2) to the binary representation
return DecimalToBinary(decimalNumber / 2) + (decimalNumber % 2).ToString();
}
}
}
In this program, we have the 'DecimalToBinary' method that takes an integer 'decimalNumber' as input and returns its binary representation as a string.
We have a base case where if the 'decimalNumber' is 0, we return "0" as the binary representation.
In the recursive case, we divide the 'decimalNumber' by 2 and recursively call 'DecimalToBinary' with the quotient. Then, we append the remainder (obtained by 'decimalNumber % 2') to the binary representation.
The recursive calls continue until we reach the base case (decimalNumber equals 0), at which point the recursion stops and the binary representation is built.
In the example above, the output would be:
Binary representation of 10 is: 1010
The decimal number 10 is converted to binary as 1010.