Convert decimal to binary using recursion

Problem statement:- Program to Convert decimal to binary using recursion.

Data requirement:-

   Input Data:- n

  Output Data:-
DecimalToBinary(n)

Program in C

Here is the source code of the C Program to Convert decimal to binary using recursion.

Code:

#include<stdio.h>
int DecimalToBinary(int n)
{
    if(n==0)
        return 0;
    else
        return (n% 2 + 10 * DecimalToBinary(n / 2));
}
int main()
{
    int n;
    printf("Enter the Decimal Value:");
    scanf("%d",&n);
    printf("Binary Value of Decimal number is: %d",DecimalToBinary(n));
}

Input/Output:
Enter the Decimal Value:8
Binary Value of Decimal number is: 1000

Program in C++

Here is the source code of the C++ Program to Convert decimal to binary using recursion.

Code:

#include<iostream>
using namespace std;
int DecimalToBinary(int n)
{
    if(n==0)
        return 0;
    else
        return (n% 2 + 10 * DecimalToBinary(n / 2));
}
int main()
{
    int n;
    cout<<"Enter the Decimal Value:";
    cin>>n;
    cout<<"Binary Value of Decimal number is: "<<DecimalToBinary(n);
}

Input/Output:
Enter the Decimal Value:165
Binary Value of Decimal number is: 10100101

Program in Java

Here is the source code of the Java Program to Convert decimal to binary using recursion.

Code:

import java.util.Scanner;
public class DecimalToBinaryConvert {
static int DecimalToBinary(int n)
{
    if(n==0)
        return 0;
    else
        return (n% 2 + 10 * DecimalToBinary(n / 2));
}
public static void main(String[] args) {
           Scanner cs=new Scanner(System.in);
            int n;
    System.out.print("Enter the Decimal Value:");
    n=cs.nextInt();
    System.out.print("Binary Value of Decimal number is: "+DecimalToBinary(n));
        cs.close();
}
}

Input/Output:
Enter the Decimal Value:10
Binary Value of Decimal number is: 1010

Program in Python

Here is the source code of the Python program to convert decimal to binary using recursion.

Code:

def DecimalToBinary(n):
    if n==0:
        return 0
    else:
        return  (n% 2 + 10 * DecimalToBinary(n // 2))
n=int(input("Enter the Decimal Value:"))
print("Binary Value of Decimal number is:",DecimalToBinary(n))

Input/Output:

Post a Comment

0 Comments