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:
- Open a C++ compiler (e.g., Code::Blocks, Visual Studio, or an online compiler like repl.it).
- Create a new C++ project or file, and paste the code provided above.
- Compile the program to check for errors.
- Run the program and input a decimal number when prompted.
- The binary equivalent of the entered decimal number will be displayed on the screen.