Write C++ program to convert decimal number to binary using function


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4.  
  5. //Function declaration
  6. long long convertDecimalToBinary(int);
  7.  
  8. int main()
  9. {
  10. int n, binaryNumber;
  11.  
  12. cout << "Enter a decimal number: ";
  13. cin >> n;
  14. binaryNumber = convertDecimalToBinary(n);
  15. cout << n << " in decimal = " << binaryNumber << " in binary" << endl ;
  16. return 0;
  17. }
  18.  
  19. long long convertDecimalToBinary(int n)
  20. {
  21. long long binaryNumber = 0;
  22. int remainder, i = 1, step = 1;
  23.  
  24. while (n!=0)
  25. {
  26. remainder = n%2;
  27. cout << "Step " << step++ << ": " << n << "/2, Remainder = " << remainder << ", Quotient = " << n/2 << endl;
  28. n /= 2;
  29. binaryNumber += remainder*i;
  30. i *= 10;
  31. }
  32. return binaryNumber;
  33. }
  34.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts