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.

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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.