Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Convert a decimal number to hexadecimal number

C++ For Loop: Exercise-71 with Solution

Write a program in C++ to convert a decimal number to hexadecimal number.

Pictorial Presentation:

C++ Exercises: Convert a decimal number to hexadecimal number

Sample Solution:-

C++ Code :

#include <iostream>
#include <math.h>
using namespace std;
 
int main()
{
    int dec_num, r;
    string hexdec_num="";
    char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	cout << "\n\n Convert a decimal number to hexadecimal number:\n";
	cout << "---------------------------------------------------\n";
	cout << " Input a decimal number: ";
	cin>> dec_num;
		
        while(dec_num>0)
        {
            r = dec_num % 16;
            hexdec_num = hex[r] + hexdec_num;
            dec_num = dec_num/16;
        }
        cout<<" The hexadecimal number is : "<<hexdec_num<<"\n"; 
	}

Sample Output:

 Convert a decimal number to hexadecimal number:                       
---------------------------------------------------                    
 Input a decimal number: 43                                            
 The hexadecimal number is : 2B

Flowchart:

Flowchart: Convert a decimal number to hexadecimal number

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to convert a decimal number to binary number.
Next: Write a program in C++ to convert a decimal number to octal number.

What is the difficulty level of this exercise?