PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Program Based on Conversion

Program to convert a decimal number into binary number

Input - Output

Input
Enter a decimal number : 9

Output
Binary equivalent of given number : 1001

Input
Enter a decimal number : 12

Output
Binary equivalent of given number : 1100

Algorithm

Step 1: START

Step 2: Enter a number 'num' as an input.

Step 3: Calculate remainder i.e(num%2) and store it into an array

Step 4: Divide the num by 2 i.e (num/2)

Step 5: Repeat the step 3 and 4 until the num is greater than zero

Step 6: END

CODE


/* Decimal to Binary Conversion */

#include <stdio.h>
int main()
{
      int num,bin[10],i,j;
      printf(" Enter the decimal number : ");
      scanf("%d",&num);
      for(i=0;num>0;i++)
    {
        bin[i]=num%2;
        num/=2;
    }
      printf(" Binary of given number is = ");
      for(j=i-1;j>=0;j--)
      printf("%d",bin[j]);
    return 0;
}


/* Decimal to Binary Conversion */

#include <iostream>
using namespace std;
int main()
{
      int num,bin[10],i,j;
      cout<<" Enter the decimal number : ";
      cin>>num;
      for(i=0;num>0;i++)
    {
        bin[i]=num%2;
        num/=2;
    }
      cout<<" Binary of given number is = ";
      for(j=i-1;j>=0;j--)
      cout<<bin[j];
    return 0;
}

OutPut

Enter the decimal number: 9

Binary of given number is = 1001