C# Program to Convert Decimal to Hexadecimal
Posted by Superadmin on August 14 2022 14:31:16

C# Program to Convert Decimal to Hexadecimal

 

This is a C# Program to perform decimal to hexaDecimal conversion.

Problem Description

This C# Program Performs Decimal to HexaDecimal Conversion.

Problem Solution

Here the decimal number is first obtained from the user and Is converted to hexadecimal.

Program/Source Code

Here is source code of the C# Program to Perform Decimal to HexaDecimal Conversion. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Perform Decimal to HexaDecimal Conversion
 */
using System;
class program
{
    public static void Main()
    {
        int decimalNumber, quotient;
        int i = 1, j, temp = 0;
        char[] hexadecimalNumber = new char[100];
        char temp1;
        Console.WriteLine("Enter a Decimal Number :");
        decimalNumber = int.Parse(Console.ReadLine());
        quotient = decimalNumber;
        while (quotient != 0)
        {
            temp = quotient % 16;
            if (temp < 10)
                temp = temp + 48;
            else
                temp = temp + 55;
            temp1 = Convert.ToChar(temp);
            hexadecimalNumber[i++] = temp1;
            quotient = quotient / 16;
        }
        Console.Write("Equivalent HexaDecimal Number is ");
        for (j = i - 1; j > 0; j--)
            Console.Write(hexadecimalNumber[j]);
        Console.Read();
 
    }
}
Program Explanation

In this C# program, we are reading the decimal number using ‘decimalnumber’ variable. Decimal is a term that describes the base-10 number system. Hexadecimal is base 16 arithmetic where each digit is a value from 0 to 15, rather than the 0-9 of base 10.

 

Assign the value of ‘decimalnumber’ variable to ‘quotient’ variable. While loop is used to check the value of ‘quotient’ variable is not equal to 0. If the condition is true, then execute the statement. The ‘temp’ variable is used to compute the modulus of the value of ‘quotient’ variable by 16.

If condition statement, is used to convert integer into character. Check the value of ‘temp’ variable is equal to 0 and decrement the value of ‘j’ variable. If the condition is true, then execute the statement and print the character value of hexadecimalnum[] array character variable.

Runtime Test Cases
 
Enter a Decimal Number :
45
Equivalent HexaDecimal Number is 2D