C++ Program to Convert Decimal to Binary Value

«
»

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.

advertisement
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
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
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn