Given an integer number, now we convert the given integer number into a binary number using recursion. Recursion is a method in which a function calls itself directly or indirectly and such type of function is known as a recursive function. It solves the problem very efficiently like we find the binary equivalent of an integer.
Examples:
Input : 10
Output: 1010
Input : 11
Output: 1011
Approach:
To display the binary equivalent of an integer we use the following steps:
- If condition is used to check if the given value is not equal to zero.
- If the given condition is true then perform the modulus of the val by 2, then add the modulus result to 10 and then multiply the value of the result with the value of decimaltobinary() function.
- Now repeat step 2 until the value of val variable is greater than zero.
- Print the array in reverse order now.
- And if the condition is false then it will execute the else section, i.e., return 0
The below image can help you better understand the approach.

Let us considered the integer number is 10. Now we find the binary equivalent of 10 so,
- 10 % 2 + 10 * (10 / 2) % 2 will return 0
- 5 % 2 + 10 * (5 / 2) % 2 will return 1
- 2 % 2 + 10 * (2 / 2) % 2 will return 0
- 1 % 2 + 10 * (1 / 2) % 2 will return 1
So the final result is 1010.
Example 1:
C#
using System;
class GFG{
public static void Main( string [] args)
{
int num = 15;
decimaltobinary(num);
}
public static int decimaltobinary( int val)
{
int binary;
if (val != 0)
{
binary = (val % 2) + 10 * decimaltobinary(val / 2);
Console.Write(binary);
return 0;
}
else
{
return 0;
}
}
}
|
Example 2:
C#
using System;
class GFG{
public static int decimaltobinary( int val)
{
int binary;
if (val != 0)
{
binary = (val % 2) + 10 * decimaltobinary(val / 2);
Console.Write(binary);
return 0;
}
else
{
return 0;
}
}
public static void Main( string [] args)
{
int num;
Console.Write( "Hi! Enter the number:" );
num = int .Parse(Console.ReadLine());
decimaltobinary(num);
}
}
|
Output:
Hi! Enter the number:10
1010