diff --git a/CPP/binaryToDecimalAndViceversa.cpp b/CPP/binaryToDecimalAndViceversa.cpp new file mode 100644 index 000000000..389710ff9 --- /dev/null +++ b/CPP/binaryToDecimalAndViceversa.cpp @@ -0,0 +1,31 @@ +// convert binary to decimal + +#include +#include + +using namespace std; + +// function prototype +int convert(long long); + +int main() { + long long n; + cout << "Enter a binary number: "; + cin >> n; + cout << n << " in binary = " << convert(n) << " in decimal"; + return 0; +} + +// function definition +int convert(long long n) { + int dec = 0, i = 0, rem; + + while (n!=0) { + rem = n % 10; + n /= 10; + dec += rem * pow(2, i); + ++i; + } + + return dec; +}