Decimal to Binary Conversion in C++

C++C++Beginner
Practice Now

Introduction

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/ControlFlowGroup -.-> cpp/while_loop("`While Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") subgraph Lab Skills cpp/variables -.-> lab-96155{{"`Decimal to Binary Conversion in C++`"}} cpp/while_loop -.-> lab-96155{{"`Decimal to Binary Conversion in C++`"}} cpp/output -.-> lab-96155{{"`Decimal to Binary Conversion in C++`"}} cpp/user_input -.-> lab-96155{{"`Decimal to Binary Conversion in C++`"}} cpp/files -.-> lab-96155{{"`Decimal to Binary Conversion in C++`"}} end

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 C++ Tutorials you may like