Adsense 728 * 15

Search

Custom Search

C Program to Convert Binary to Decimal Number

Write a C program to convert binary to decimal number. In this programming question, we are going to write a code which takes binary number as an input and print their decimal representation.

This question is very important in terms of technical interview.

C interview questions and answers

For example -

Input      : 100 (Binary Number)
Output    : 4    (Decimal Number)

Input     : 111 (Binary Number)
Output  :  7    (Decimal Number)

C Program to Convert Binary to Decimal Number



C++ program to convert binary to decimal number

How to Convert Binary to Decimal Number


Let's assume, we have to convert 100 to decimal number.

Decimal Number Conversion : 1 * 2 2   +  0 * 2 +  0 * 2 0 = 4

Similarly, we can convert any binary representation into decimal number.

Program to Convert Decimal to Binary Number

Program to count number of digits of a number


C Program to Convert Binary to Decimal Number


#include <stdio.h>
#include <math.h>

int main() {
 
  int bnum, sum, rem, count=0;
 
  printf("Enter a binary number \n");
  scanf("%d",&bnum);
 
  /* Initialize a sum variable to 0 */
 
  sum = 0;
 
  while(bnum > 0){
  
      /* Take a Remainder */
  
      rem = bnum%10;
  
      /* If remainder is other than 0 and 1,
       then it is not a binary number. */

      if(rem==0 || rem==1 ){

        /* calculate sum. */
  
        sum = sum + rem *pow(2,count);
 
        /* Divide to reduce the number length. */
 
        bnum = bnum/10;
  
        /* Increment the count. */

        ++count;
   
      } else {

         printf(" Please enter valid binary number \n");
         return 0;    
      }  

  }
 
   printf("\n Decimal number is %d",sum);
  
   return 0;
}


Output:

Enter binary number 1000

Decimal number is 8

Programming question on Arrays

No comments:

Post a Comment