Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to convert binary to decimal number using user define function.

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to convert binary to decimal number using user define function.

Objective

Write a C++ program to convert a Binary number to Decimal using a function.

Algorithm / Approach

  1. Write a custom power() function.
  2. In binToDec(), extract each digit (rem = n % 10).
  3. Multiply the digit by 2 raised to the power of its position index.
  4. Add it to the decimal total.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
long binToDec(long n);
int power(int, int);
int main() {
 long bi;
 cout<<"Enter a binary no. :";
 cin>>bi;
 cout<<"BINARY : "<< bi<< endl;
 cout<<"DECIMAL: "<< binToDec(bi);
 return 0;
}

long binToDec(long n) {
 int rem;
 long dec = 0, i=0;
 while(n != 0) {
  rem = n%10;
  n = n/10;
  dec = dec +(rem*power(2,i));
  ++i;
 }
return dec;
}
int power(int a, int b) {
int res= 1;
for(int i =0; i< b; i++) {
 res = res*b;
}
return res;
}

Expected Output

Enter a binary no. :11011
 BINARY  : 11001
 DECIMAL : 27

Explanation of the Program

  • Binary to decimal conversion involves multiplying each binary digit by 2^position and summing the results.
  • Note on the provided code: There is a severe logical bug in the custom power(int a, int b) function. Inside the loop, it calculates res = res * b;. This calculates (B to the power of B), entirely ignoring the base a! It should be res = res * a;.

Complexity

Time Complexity O(log₁₀ n) - For extracting digits.
Space Complexity O(1)

Common Mistakes

  • Logical Error: The custom power function multiplies the exponent by itself (res = res * b) instead of the base (res = res * a).
ADVERTISEMENT