Articles

C++ program to convert binary to decimal using functions

C++ program to convert binary to decimal using functions


In this chapter of C++ program tutorial our task is to write simple: 

  • c++ program to convert binary number to decimal

C++ program to convert binary to decimal using functions

Below is the c++ program to convert binary to decimal using functions:

/*  Program Name: To convert a binary number to its decimal equivalent
    Program Author: Sayantan Bose
*/
#include <iostream>
#include <math.h>
using namespace std;

//Function to make the conversion
 int solve(long long num) {
 int decimal = 0, i = 0, r;
 while (num != 0) {
 r = num % 10;
 num /= 10;
 decimal += r * pow(2, i);
 ++i;
 }
 return decimal;
 }

 //Main function
int main() {
 long long num;
 cout<<"Enter a binary number: ";
 cin>>num;
 int decimal_num=solve(num);
 cout<<num<< " in binary = "<< decimal_num<< " in decimal";
 return 0;
 }

OUTPUT

Enter a binary number:
101
101 in binary = 5 in decimal
Or
Enter a binary number:
110011
110011 in binary = 51 in decimal
 
EXPLANATION :
In the above c++ program to convert binary to decimal using while loop:
  • A binary number can be converted to its decimal equivalent by multiplying each digit of the binary number with 2 powered to the position of the digit in the number.
  • In the above program, a given binary number is passed on to the function solve where it is converted to its decimal equivalent.

The position of the digits of a binary number always starts from the left side, with 0.

WORKING OF BINARY TO DECIMAL CONVERTER PROGRAM :

c++ program to convert binary to decimal using while loop

You can see the above code execution and output in codeblocks IDE:

c++ program to convert binary to decimal using while loop

 


CPP Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Sayantan Bose
- šŸ”­ Iā€™m currently working on DS Algo skills - šŸŒ± Iā€™m currently learning web develeopement - šŸ‘Æ Iā€™m looking to collaborate with Oppia - šŸ“« Reach me at https://www.linkedin.com/in/sayantan-bose-14134a1a6/ - šŸ˜„ Pronouns: his/him
Page Views :    Published Date : Jan 20,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!