#include<iostream>
using namespace std;
/*Function Prototypes*/
int find_binary(int); //for finding binary of decimal number
int countOnes(int,int &); //for counting ones in the decimal number
void show_result(int,int,int); //for showing results
int main()
{
int num,binary,ones;
cout << "Enter a Decimal number: ";
cin >> num;
ones=countOnes(num,binary); //calling function for getting the number of ones ones
show_result(num,binary,ones); //calling function to show the output
return 0;
}
/*Definitions of functions*/
int find_binary(int num )
{
int calD,calB, //for calculation
binary; //to store binary number
calD=num;
calB=1;
while( calD!=0 )
{
calB=calB*10+calD%2; //getting the reverse of binary number
calD/=2;
}
binary=0;
while( calB>=10 )
{
binary=binary*10+calB%10; //reversing the number to get the original binary number binary number
calB/=10;
}
return binary;
}
int countOnes(int num,int &binary)
{
int ones=0,
cal; //for calculation
if( num<0 )
{
binary=find_binary(abs(num)); //calling the function inside another function by passing absolute value
binary=-binary; //ataching -ve sign to get the original number
}
else
binary=find_binary(num); //calling the function inside another function
cal=abs(binary); //storing absolute value
while(cal!=0)
{
/*The number of ones are counted if the remainder is 1*/
if(cal%10==1)
{
ones++; //counted the number of 1s
}
cal/=10;
}
return ones;
}
void show_result(int num,int binary,int ones)
{
/*Showing the output*/
cout << "Binary form of "
<< num
<< " is: "
<< binary
<< ".\n";
cout << "And the number of ones in "
<< binary
<< " are: "
<< ones
<< endl;
}
No comments:
Post a Comment