C++ Program to Convert Decimal to Binary

«
»

This is a C++ Program to Convert a Decimal Number to its Binary Equivalent.

Problem Description

The program takes a decimal number and converts it into its binary equivalent.

Problem Solution

1. The program takes a decimal number.
2. Using a while loop, the binary equivalent is calculated.
3. The result is printed,
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Convert a Decimal Number to its Binary Equivalent. The program output is shown below.

  1. #include<iostream>
  2. using namespace std; 
  3. int main ()
  4. {
  5.     int num, bin;
  6.     cout << "Enter the number : ";
  7.     cin >> num;
  8.     cout << "The binary equivalent of " << num << " is ";
  9.     while (num > 0)
  10.     {
  11.         bin = num % 2;
  12.         cout << bin;
  13.         num /= 2;
  14.     }
  15.     return 0;
  16. }
Program Explanation

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.

advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter the number : 3
The binary equivalent of 3 is 11
 
Case 2 :
Enter the number : 121
The binary equivalent of 121 is 1001111
 
Case 3 :
Enter the number : 15
The binary equivalent of 15 is 1111

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.