C++ Program to Convert Decimal to Any Base

«
»
This C++ Program demonstrates the Conversion of a Number from a Decimal Base to Any Base less than the Number.

Here is source code of the C++ Program to Convert a Number from Decimal Base to Any Base. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Convert a Decimal Base to Any Base
  3.  */
  4. #include<iostream>
  5. #include <cstdio>
  6. using namespace std;
  7.  
  8. /*
  9.  * Convert a Decimal Base to Any Base
  10.  */
  11. void convert10tob(int N, int b)
  12. {
  13.      if (N == 0)
  14.         return;
  15.      int x = N % b;
  16.      N /= b;
  17.      if (x < 0)
  18.         N += 1; 
  19.      convert10tob(N, b);
  20.      cout<< x < 0 ? x + (b * -1) : x;
  21.      return;
  22. }
  23.  
  24. /*
  25.  * Main
  26.  */
  27. int main()
  28. {
  29.     int N,b;
  30.     cout<<"Enter the integer to convert(N): ";
  31.     cin>>N;
  32.     cout<<"Enter the base <= N: ";
  33.     cin>>b;
  34.     if (N != 0)
  35.     {
  36.         convert10tob(N, b);
  37.         cout<<endl;
  38.     }
  39.     else
  40.         cout<<"0"<<endl;
  41.     return 0;
  42. }

$ g++ decimal_any.cpp
$ a.out
 
Enter the integer to convert(N): 100
Enter the base >= N: 2
1100100
 
------------------
(program exited with code: 1)
Press return to continue

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

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

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.