Convert Decimal to Binary in CPlusPlus

 

 

Introduction:

In computer science, binary numbers are crucial as they represent data in a format that a computer can understand. A binary number is composed of only two digits, 0 and 1. These binary digits correspond to the electrical states of a system: on (1) and off (0). In this program, we will explore how to convert a decimal number (base 10) to its binary equivalent (base 2) using C++ programming.

Objective:

The main objective of this program is to take a decimal number input from the user and convert it to its binary equivalent. The conversion will be done using the concept of division by 2 and keeping track of the remainders until the quotient becomes zero.

C++ Code:


#include 
#include 
using namespace std;

void decimalToBinary(int n) {
    stack binaryStack;

    // If n is 0, print 0 as binary
    if (n == 0) {
        cout << 0; return; } // Push remainders of n divided by 2 to the stack while (n > 0) {
        binaryStack.push(n % 2);
        n = n / 2;
    }

    // Print binary number from the stack
    while (!binaryStack.empty()) {
        cout << binaryStack.top();
        binaryStack.pop();
    }
}

int main() {
    int decimalNumber;
    
    // User input for decimal number
    cout << "Enter a decimal number: "; cin >> decimalNumber;
    
    cout << "Binary equivalent: ";
    decimalToBinary(decimalNumber);
    
    return 0;
}
        

Explanation of the Program:

The C++ program is designed to convert a given decimal number into its binary equivalent. Here’s a step-by-step breakdown:

  • Input: The program prompts the user to input a decimal number (an integer).
  • Conversion Logic:
    The function `decimalToBinary` works by continuously dividing the decimal number by 2 and storing the remainder at each step. This remainder represents the binary digits (0 or 1) in reverse order.
  • Stack Data Structure: The program uses a stack to store these binary digits. A stack is a data structure that operates on a Last-In, First-Out (LIFO) principle, which helps to print the binary number in the correct order after the division process is complete.
  • Output: The program prints the binary equivalent of the given decimal number by popping the elements of the stack.

How to Run the Program:

To run this program, follow these steps:

  1. Open a C++ compiler (e.g., Code::Blocks, Visual Studio, or an online compiler like repl.it).
  2. Create a new C++ project or file, and paste the code provided above.
  3. Compile the program to check for errors.
  4. Run the program and input a decimal number when prompted.
  5. The binary equivalent of the entered decimal number will be displayed on the screen.
© 2024 Learn Programming

 

Leave a Reply

Your email address will not be published. Required fields are marked *