Sunday, 3 June 2012

C++ Program to convert any entered decimal number into binary

C++ Program to convert any entered decimal number into binary


#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream.h>

void convert_DtoB(int);
void show_answer(int[],int);

//FUNCTION THAT CONVERTS DECIMAL NUMBER TO BINARY
void convert_DtoB(int decimal)
{
    int    remainder = 0;

    int    counter = 0;
    int    binary[16] = {0}; //array to store the binary equivalent

    while( decimal != 1 )
    {
        remainder = decimal % 2;    //calculate the remainder
        decimal = (int)(decimal / 2);    //calculate the leftover number

        binary[counter] = remainder;    //store remainder as binary digit
        counter++;
    }
    binary[counter] = decimal;    //store the left over number as binary digit

    show_answer(binary,counter);    //display the binary number
}

//FUNCTION THAT DISPLAYS THE BINARY NUMBER
void show_answer(int answer[], int counter)
{
    //traverses the array backwards
    for(int n=counter; n>=0; n--)
    {
        cout << answer[n];
    }
}

void main()
{
    int number = 0;

    clrscr();

    cout << "Enter a Decimal number please....: ";
    cin  >> number;
        number = abs(number);    //To avoid negative entries
    cout<<endl;
    cout<<"The binaray equivalent is ";
    convert_DtoB(number);
    getch();
}

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More