Write a C++ program that converts a given decimal number into its binary equivalent.
A decimal number is represented using the base-10 numeral system, with digits from 0 to 9. It’s the standard way for humans to express numbers in everyday calculations.
A binary number is expressed using only two digits: 0 and 1. It’s commonly used for computer operations and data representation.
1. The program takes a decimal number.
2. Using a while loop, the binary equivalent is calculated.
3. The result is printed,
4. Exit.
Example:
To convert the decimal number 25 to binary:
- Divide 25 by 2, getting the quotient 12 and a remainder of 1.
- Divide the quotient (12) by 2, getting 6 with a remainder of 0.
- Divide the new quotient (6) by 2, getting 3 with a remainder of 0.
- Continue until the quotient becomes 0.
- The binary representation of 25 is “11001”.
Here is the source code of C++ Program to Convert a Decimal Number to its Binary Equivalent. The program output is shown below.
/* * C++ Program to Convert Decimal to Binary */ #include<iostream> using namespace std; int main () { int num, bin; cout << "Enter the number : "; cin >> num; cout << "The binary equivalent of " << num << " is "; while (num > 0) { bin = num % 2; cout << bin; num /= 2; } return 0; }
1. The user is asked to enter a decimal number and it is stored in the variable ‘num’.
2. Using a while loop, the modulus of num and 2 is stored in the variable bin and printed.
3. num is then equal to num divided by 2.
4. The loop continues till num is greater than 0.
5. The result is then printed.
Time Complexity: O(log n)
The time complexity of the while loop depends on the number of bits required to represent the input number ‘num’ in binary. It iterates until ‘num’ becomes 0, which happens in log base 2 of ‘num’ iterations.
Space Complexity: O(1)
The space complexity is constant. The program uses a fixed amount of memory for a few integer variables (num, bin) regardless of the input size.
Test case 1: In this case, we input the decimal number “3” to convert it into a binary number.
Enter the number : 3 The binary equivalent of 3 is 11
Test case 2: In this case, we input the decimal number “121” to convert it into a binary number.
Enter the number : 121 The binary equivalent of 121 is 1001111
Test case 3: In this case, we input the decimal number “25” to convert it into a binary number.
Enter the number : 25 The binary equivalent of 25 is 11001
To practice programs on every topic in C++, please visit “Programming Examples in C++”, “Data Structures in C++” and “Algorithms in C++”.
- Practice Programming MCQs
- Apply for Computer Science Internship
- Check Programming Books
- Practice Computer Science MCQs
- Check Computer Science Books