Description

We can convert any decimal number into binary number in c without using an array.

Decimal Number

A Decimal number is a base 10 of number because it ranges goes from 0 to 9, In decimal number there are total 10 digits between 0 to 9. Any combination of digits is decimal number. For Example : 33, 782, 7, 0, 5 etc.

Binary Number

A binary number a base 2 of number because it ranges goes from 0 to 1, It has only two digits o and 1. Any combination of digits is binary number. For Example : 0110001, 111001, 101 etc.

Decimal to Binary Table given below...

Decimal Binary
1 1
2 10
3 111
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010

Algorithm

Steps:

  1. run the loop while n is greater than 0,
  2. calcualte the remainder and store the value in j variable, after this initilized a variable temp which store the power of 10 after every iteration.
  3. bin += j * temp -> here we store the new bit in bin variable here bin variable store the binary of the digit.
  4. after perfom these operation than remove the last bit of the number using n = n / 2;
  5. Exit to the loop
  6. Print the binary of the digit given by user.
  7. Exit the program.

Using for loop

#include <stdio.h>
#include <math.h>
int main() {
    int n, i, j, bin = 0, temp;
    printf("Enter the Decimal Number : ");
    scanf("%d", &n);
    temp = n;
    for(i = 0; n > 0; i++){
        j = n % 2;
        int temp = pow(10, i);
        bin += j * temp;
        n = n / 2;
    }
    printf("\nBinary of %d is : %d", temp, bin);

    return 0;
}

/*

Enter the Decimal Number : 34
Binary of 34 is : 100010

*/

Using while loop

#include <stdio.h>
#include <math.h>
int main() {
    int n, i = 0, bin = 0, temp;
    printf("Enter the Decimal Number : ");
    scanf("%d", &n);
    temp = n;
    while(n > 0){
        int temp = pow(10, i);
        bin += (n % 2) * temp;
        n = n / 2;
        i++;
    }
    printf("\nBinary of %d is : %d", temp, bin);

    return 0;
}

/*

Enter the Decimal Number : 34
Binary of 34 is : 100010

*/

Please Comment...

Comments

Login is mandatory to comment Please login

Recommended Posts

A C program for checking whether a given line is a comment

Write a program in c to check whether a given line is comment or not.

Linear search in c | Algorithm of Linear search | c programming

It is the easiest search algorithm because it starts at the beginning and works through each element in a list until the desired element is located.