Here is a C++ program to convert binary to decimal. Here are the different methods to convert binary to decimal like using recursion.
How to convert binary to decimal .
Method 1 : C++ program to convert binary to decimalHow to convert binary to decimal .
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
long decimal=0,rem,num,temp=1;
cout<<"Enter the number in binary ";
cin>>num;
temp=num;
for(int i=0;num>0;i++)
{
rem=num%10;
num/=10;
decimal+=rem*pow(2,i);
}
cout<<"Decimal equivalent "<<decimal;
return 0;
}
#include<math.h>
using namespace std;
int main()
{
long decimal=0,rem,num,temp=1;
cout<<"Enter the number in binary ";
cin>>num;
temp=num;
for(int i=0;num>0;i++)
{
rem=num%10;
num/=10;
decimal+=rem*pow(2,i);
}
cout<<"Decimal equivalent "<<decimal;
return 0;
}
Method 2 : C++ program to convert binary to decimal using recursion
#include<iostream>
#include<math.h>
using namespace std;
int deci(int n,int i)
{
if(n==0)
return 0;
return (n%10)*pow(2,i)+deci(n/10,i+1);
}
int main()
{
int num;
cout<<"Enter Binary number : ";
cin>>num;
cout<<"Decimal equivalent : "<<deci(num,0);
return 0;
}
#include<math.h>
using namespace std;
int deci(int n,int i)
{
if(n==0)
return 0;
return (n%10)*pow(2,i)+deci(n/10,i+1);
}
int main()
{
int num;
cout<<"Enter Binary number : ";
cin>>num;
cout<<"Decimal equivalent : "<<deci(num,0);
return 0;
}
Method 3 : Another C++ program to convert binary to decimal
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int main()
{
int decimal=0,lt;
char num[30];
cout<<"Enter the number in binary ";
cin>>num;
lt=strlen(num)-1;
for(int i=lt;i>=0;i--)
decimal+=(num[i]-48)*pow(2,lt-i);
cout<<"Decimal equivalent "<<decimal;
return 0;
}
#include<math.h>
#include<string.h>
using namespace std;
int main()
{
int decimal=0,lt;
char num[30];
cout<<"Enter the number in binary ";
cin>>num;
lt=strlen(num)-1;
for(int i=lt;i>=0;i--)
decimal+=(num[i]-48)*pow(2,lt-i);
cout<<"Decimal equivalent "<<decimal;
return 0;
}
Method 4 : C++ program to convert decimal to binary using function
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
void binary(char *a,int lt)
{
int decimal=0;
for(int i=lt;i>=0;i--)
decimal+=(a[i]-48)*pow(2,lt-i);
cout<<"Decimal equivalent "<<decimal;
}
int main()
{
int lt;
char num[30];
cout<<"Enter the number in binary ";
cin>>num;
lt=strlen(num)-1;
binary(num,lt);
return 0;
}
#include<math.h>
#include<string.h>
using namespace std;
void binary(char *a,int lt)
{
int decimal=0;
for(int i=lt;i>=0;i--)
decimal+=(a[i]-48)*pow(2,lt-i);
cout<<"Decimal equivalent "<<decimal;
}
int main()
{
int lt;
char num[30];
cout<<"Enter the number in binary ";
cin>>num;
lt=strlen(num)-1;
binary(num,lt);
return 0;
}
No comments:
Post a Comment