Decimal to Binary Conversion in C++

Beginner

Introduction

In this lab, you will learn how to write and implement a C++ program that converts decimal numbers to binary numbers using loops.

Open a new C++ file

Open a new C++ file in the ~/project directory with the name decimal_to_binary.cpp:

cd ~/project
touch decimal_to_binary.cpp

Write the program

Copy and paste the following code into the decimal_to_binary.cpp file:

#include<iostream>
using namespace std;
int main()
{
    int decimal_number, i=1, binary_number=0, remainder;
    cout<<"Enter the decimal number to be converted: ";
    cin>>decimal_number;

    while(decimal_number!=0)
    {
        remainder = decimal_number%2;
        decimal_number/=2;
        binary_number+=remainder*i;
        i*=10;
    }

    cout<<"The binary number is: "<<binary_number<<"\n";
    return 0;
}

Save and Compile

Save the file and compile it with the following command in the terminal of Ubuntu system:

g++ decimal_to_binary.cpp -o decimal_to_binary

Run the program

Run the program with the following command:

./decimal_to_binary

You will see the following message on the screen:

Enter the decimal number to be converted:

Full code

#include<iostream>
using namespace std;
int main()
{
    int decimal_number, i=1, binary_number=0, remainder;
    cout<<"Enter the decimal number to be converted: ";
    cin>>decimal_number;

    while(decimal_number!=0)
    {
        remainder = decimal_number%2;
        decimal_number/=2;
        binary_number+=remainder*i;
        i*=10;
    }

    cout<<"The binary number is: "<<binary_number<<"\n";
    return 0;
}

Summary

In this lab, you learned how to write and implement a C++ program that converts decimal numbers to binary numbers using loops. Now, you can easily convert any decimal number to binary number with this program.

Other Tutorials you may like