﻿ C# - Convert a number in decimal to hexadecimal

# C#: Convert a number in decimal to hexadecimal

## C# Sharp For Loop: Exercise-55 with Solution

Write a program in C# Sharp to convert a decimal number to hexadecimal.

Sample Solution:-

C# Sharp Code:

``````using System;  // Importing necessary namespace

public class Exercise55  // Declaration of the Exercise55 class
{
public static void Main()  // Main method, entry point of the program
{
int decn, q, dn = 0, m, l;  // Declaration of variables
int tmp;
int s;

Console.Write("\n\n");
Console.Write("Convert a number in decimal to hexadecimal:\n");
Console.Write("---------------------------------------------");
Console.Write("\n\n");

Console.Write("Input  any Decimal number: ");
decn = Convert.ToInt32(Console.ReadLine());  // Taking user input for a decimal number
q = decn;

for (l = q; l > 0; l = l / 16)
{
tmp = l % 16;
if (tmp < 10)
tmp = tmp + 48;  // For digits less than 10, adding ASCII value of '0'
else
tmp = tmp + 55;  // For digits greater than 9, adding ASCII value of 'A'

dn = dn * 100 + tmp;  // Generating a number with two digits for each hexadecimal character
}

Console.Write("\nThe equivalent Hexadecimal Number : ");
// Reconstructing the hexadecimal number by extracting digits from the generated number
for (m = dn; m > 0; m = m / 100)
{
s = m % 100;  // Extracting two digits at a time
Console.Write("{0}", (char)s);  // Printing the character equivalent of the hexadecimal number
}

}
}
```
```

Sample Output:

```Convert a number in decimal to hexadecimal:
---------------------------------------------
Input  any Decimal number: 1015
The equivalent Hexadecimal Number : 3F7
```

Flowchart:

C# Sharp Code Editor: