Convert Binary to Decimal program in C++

Convert Binary to Decimal program

Given: Binary number as input and we have to convert it to decimal number.

This can be done by multiplying each digit of binary number starting from LSB with powers of 2 respectively.

Example:

Binary number: 100101

(1*2^5) + (0*2^4)+ (0*2^3)+ (1*2^2)+ (0*2^1)+ (1*2^0) = 37

Decimal number =37

# Algorithm

  1. Binary number is taken as input.
  2.  Multiply each digit of the binary number (starting from the last) with the powers of 2 respectively.
  3.  Add all the multiplied digits.
  4.  The total sum gives the result.

Code:

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

int main()

{

long int i, no;

int x, y = 0;

cout &lt;&lt; "Enter any binary number: ";

cin &gt;&gt; no;

cout &lt;&lt; "\nThe decimal conversion of " &lt;&lt; no &lt;&lt; " is ";

for (i = 0; no != 0; i++)

{

	x = no % 10;

	y = (x) *(pow(2, i)) + y;

	no = no / 10;
}

cout &lt;&lt; y;

return 0;

}