Adsense 728 * 15

Search

Custom Search

C++ Program to Convert Binary to Decimal Number

Write a C++ code to convert binary to Decimal number. Given an input binary number, we have to write a code to convert binary to decimal number.


C program to convert binary to decimal number


C++ Program to Convert Binary to Decimal Number


C++ Program to Convert Binary to Decimal Number



In this program, we write a code which takes an input binary number and print it's decimal representation.


#include <iostream>
#include <math.h>
using namespace std;

int main() {
 
    int bnum, rem, count = 0, sum = 0, flag = 1;
    
    cout << "Enter a binary number \n";
    cin  >> bnum;
    
    while(bnum > 0) {
    
         rem = bnum % 10;
         
         // Binary number only contains 0 and 1
         if(rem == 0 || rem == 1) {
             
             sum = sum + rem * pow(2, count);
             
         } else {
             
             flag = 0;
             break;
         }
         
         //Increment count variable
         count++;
         bnum = bnum / 10;
    }
    
    if(flag) {
     cout << "Decimal number is " << sum;
    } else {
     cout << "Invalid binary number";
    }
    
    return 0;
}




No comments:

Post a Comment